runtests.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. #!/usr/bin/env python
  2. import argparse
  3. import atexit
  4. import copy
  5. import gc
  6. import multiprocessing
  7. import os
  8. import shutil
  9. import socket
  10. import subprocess
  11. import sys
  12. import tempfile
  13. import warnings
  14. from functools import partial
  15. from pathlib import Path
  16. try:
  17. import django
  18. except ImportError as e:
  19. raise RuntimeError(
  20. "Django module not found, reference tests/README.rst for instructions."
  21. ) from e
  22. else:
  23. from django.apps import apps
  24. from django.conf import settings
  25. from django.core.exceptions import ImproperlyConfigured
  26. from django.db import connection, connections
  27. from django.test import TestCase, TransactionTestCase
  28. from django.test.runner import _init_worker, get_max_test_processes, parallel_type
  29. from django.test.selenium import SeleniumTestCaseBase
  30. from django.test.utils import NullTimeKeeper, TimeKeeper, get_runner
  31. from django.utils.deprecation import (
  32. RemovedInDjango50Warning,
  33. RemovedInDjango51Warning,
  34. )
  35. from django.utils.log import DEFAULT_LOGGING
  36. try:
  37. import MySQLdb
  38. except ImportError:
  39. pass
  40. else:
  41. # Ignore informational warnings from QuerySet.explain().
  42. warnings.filterwarnings("ignore", r"\(1003, *", category=MySQLdb.Warning)
  43. # Make deprecation warnings errors to ensure no usage of deprecated features.
  44. warnings.simplefilter("error", RemovedInDjango50Warning)
  45. warnings.simplefilter("error", RemovedInDjango51Warning)
  46. # Make resource and runtime warning errors to ensure no usage of error prone
  47. # patterns.
  48. warnings.simplefilter("error", ResourceWarning)
  49. warnings.simplefilter("error", RuntimeWarning)
  50. # Ignore known warnings in test dependencies.
  51. warnings.filterwarnings(
  52. "ignore", "'U' mode is deprecated", DeprecationWarning, module="docutils.io"
  53. )
  54. # Reduce garbage collection frequency to improve performance. Since CPython
  55. # uses refcounting, garbage collection only collects objects with cyclic
  56. # references, which are a minority, so the garbage collection threshold can be
  57. # larger than the default threshold of 700 allocations + deallocations without
  58. # much increase in memory usage.
  59. gc.set_threshold(100_000)
  60. RUNTESTS_DIR = os.path.abspath(os.path.dirname(__file__))
  61. TEMPLATE_DIR = os.path.join(RUNTESTS_DIR, "templates")
  62. # Create a specific subdirectory for the duration of the test suite.
  63. TMPDIR = tempfile.mkdtemp(prefix="django_")
  64. # Set the TMPDIR environment variable in addition to tempfile.tempdir
  65. # so that children processes inherit it.
  66. tempfile.tempdir = os.environ["TMPDIR"] = TMPDIR
  67. # Removing the temporary TMPDIR.
  68. atexit.register(shutil.rmtree, TMPDIR)
  69. # This is a dict mapping RUNTESTS_DIR subdirectory to subdirectories of that
  70. # directory to skip when searching for test modules.
  71. SUBDIRS_TO_SKIP = {
  72. "": {"import_error_package", "test_runner_apps"},
  73. "gis_tests": {"data"},
  74. }
  75. ALWAYS_INSTALLED_APPS = [
  76. "django.contrib.contenttypes",
  77. "django.contrib.auth",
  78. "django.contrib.sites",
  79. "django.contrib.sessions",
  80. "django.contrib.messages",
  81. "django.contrib.admin.apps.SimpleAdminConfig",
  82. "django.contrib.staticfiles",
  83. ]
  84. ALWAYS_MIDDLEWARE = [
  85. "django.contrib.sessions.middleware.SessionMiddleware",
  86. "django.middleware.common.CommonMiddleware",
  87. "django.middleware.csrf.CsrfViewMiddleware",
  88. "django.contrib.auth.middleware.AuthenticationMiddleware",
  89. "django.contrib.messages.middleware.MessageMiddleware",
  90. ]
  91. # Need to add the associated contrib app to INSTALLED_APPS in some cases to
  92. # avoid "RuntimeError: Model class X doesn't declare an explicit app_label
  93. # and isn't in an application in INSTALLED_APPS."
  94. CONTRIB_TESTS_TO_APPS = {
  95. "deprecation": ["django.contrib.flatpages", "django.contrib.redirects"],
  96. "flatpages_tests": ["django.contrib.flatpages"],
  97. "redirects_tests": ["django.contrib.redirects"],
  98. }
  99. def get_test_modules(gis_enabled):
  100. """
  101. Scan the tests directory and yield the names of all test modules.
  102. The yielded names have either one dotted part like "test_runner" or, in
  103. the case of GIS tests, two dotted parts like "gis_tests.gdal_tests".
  104. """
  105. discovery_dirs = [""]
  106. if gis_enabled:
  107. # GIS tests are in nested apps
  108. discovery_dirs.append("gis_tests")
  109. else:
  110. SUBDIRS_TO_SKIP[""].add("gis_tests")
  111. for dirname in discovery_dirs:
  112. dirpath = os.path.join(RUNTESTS_DIR, dirname)
  113. subdirs_to_skip = SUBDIRS_TO_SKIP[dirname]
  114. with os.scandir(dirpath) as entries:
  115. for f in entries:
  116. if (
  117. "." in f.name
  118. or os.path.basename(f.name) in subdirs_to_skip
  119. or f.is_file()
  120. or not os.path.exists(os.path.join(f.path, "__init__.py"))
  121. ):
  122. continue
  123. test_module = f.name
  124. if dirname:
  125. test_module = dirname + "." + test_module
  126. yield test_module
  127. def get_label_module(label):
  128. """Return the top-level module part for a test label."""
  129. path = Path(label)
  130. if len(path.parts) == 1:
  131. # Interpret the label as a dotted module name.
  132. return label.split(".")[0]
  133. # Otherwise, interpret the label as a path. Check existence first to
  134. # provide a better error message than relative_to() if it doesn't exist.
  135. if not path.exists():
  136. raise RuntimeError(f"Test label path {label} does not exist")
  137. path = path.resolve()
  138. rel_path = path.relative_to(RUNTESTS_DIR)
  139. return rel_path.parts[0]
  140. def get_filtered_test_modules(start_at, start_after, gis_enabled, test_labels=None):
  141. if test_labels is None:
  142. test_labels = []
  143. # Reduce each test label to just the top-level module part.
  144. label_modules = set()
  145. for label in test_labels:
  146. test_module = get_label_module(label)
  147. label_modules.add(test_module)
  148. # It would be nice to put this validation earlier but it must come after
  149. # django.setup() so that connection.features.gis_enabled can be accessed.
  150. if "gis_tests" in label_modules and not gis_enabled:
  151. print("Aborting: A GIS database backend is required to run gis_tests.")
  152. sys.exit(1)
  153. def _module_match_label(module_name, label):
  154. # Exact or ancestor match.
  155. return module_name == label or module_name.startswith(label + ".")
  156. start_label = start_at or start_after
  157. for test_module in get_test_modules(gis_enabled):
  158. if start_label:
  159. if not _module_match_label(test_module, start_label):
  160. continue
  161. start_label = ""
  162. if not start_at:
  163. assert start_after
  164. # Skip the current one before starting.
  165. continue
  166. # If the module (or an ancestor) was named on the command line, or
  167. # no modules were named (i.e., run all), include the test module.
  168. if not test_labels or any(
  169. _module_match_label(test_module, label_module)
  170. for label_module in label_modules
  171. ):
  172. yield test_module
  173. def setup_collect_tests(start_at, start_after, test_labels=None):
  174. state = {
  175. "INSTALLED_APPS": settings.INSTALLED_APPS,
  176. "ROOT_URLCONF": getattr(settings, "ROOT_URLCONF", ""),
  177. "TEMPLATES": settings.TEMPLATES,
  178. "LANGUAGE_CODE": settings.LANGUAGE_CODE,
  179. "STATIC_URL": settings.STATIC_URL,
  180. "STATIC_ROOT": settings.STATIC_ROOT,
  181. "MIDDLEWARE": settings.MIDDLEWARE,
  182. }
  183. # Redirect some settings for the duration of these tests.
  184. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
  185. settings.ROOT_URLCONF = "urls"
  186. settings.STATIC_URL = "static/"
  187. settings.STATIC_ROOT = os.path.join(TMPDIR, "static")
  188. settings.TEMPLATES = [
  189. {
  190. "BACKEND": "django.template.backends.django.DjangoTemplates",
  191. "DIRS": [TEMPLATE_DIR],
  192. "APP_DIRS": True,
  193. "OPTIONS": {
  194. "context_processors": [
  195. "django.template.context_processors.debug",
  196. "django.template.context_processors.request",
  197. "django.contrib.auth.context_processors.auth",
  198. "django.contrib.messages.context_processors.messages",
  199. ],
  200. },
  201. }
  202. ]
  203. settings.LANGUAGE_CODE = "en"
  204. settings.SITE_ID = 1
  205. settings.MIDDLEWARE = ALWAYS_MIDDLEWARE
  206. settings.MIGRATION_MODULES = {
  207. # This lets us skip creating migrations for the test models as many of
  208. # them depend on one of the following contrib applications.
  209. "auth": None,
  210. "contenttypes": None,
  211. "sessions": None,
  212. }
  213. log_config = copy.deepcopy(DEFAULT_LOGGING)
  214. # Filter out non-error logging so we don't have to capture it in lots of
  215. # tests.
  216. log_config["loggers"]["django"]["level"] = "ERROR"
  217. settings.LOGGING = log_config
  218. settings.SILENCED_SYSTEM_CHECKS = [
  219. "fields.W342", # ForeignKey(unique=True) -> OneToOneField
  220. ]
  221. # RemovedInDjango50Warning
  222. settings.FORM_RENDERER = "django.forms.renderers.DjangoDivFormRenderer"
  223. # Load all the ALWAYS_INSTALLED_APPS.
  224. django.setup()
  225. # This flag must be evaluated after django.setup() because otherwise it can
  226. # raise AppRegistryNotReady when running gis_tests in isolation on some
  227. # backends (e.g. PostGIS).
  228. gis_enabled = connection.features.gis_enabled
  229. test_modules = list(
  230. get_filtered_test_modules(
  231. start_at,
  232. start_after,
  233. gis_enabled,
  234. test_labels=test_labels,
  235. )
  236. )
  237. return test_modules, state
  238. def teardown_collect_tests(state):
  239. # Restore the old settings.
  240. for key, value in state.items():
  241. setattr(settings, key, value)
  242. def get_installed():
  243. return [app_config.name for app_config in apps.get_app_configs()]
  244. # This function should be called only after calling django.setup(),
  245. # since it calls connection.features.gis_enabled.
  246. def get_apps_to_install(test_modules):
  247. for test_module in test_modules:
  248. if test_module in CONTRIB_TESTS_TO_APPS:
  249. yield from CONTRIB_TESTS_TO_APPS[test_module]
  250. yield test_module
  251. # Add contrib.gis to INSTALLED_APPS if needed (rather than requiring
  252. # @override_settings(INSTALLED_APPS=...) on all test cases.
  253. if connection.features.gis_enabled:
  254. yield "django.contrib.gis"
  255. def setup_run_tests(verbosity, start_at, start_after, test_labels=None):
  256. test_modules, state = setup_collect_tests(
  257. start_at, start_after, test_labels=test_labels
  258. )
  259. installed_apps = set(get_installed())
  260. for app in get_apps_to_install(test_modules):
  261. if app in installed_apps:
  262. continue
  263. if verbosity >= 2:
  264. print(f"Importing application {app}")
  265. settings.INSTALLED_APPS.append(app)
  266. installed_apps.add(app)
  267. apps.set_installed_apps(settings.INSTALLED_APPS)
  268. # Force declaring available_apps in TransactionTestCase for faster tests.
  269. def no_available_apps(self):
  270. raise Exception(
  271. "Please define available_apps in TransactionTestCase and its subclasses."
  272. )
  273. TransactionTestCase.available_apps = property(no_available_apps)
  274. TestCase.available_apps = None
  275. # Set an environment variable that other code may consult to see if
  276. # Django's own test suite is running.
  277. os.environ["RUNNING_DJANGOS_TEST_SUITE"] = "true"
  278. test_labels = test_labels or test_modules
  279. return test_labels, state
  280. def teardown_run_tests(state):
  281. teardown_collect_tests(state)
  282. # Discard the multiprocessing.util finalizer that tries to remove a
  283. # temporary directory that's already removed by this script's
  284. # atexit.register(shutil.rmtree, TMPDIR) handler. Prevents
  285. # FileNotFoundError at the end of a test run (#27890).
  286. from multiprocessing.util import _finalizer_registry
  287. _finalizer_registry.pop((-100, 0), None)
  288. del os.environ["RUNNING_DJANGOS_TEST_SUITE"]
  289. class ActionSelenium(argparse.Action):
  290. """
  291. Validate the comma-separated list of requested browsers.
  292. """
  293. def __call__(self, parser, namespace, values, option_string=None):
  294. try:
  295. import selenium # NOQA
  296. except ImportError as e:
  297. raise ImproperlyConfigured(f"Error loading selenium module: {e}")
  298. browsers = values.split(",")
  299. for browser in browsers:
  300. try:
  301. SeleniumTestCaseBase.import_webdriver(browser)
  302. except ImportError:
  303. raise argparse.ArgumentError(
  304. self, "Selenium browser specification '%s' is not valid." % browser
  305. )
  306. setattr(namespace, self.dest, browsers)
  307. def django_tests(
  308. verbosity,
  309. interactive,
  310. failfast,
  311. keepdb,
  312. reverse,
  313. test_labels,
  314. debug_sql,
  315. parallel,
  316. tags,
  317. exclude_tags,
  318. test_name_patterns,
  319. start_at,
  320. start_after,
  321. pdb,
  322. buffer,
  323. timing,
  324. shuffle,
  325. ):
  326. if parallel in {0, "auto"}:
  327. max_parallel = get_max_test_processes()
  328. else:
  329. max_parallel = parallel
  330. if verbosity >= 1:
  331. msg = "Testing against Django installed in '%s'" % os.path.dirname(
  332. django.__file__
  333. )
  334. if max_parallel > 1:
  335. msg += " with up to %d processes" % max_parallel
  336. print(msg)
  337. process_setup_args = (verbosity, start_at, start_after, test_labels)
  338. test_labels, state = setup_run_tests(*process_setup_args)
  339. # Run the test suite, including the extra validation tests.
  340. if not hasattr(settings, "TEST_RUNNER"):
  341. settings.TEST_RUNNER = "django.test.runner.DiscoverRunner"
  342. if parallel in {0, "auto"}:
  343. # This doesn't work before django.setup() on some databases.
  344. if all(conn.features.can_clone_databases for conn in connections.all()):
  345. parallel = max_parallel
  346. else:
  347. parallel = 1
  348. TestRunner = get_runner(settings)
  349. TestRunner.parallel_test_suite.init_worker = partial(
  350. _init_worker,
  351. process_setup=setup_run_tests,
  352. process_setup_args=process_setup_args,
  353. )
  354. test_runner = TestRunner(
  355. verbosity=verbosity,
  356. interactive=interactive,
  357. failfast=failfast,
  358. keepdb=keepdb,
  359. reverse=reverse,
  360. debug_sql=debug_sql,
  361. parallel=parallel,
  362. tags=tags,
  363. exclude_tags=exclude_tags,
  364. test_name_patterns=test_name_patterns,
  365. pdb=pdb,
  366. buffer=buffer,
  367. timing=timing,
  368. shuffle=shuffle,
  369. )
  370. failures = test_runner.run_tests(test_labels)
  371. teardown_run_tests(state)
  372. return failures
  373. def collect_test_modules(start_at, start_after):
  374. test_modules, state = setup_collect_tests(start_at, start_after)
  375. teardown_collect_tests(state)
  376. return test_modules
  377. def get_subprocess_args(options):
  378. subprocess_args = [sys.executable, __file__, "--settings=%s" % options.settings]
  379. if options.failfast:
  380. subprocess_args.append("--failfast")
  381. if options.verbosity:
  382. subprocess_args.append("--verbosity=%s" % options.verbosity)
  383. if not options.interactive:
  384. subprocess_args.append("--noinput")
  385. if options.tags:
  386. subprocess_args.append("--tag=%s" % options.tags)
  387. if options.exclude_tags:
  388. subprocess_args.append("--exclude_tag=%s" % options.exclude_tags)
  389. if options.shuffle is not False:
  390. if options.shuffle is None:
  391. subprocess_args.append("--shuffle")
  392. else:
  393. subprocess_args.append("--shuffle=%s" % options.shuffle)
  394. return subprocess_args
  395. def bisect_tests(bisection_label, options, test_labels, start_at, start_after):
  396. if not test_labels:
  397. test_labels = collect_test_modules(start_at, start_after)
  398. print("***** Bisecting test suite: %s" % " ".join(test_labels))
  399. # Make sure the bisection point isn't in the test list
  400. # Also remove tests that need to be run in specific combinations
  401. for label in [bisection_label, "model_inheritance_same_model_name"]:
  402. try:
  403. test_labels.remove(label)
  404. except ValueError:
  405. pass
  406. subprocess_args = get_subprocess_args(options)
  407. iteration = 1
  408. while len(test_labels) > 1:
  409. midpoint = len(test_labels) // 2
  410. test_labels_a = test_labels[:midpoint] + [bisection_label]
  411. test_labels_b = test_labels[midpoint:] + [bisection_label]
  412. print("***** Pass %da: Running the first half of the test suite" % iteration)
  413. print("***** Test labels: %s" % " ".join(test_labels_a))
  414. failures_a = subprocess.run(subprocess_args + test_labels_a)
  415. print("***** Pass %db: Running the second half of the test suite" % iteration)
  416. print("***** Test labels: %s" % " ".join(test_labels_b))
  417. print("")
  418. failures_b = subprocess.run(subprocess_args + test_labels_b)
  419. if failures_a.returncode and not failures_b.returncode:
  420. print("***** Problem found in first half. Bisecting again...")
  421. iteration += 1
  422. test_labels = test_labels_a[:-1]
  423. elif failures_b.returncode and not failures_a.returncode:
  424. print("***** Problem found in second half. Bisecting again...")
  425. iteration += 1
  426. test_labels = test_labels_b[:-1]
  427. elif failures_a.returncode and failures_b.returncode:
  428. print("***** Multiple sources of failure found")
  429. break
  430. else:
  431. print("***** No source of failure found... try pair execution (--pair)")
  432. break
  433. if len(test_labels) == 1:
  434. print("***** Source of error: %s" % test_labels[0])
  435. def paired_tests(paired_test, options, test_labels, start_at, start_after):
  436. if not test_labels:
  437. test_labels = collect_test_modules(start_at, start_after)
  438. print("***** Trying paired execution")
  439. # Make sure the constant member of the pair isn't in the test list
  440. # Also remove tests that need to be run in specific combinations
  441. for label in [paired_test, "model_inheritance_same_model_name"]:
  442. try:
  443. test_labels.remove(label)
  444. except ValueError:
  445. pass
  446. subprocess_args = get_subprocess_args(options)
  447. for i, label in enumerate(test_labels):
  448. print(
  449. "***** %d of %d: Check test pairing with %s"
  450. % (i + 1, len(test_labels), label)
  451. )
  452. failures = subprocess.call(subprocess_args + [label, paired_test])
  453. if failures:
  454. print("***** Found problem pair with %s" % label)
  455. return
  456. print("***** No problem pair found")
  457. if __name__ == "__main__":
  458. parser = argparse.ArgumentParser(description="Run the Django test suite.")
  459. parser.add_argument(
  460. "modules",
  461. nargs="*",
  462. metavar="module",
  463. help='Optional path(s) to test modules; e.g. "i18n" or '
  464. '"i18n.tests.TranslationTests.test_lazy_objects".',
  465. )
  466. parser.add_argument(
  467. "-v",
  468. "--verbosity",
  469. default=1,
  470. type=int,
  471. choices=[0, 1, 2, 3],
  472. help="Verbosity level; 0=minimal output, 1=normal output, 2=all output",
  473. )
  474. parser.add_argument(
  475. "--noinput",
  476. action="store_false",
  477. dest="interactive",
  478. help="Tells Django to NOT prompt the user for input of any kind.",
  479. )
  480. parser.add_argument(
  481. "--failfast",
  482. action="store_true",
  483. help="Tells Django to stop running the test suite after first failed test.",
  484. )
  485. parser.add_argument(
  486. "--keepdb",
  487. action="store_true",
  488. help="Tells Django to preserve the test database between runs.",
  489. )
  490. parser.add_argument(
  491. "--settings",
  492. help='Python path to settings module, e.g. "myproject.settings". If '
  493. "this isn't provided, either the DJANGO_SETTINGS_MODULE "
  494. 'environment variable or "test_sqlite" will be used.',
  495. )
  496. parser.add_argument(
  497. "--bisect",
  498. help="Bisect the test suite to discover a test that causes a test "
  499. "failure when combined with the named test.",
  500. )
  501. parser.add_argument(
  502. "--pair",
  503. help="Run the test suite in pairs with the named test to find problem pairs.",
  504. )
  505. parser.add_argument(
  506. "--shuffle",
  507. nargs="?",
  508. default=False,
  509. type=int,
  510. metavar="SEED",
  511. help=(
  512. "Shuffle the order of test cases to help check that tests are "
  513. "properly isolated."
  514. ),
  515. )
  516. parser.add_argument(
  517. "--reverse",
  518. action="store_true",
  519. help="Sort test suites and test cases in opposite order to debug "
  520. "test side effects not apparent with normal execution lineup.",
  521. )
  522. parser.add_argument(
  523. "--selenium",
  524. action=ActionSelenium,
  525. metavar="BROWSERS",
  526. help="A comma-separated list of browsers to run the Selenium tests against.",
  527. )
  528. parser.add_argument(
  529. "--headless",
  530. action="store_true",
  531. help="Run selenium tests in headless mode, if the browser supports the option.",
  532. )
  533. parser.add_argument(
  534. "--selenium-hub",
  535. help="A URL for a selenium hub instance to use in combination with --selenium.",
  536. )
  537. parser.add_argument(
  538. "--external-host",
  539. default=socket.gethostname(),
  540. help=(
  541. "The external host that can be reached by the selenium hub instance when "
  542. "running Selenium tests via Selenium Hub."
  543. ),
  544. )
  545. parser.add_argument(
  546. "--debug-sql",
  547. action="store_true",
  548. help="Turn on the SQL query logger within tests.",
  549. )
  550. # 0 is converted to "auto" or 1 later on, depending on a method used by
  551. # multiprocessing to start subprocesses and on the backend support for
  552. # cloning databases.
  553. parser.add_argument(
  554. "--parallel",
  555. nargs="?",
  556. const="auto",
  557. default=0,
  558. type=parallel_type,
  559. metavar="N",
  560. help=(
  561. 'Run tests using up to N parallel processes. Use the value "auto" '
  562. "to run one test process for each processor core."
  563. ),
  564. )
  565. parser.add_argument(
  566. "--tag",
  567. dest="tags",
  568. action="append",
  569. help="Run only tests with the specified tags. Can be used multiple times.",
  570. )
  571. parser.add_argument(
  572. "--exclude-tag",
  573. dest="exclude_tags",
  574. action="append",
  575. help="Do not run tests with the specified tag. Can be used multiple times.",
  576. )
  577. parser.add_argument(
  578. "--start-after",
  579. dest="start_after",
  580. help="Run tests starting after the specified top-level module.",
  581. )
  582. parser.add_argument(
  583. "--start-at",
  584. dest="start_at",
  585. help="Run tests starting at the specified top-level module.",
  586. )
  587. parser.add_argument(
  588. "--pdb", action="store_true", help="Runs the PDB debugger on error or failure."
  589. )
  590. parser.add_argument(
  591. "-b",
  592. "--buffer",
  593. action="store_true",
  594. help="Discard output of passing tests.",
  595. )
  596. parser.add_argument(
  597. "--timing",
  598. action="store_true",
  599. help="Output timings, including database set up and total run time.",
  600. )
  601. parser.add_argument(
  602. "-k",
  603. dest="test_name_patterns",
  604. action="append",
  605. help=(
  606. "Only run test methods and classes matching test name pattern. "
  607. "Same as unittest -k option. Can be used multiple times."
  608. ),
  609. )
  610. options = parser.parse_args()
  611. using_selenium_hub = options.selenium and options.selenium_hub
  612. if options.selenium_hub and not options.selenium:
  613. parser.error(
  614. "--selenium-hub and --external-host require --selenium to be used."
  615. )
  616. if using_selenium_hub and not options.external_host:
  617. parser.error("--selenium-hub and --external-host must be used together.")
  618. # Allow including a trailing slash on app_labels for tab completion convenience
  619. options.modules = [os.path.normpath(labels) for labels in options.modules]
  620. mutually_exclusive_options = [
  621. options.start_at,
  622. options.start_after,
  623. options.modules,
  624. ]
  625. enabled_module_options = [
  626. bool(option) for option in mutually_exclusive_options
  627. ].count(True)
  628. if enabled_module_options > 1:
  629. print(
  630. "Aborting: --start-at, --start-after, and test labels are mutually "
  631. "exclusive."
  632. )
  633. sys.exit(1)
  634. for opt_name in ["start_at", "start_after"]:
  635. opt_val = getattr(options, opt_name)
  636. if opt_val:
  637. if "." in opt_val:
  638. print(
  639. "Aborting: --%s must be a top-level module."
  640. % opt_name.replace("_", "-")
  641. )
  642. sys.exit(1)
  643. setattr(options, opt_name, os.path.normpath(opt_val))
  644. if options.settings:
  645. os.environ["DJANGO_SETTINGS_MODULE"] = options.settings
  646. else:
  647. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_sqlite")
  648. options.settings = os.environ["DJANGO_SETTINGS_MODULE"]
  649. if options.selenium:
  650. if multiprocessing.get_start_method() == "spawn" and options.parallel != 1:
  651. parser.error(
  652. "You cannot use --selenium with parallel tests on this system. "
  653. "Pass --parallel=1 to use --selenium."
  654. )
  655. if not options.tags:
  656. options.tags = ["selenium"]
  657. elif "selenium" not in options.tags:
  658. options.tags.append("selenium")
  659. if options.selenium_hub:
  660. SeleniumTestCaseBase.selenium_hub = options.selenium_hub
  661. SeleniumTestCaseBase.external_host = options.external_host
  662. SeleniumTestCaseBase.headless = options.headless
  663. SeleniumTestCaseBase.browsers = options.selenium
  664. if options.bisect:
  665. bisect_tests(
  666. options.bisect,
  667. options,
  668. options.modules,
  669. options.start_at,
  670. options.start_after,
  671. )
  672. elif options.pair:
  673. paired_tests(
  674. options.pair,
  675. options,
  676. options.modules,
  677. options.start_at,
  678. options.start_after,
  679. )
  680. else:
  681. time_keeper = TimeKeeper() if options.timing else NullTimeKeeper()
  682. with time_keeper.timed("Total run"):
  683. failures = django_tests(
  684. options.verbosity,
  685. options.interactive,
  686. options.failfast,
  687. options.keepdb,
  688. options.reverse,
  689. options.modules,
  690. options.debug_sql,
  691. options.parallel,
  692. options.tags,
  693. options.exclude_tags,
  694. getattr(options, "test_name_patterns", None),
  695. options.start_at,
  696. options.start_after,
  697. options.pdb,
  698. options.buffer,
  699. options.timing,
  700. options.shuffle,
  701. )
  702. time_keeper.print_results()
  703. if failures:
  704. sys.exit(1)