runtests.py 26 KB

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