runtests.py 19 KB

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