runtests.py 22 KB

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