runtests.py 23 KB

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