runtests.py 22 KB

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