runtests.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. #!/usr/bin/env python
  2. import argparse
  3. import atexit
  4. import copy
  5. import os
  6. import shutil
  7. import subprocess
  8. import sys
  9. import tempfile
  10. import warnings
  11. import django
  12. from django.apps import apps
  13. from django.conf import settings
  14. from django.db import connection, connections
  15. from django.test import TestCase, TransactionTestCase
  16. from django.test.runner import default_test_processes
  17. from django.test.selenium import SeleniumTestCaseBase
  18. from django.test.utils import get_runner
  19. from django.utils.deprecation import (
  20. RemovedInDjango21Warning, RemovedInDjango30Warning,
  21. )
  22. from django.utils.log import DEFAULT_LOGGING
  23. # Make deprecation warnings errors to ensure no usage of deprecated features.
  24. warnings.simplefilter("error", RemovedInDjango30Warning)
  25. warnings.simplefilter("error", RemovedInDjango21Warning)
  26. # Make runtime warning errors to ensure no usage of error prone patterns.
  27. warnings.simplefilter("error", RuntimeWarning)
  28. # Ignore known warnings in test dependencies.
  29. warnings.filterwarnings("ignore", "'U' mode is deprecated", DeprecationWarning, module='docutils.io')
  30. RUNTESTS_DIR = os.path.abspath(os.path.dirname(__file__))
  31. TEMPLATE_DIR = os.path.join(RUNTESTS_DIR, 'templates')
  32. # Create a specific subdirectory for the duration of the test suite.
  33. TMPDIR = tempfile.mkdtemp(prefix='django_')
  34. # Set the TMPDIR environment variable in addition to tempfile.tempdir
  35. # so that children processes inherit it.
  36. tempfile.tempdir = os.environ['TMPDIR'] = TMPDIR
  37. # Removing the temporary TMPDIR.
  38. atexit.register(shutil.rmtree, TMPDIR)
  39. SUBDIRS_TO_SKIP = [
  40. 'data',
  41. 'import_error_package',
  42. 'test_discovery_sample',
  43. 'test_discovery_sample2',
  44. ]
  45. ALWAYS_INSTALLED_APPS = [
  46. 'django.contrib.contenttypes',
  47. 'django.contrib.auth',
  48. 'django.contrib.sites',
  49. 'django.contrib.sessions',
  50. 'django.contrib.messages',
  51. 'django.contrib.admin.apps.SimpleAdminConfig',
  52. 'django.contrib.staticfiles',
  53. ]
  54. ALWAYS_MIDDLEWARE = [
  55. 'django.contrib.sessions.middleware.SessionMiddleware',
  56. 'django.middleware.common.CommonMiddleware',
  57. 'django.middleware.csrf.CsrfViewMiddleware',
  58. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  59. 'django.contrib.messages.middleware.MessageMiddleware',
  60. ]
  61. # Need to add the associated contrib app to INSTALLED_APPS in some cases to
  62. # avoid "RuntimeError: Model class X doesn't declare an explicit app_label
  63. # and isn't in an application in INSTALLED_APPS."
  64. CONTRIB_TESTS_TO_APPS = {
  65. 'flatpages_tests': 'django.contrib.flatpages',
  66. 'redirects_tests': 'django.contrib.redirects',
  67. }
  68. def get_test_modules():
  69. modules = []
  70. discovery_paths = [(None, RUNTESTS_DIR)]
  71. if connection.features.gis_enabled:
  72. # GIS tests are in nested apps
  73. discovery_paths.append(('gis_tests', os.path.join(RUNTESTS_DIR, 'gis_tests')))
  74. else:
  75. SUBDIRS_TO_SKIP.append('gis_tests')
  76. for modpath, dirpath in discovery_paths:
  77. for f in os.listdir(dirpath):
  78. if ('.' in f or
  79. os.path.basename(f) in SUBDIRS_TO_SKIP or
  80. os.path.isfile(f) or
  81. not os.path.exists(os.path.join(dirpath, f, '__init__.py'))):
  82. continue
  83. modules.append((modpath, f))
  84. return modules
  85. def get_installed():
  86. return [app_config.name for app_config in apps.get_app_configs()]
  87. def setup(verbosity, test_labels, parallel):
  88. # Reduce the given test labels to just the app module path.
  89. test_labels_set = set()
  90. for label in test_labels:
  91. bits = label.split('.')[:1]
  92. test_labels_set.add('.'.join(bits))
  93. if verbosity >= 1:
  94. msg = "Testing against Django installed in '%s'" % os.path.dirname(django.__file__)
  95. max_parallel = default_test_processes() if parallel == 0 else parallel
  96. if max_parallel > 1:
  97. msg += " with up to %d processes" % max_parallel
  98. print(msg)
  99. # Force declaring available_apps in TransactionTestCase for faster tests.
  100. def no_available_apps(self):
  101. raise Exception("Please define available_apps in TransactionTestCase "
  102. "and its subclasses.")
  103. TransactionTestCase.available_apps = property(no_available_apps)
  104. TestCase.available_apps = None
  105. state = {
  106. 'INSTALLED_APPS': settings.INSTALLED_APPS,
  107. 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""),
  108. 'TEMPLATES': settings.TEMPLATES,
  109. 'LANGUAGE_CODE': settings.LANGUAGE_CODE,
  110. 'STATIC_URL': settings.STATIC_URL,
  111. 'STATIC_ROOT': settings.STATIC_ROOT,
  112. 'MIDDLEWARE': settings.MIDDLEWARE,
  113. }
  114. # Redirect some settings for the duration of these tests.
  115. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
  116. settings.ROOT_URLCONF = 'urls'
  117. settings.STATIC_URL = '/static/'
  118. settings.STATIC_ROOT = os.path.join(TMPDIR, 'static')
  119. settings.TEMPLATES = [{
  120. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  121. 'DIRS': [TEMPLATE_DIR],
  122. 'APP_DIRS': True,
  123. 'OPTIONS': {
  124. 'context_processors': [
  125. 'django.template.context_processors.debug',
  126. 'django.template.context_processors.request',
  127. 'django.contrib.auth.context_processors.auth',
  128. 'django.contrib.messages.context_processors.messages',
  129. ],
  130. },
  131. }]
  132. settings.LANGUAGE_CODE = 'en'
  133. settings.SITE_ID = 1
  134. settings.MIDDLEWARE = ALWAYS_MIDDLEWARE
  135. settings.MIGRATION_MODULES = {
  136. # This lets us skip creating migrations for the test models as many of
  137. # them depend on one of the following contrib applications.
  138. 'auth': None,
  139. 'contenttypes': None,
  140. 'sessions': None,
  141. }
  142. log_config = copy.deepcopy(DEFAULT_LOGGING)
  143. # Filter out non-error logging so we don't have to capture it in lots of
  144. # tests.
  145. log_config['loggers']['django']['level'] = 'ERROR'
  146. settings.LOGGING = log_config
  147. settings.SILENCED_SYSTEM_CHECKS = [
  148. 'fields.W342', # ForeignKey(unique=True) -> OneToOneField
  149. ]
  150. # Load all the ALWAYS_INSTALLED_APPS.
  151. django.setup()
  152. # It would be nice to put this validation earlier but it must come after
  153. # django.setup() so that connection.features.gis_enabled can be accessed
  154. # without raising AppRegistryNotReady when running gis_tests in isolation
  155. # on some backends (e.g. PostGIS).
  156. if 'gis_tests' in test_labels_set and not connection.features.gis_enabled:
  157. print('Aborting: A GIS database backend is required to run gis_tests.')
  158. sys.exit(1)
  159. # Load all the test model apps.
  160. test_modules = get_test_modules()
  161. installed_app_names = set(get_installed())
  162. for modpath, module_name in test_modules:
  163. if modpath:
  164. module_label = modpath + '.' + module_name
  165. else:
  166. module_label = module_name
  167. # if the module (or an ancestor) was named on the command line, or
  168. # no modules were named (i.e., run all), import
  169. # this module and add it to INSTALLED_APPS.
  170. if not test_labels:
  171. module_found_in_labels = True
  172. else:
  173. module_found_in_labels = any(
  174. # exact match or ancestor match
  175. module_label == label or module_label.startswith(label + '.')
  176. for label in test_labels_set)
  177. if module_name in CONTRIB_TESTS_TO_APPS and module_found_in_labels:
  178. settings.INSTALLED_APPS.append(CONTRIB_TESTS_TO_APPS[module_name])
  179. if module_found_in_labels and module_label not in installed_app_names:
  180. if verbosity >= 2:
  181. print("Importing application %s" % module_name)
  182. settings.INSTALLED_APPS.append(module_label)
  183. # Add contrib.gis to INSTALLED_APPS if needed (rather than requiring
  184. # @override_settings(INSTALLED_APPS=...) on all test cases.
  185. gis = 'django.contrib.gis'
  186. if connection.features.gis_enabled and gis not in settings.INSTALLED_APPS:
  187. if verbosity >= 2:
  188. print("Importing application %s" % gis)
  189. settings.INSTALLED_APPS.append(gis)
  190. apps.set_installed_apps(settings.INSTALLED_APPS)
  191. return state
  192. def teardown(state):
  193. # Restore the old settings.
  194. for key, value in state.items():
  195. setattr(settings, key, value)
  196. # Discard the multiprocessing.util finalizer that tries to remove a
  197. # temporary directory that's already removed by this script's
  198. # atexit.register(shutil.rmtree, TMPDIR) handler. Prevents
  199. # FileNotFoundError at the end of a test run on Python 3.6+ (#27890).
  200. from multiprocessing.util import _finalizer_registry
  201. _finalizer_registry.pop((-100, 0), None)
  202. def actual_test_processes(parallel):
  203. if parallel == 0:
  204. # This doesn't work before django.setup() on some databases.
  205. if all(conn.features.can_clone_databases for conn in connections.all()):
  206. return default_test_processes()
  207. else:
  208. return 1
  209. else:
  210. return parallel
  211. class ActionSelenium(argparse.Action):
  212. """
  213. Validate the comma-separated list of requested browsers.
  214. """
  215. def __call__(self, parser, namespace, values, option_string=None):
  216. browsers = values.split(',')
  217. for browser in browsers:
  218. try:
  219. SeleniumTestCaseBase.import_webdriver(browser)
  220. except ImportError:
  221. raise argparse.ArgumentError(self, "Selenium browser specification '%s' is not valid." % browser)
  222. setattr(namespace, self.dest, browsers)
  223. def django_tests(verbosity, interactive, failfast, keepdb, reverse,
  224. test_labels, debug_sql, parallel, tags, exclude_tags):
  225. state = setup(verbosity, test_labels, parallel)
  226. extra_tests = []
  227. # Run the test suite, including the extra validation tests.
  228. if not hasattr(settings, 'TEST_RUNNER'):
  229. settings.TEST_RUNNER = 'django.test.runner.DiscoverRunner'
  230. TestRunner = get_runner(settings)
  231. test_runner = TestRunner(
  232. verbosity=verbosity,
  233. interactive=interactive,
  234. failfast=failfast,
  235. keepdb=keepdb,
  236. reverse=reverse,
  237. debug_sql=debug_sql,
  238. parallel=actual_test_processes(parallel),
  239. tags=tags,
  240. exclude_tags=exclude_tags,
  241. )
  242. failures = test_runner.run_tests(
  243. test_labels or get_installed(),
  244. extra_tests=extra_tests,
  245. )
  246. teardown(state)
  247. return failures
  248. def get_subprocess_args(options):
  249. subprocess_args = [
  250. sys.executable, __file__, '--settings=%s' % options.settings
  251. ]
  252. if options.failfast:
  253. subprocess_args.append('--failfast')
  254. if options.verbosity:
  255. subprocess_args.append('--verbosity=%s' % options.verbosity)
  256. if not options.interactive:
  257. subprocess_args.append('--noinput')
  258. if options.tags:
  259. subprocess_args.append('--tag=%s' % options.tags)
  260. if options.exclude_tags:
  261. subprocess_args.append('--exclude_tag=%s' % options.exclude_tags)
  262. return subprocess_args
  263. def bisect_tests(bisection_label, options, test_labels, parallel):
  264. state = setup(options.verbosity, test_labels, parallel)
  265. test_labels = test_labels or get_installed()
  266. print('***** Bisecting test suite: %s' % ' '.join(test_labels))
  267. # Make sure the bisection point isn't in the test list
  268. # Also remove tests that need to be run in specific combinations
  269. for label in [bisection_label, 'model_inheritance_same_model_name']:
  270. try:
  271. test_labels.remove(label)
  272. except ValueError:
  273. pass
  274. subprocess_args = get_subprocess_args(options)
  275. iteration = 1
  276. while len(test_labels) > 1:
  277. midpoint = len(test_labels) // 2
  278. test_labels_a = test_labels[:midpoint] + [bisection_label]
  279. test_labels_b = test_labels[midpoint:] + [bisection_label]
  280. print('***** Pass %da: Running the first half of the test suite' % iteration)
  281. print('***** Test labels: %s' % ' '.join(test_labels_a))
  282. failures_a = subprocess.call(subprocess_args + test_labels_a)
  283. print('***** Pass %db: Running the second half of the test suite' % iteration)
  284. print('***** Test labels: %s' % ' '.join(test_labels_b))
  285. print('')
  286. failures_b = subprocess.call(subprocess_args + test_labels_b)
  287. if failures_a and not failures_b:
  288. print("***** Problem found in first half. Bisecting again...")
  289. iteration += 1
  290. test_labels = test_labels_a[:-1]
  291. elif failures_b and not failures_a:
  292. print("***** Problem found in second half. Bisecting again...")
  293. iteration += 1
  294. test_labels = test_labels_b[:-1]
  295. elif failures_a and failures_b:
  296. print("***** Multiple sources of failure found")
  297. break
  298. else:
  299. print("***** No source of failure found... try pair execution (--pair)")
  300. break
  301. if len(test_labels) == 1:
  302. print("***** Source of error: %s" % test_labels[0])
  303. teardown(state)
  304. def paired_tests(paired_test, options, test_labels, parallel):
  305. state = setup(options.verbosity, test_labels, parallel)
  306. test_labels = test_labels or get_installed()
  307. print('***** Trying paired execution')
  308. # Make sure the constant member of the pair isn't in the test list
  309. # Also remove tests that need to be run in specific combinations
  310. for label in [paired_test, 'model_inheritance_same_model_name']:
  311. try:
  312. test_labels.remove(label)
  313. except ValueError:
  314. pass
  315. subprocess_args = get_subprocess_args(options)
  316. for i, label in enumerate(test_labels):
  317. print('***** %d of %d: Check test pairing with %s' % (
  318. i + 1, len(test_labels), label))
  319. failures = subprocess.call(subprocess_args + [label, paired_test])
  320. if failures:
  321. print('***** Found problem pair with %s' % label)
  322. return
  323. print('***** No problem pair found')
  324. teardown(state)
  325. if __name__ == "__main__":
  326. parser = argparse.ArgumentParser(description="Run the Django test suite.")
  327. parser.add_argument(
  328. 'modules', nargs='*', metavar='module',
  329. help='Optional path(s) to test modules; e.g. "i18n" or '
  330. '"i18n.tests.TranslationTests.test_lazy_objects".',
  331. )
  332. parser.add_argument(
  333. '-v', '--verbosity', default=1, type=int, choices=[0, 1, 2, 3],
  334. help='Verbosity level; 0=minimal output, 1=normal output, 2=all output',
  335. )
  336. parser.add_argument(
  337. '--noinput', action='store_false', dest='interactive',
  338. help='Tells Django to NOT prompt the user for input of any kind.',
  339. )
  340. parser.add_argument(
  341. '--failfast', action='store_true', dest='failfast',
  342. help='Tells Django to stop running the test suite after first failed test.',
  343. )
  344. parser.add_argument(
  345. '-k', '--keepdb', action='store_true', dest='keepdb',
  346. help='Tells Django to preserve the test database between runs.',
  347. )
  348. parser.add_argument(
  349. '--settings',
  350. help='Python path to settings module, e.g. "myproject.settings". If '
  351. 'this isn\'t provided, either the DJANGO_SETTINGS_MODULE '
  352. 'environment variable or "test_sqlite" will be used.',
  353. )
  354. parser.add_argument(
  355. '--bisect',
  356. help='Bisect the test suite to discover a test that causes a test '
  357. 'failure when combined with the named test.',
  358. )
  359. parser.add_argument(
  360. '--pair',
  361. help='Run the test suite in pairs with the named test to find problem pairs.',
  362. )
  363. parser.add_argument(
  364. '--reverse', action='store_true',
  365. help='Sort test suites and test cases in opposite order to debug '
  366. 'test side effects not apparent with normal execution lineup.',
  367. )
  368. parser.add_argument(
  369. '--selenium', dest='selenium', action=ActionSelenium, metavar='BROWSERS',
  370. help='A comma-separated list of browsers to run the Selenium tests against.',
  371. )
  372. parser.add_argument(
  373. '--debug-sql', action='store_true', dest='debug_sql',
  374. help='Turn on the SQL query logger within tests.',
  375. )
  376. parser.add_argument(
  377. '--parallel', dest='parallel', nargs='?', default=0, type=int,
  378. const=default_test_processes(), metavar='N',
  379. help='Run tests using up to N parallel processes.',
  380. )
  381. parser.add_argument(
  382. '--tag', dest='tags', action='append',
  383. help='Run only tests with the specified tags. Can be used multiple times.',
  384. )
  385. parser.add_argument(
  386. '--exclude-tag', dest='exclude_tags', action='append',
  387. help='Do not run tests with the specified tag. Can be used multiple times.',
  388. )
  389. options = parser.parse_args()
  390. # Allow including a trailing slash on app_labels for tab completion convenience
  391. options.modules = [os.path.normpath(labels) for labels in options.modules]
  392. if options.settings:
  393. os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
  394. else:
  395. if "DJANGO_SETTINGS_MODULE" not in os.environ:
  396. os.environ['DJANGO_SETTINGS_MODULE'] = 'test_sqlite'
  397. options.settings = os.environ['DJANGO_SETTINGS_MODULE']
  398. if options.selenium:
  399. if not options.tags:
  400. options.tags = ['selenium']
  401. elif 'selenium' not in options.tags:
  402. options.tags.append('selenium')
  403. SeleniumTestCaseBase.browsers = options.selenium
  404. if options.bisect:
  405. bisect_tests(options.bisect, options, options.modules, options.parallel)
  406. elif options.pair:
  407. paired_tests(options.pair, options, options.modules, options.parallel)
  408. else:
  409. failures = django_tests(
  410. options.verbosity, options.interactive, options.failfast,
  411. options.keepdb, options.reverse, options.modules,
  412. options.debug_sql, options.parallel, options.tags,
  413. options.exclude_tags,
  414. )
  415. if failures:
  416. sys.exit(1)