runtests.py 27 KB

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