runtests.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. #!/usr/bin/env python
  2. import atexit
  3. import copy
  4. import logging
  5. import os
  6. import shutil
  7. import subprocess
  8. import sys
  9. import tempfile
  10. import warnings
  11. from argparse import ArgumentParser
  12. import django
  13. from django.apps import apps
  14. from django.conf import settings
  15. from django.db import connection, connections
  16. from django.test import TestCase, TransactionTestCase
  17. from django.test.runner import default_test_processes
  18. from django.test.utils import get_runner
  19. from django.utils import six
  20. from django.utils._os import upath
  21. from django.utils.deprecation import (
  22. RemovedInDjango20Warning, RemovedInDjango110Warning,
  23. )
  24. from django.utils.log import DEFAULT_LOGGING
  25. warnings.simplefilter("error", RemovedInDjango110Warning)
  26. warnings.simplefilter("error", RemovedInDjango20Warning)
  27. RUNTESTS_DIR = os.path.abspath(os.path.dirname(upath(__file__)))
  28. TEMPLATE_DIR = os.path.join(RUNTESTS_DIR, 'templates')
  29. # Create a specific subdirectory for the duration of the test suite.
  30. TMPDIR = tempfile.mkdtemp(prefix='django_')
  31. # Set the TMPDIR environment variable in addition to tempfile.tempdir
  32. # so that children processes inherit it.
  33. tempfile.tempdir = os.environ['TMPDIR'] = TMPDIR
  34. # Removing the temporary TMPDIR. Ensure we pass in unicode so that it will
  35. # successfully remove temp trees containing non-ASCII filenames on Windows.
  36. # (We're assuming the temp dir name itself only contains ASCII characters.)
  37. atexit.register(shutil.rmtree, six.text_type(TMPDIR))
  38. SUBDIRS_TO_SKIP = [
  39. 'data',
  40. 'import_error_package',
  41. 'test_discovery_sample',
  42. 'test_discovery_sample2',
  43. 'test_runner_deprecation_app',
  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_CLASSES = [
  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 either isn't in an application in INSTALLED_APPS or else was imported
  64. # before its application was loaded."
  65. CONTRIB_TESTS_TO_APPS = {
  66. 'flatpages_tests': 'django.contrib.flatpages',
  67. 'redirects_tests': 'django.contrib.redirects',
  68. }
  69. def get_test_modules():
  70. modules = []
  71. discovery_paths = [
  72. (None, RUNTESTS_DIR),
  73. # GIS tests are in nested apps
  74. ('gis_tests', os.path.join(RUNTESTS_DIR, 'gis_tests')),
  75. ]
  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. if verbosity >= 1:
  89. msg = "Testing against Django installed in '%s'" % os.path.dirname(django.__file__)
  90. max_parallel = default_test_processes() if parallel == 0 else parallel
  91. if max_parallel > 1:
  92. msg += " with up to %d processes" % max_parallel
  93. print(msg)
  94. # Force declaring available_apps in TransactionTestCase for faster tests.
  95. def no_available_apps(self):
  96. raise Exception("Please define available_apps in TransactionTestCase "
  97. "and its subclasses.")
  98. TransactionTestCase.available_apps = property(no_available_apps)
  99. TestCase.available_apps = None
  100. state = {
  101. 'INSTALLED_APPS': settings.INSTALLED_APPS,
  102. 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""),
  103. 'TEMPLATES': settings.TEMPLATES,
  104. 'LANGUAGE_CODE': settings.LANGUAGE_CODE,
  105. 'STATIC_URL': settings.STATIC_URL,
  106. 'STATIC_ROOT': settings.STATIC_ROOT,
  107. 'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES,
  108. }
  109. # Redirect some settings for the duration of these tests.
  110. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
  111. settings.ROOT_URLCONF = 'urls'
  112. settings.STATIC_URL = '/static/'
  113. settings.STATIC_ROOT = os.path.join(TMPDIR, 'static')
  114. settings.TEMPLATES = [{
  115. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  116. 'DIRS': [TEMPLATE_DIR],
  117. 'APP_DIRS': True,
  118. 'OPTIONS': {
  119. 'context_processors': [
  120. 'django.template.context_processors.debug',
  121. 'django.template.context_processors.request',
  122. 'django.contrib.auth.context_processors.auth',
  123. 'django.contrib.messages.context_processors.messages',
  124. ],
  125. },
  126. }]
  127. settings.LANGUAGE_CODE = 'en'
  128. settings.SITE_ID = 1
  129. settings.MIDDLEWARE_CLASSES = ALWAYS_MIDDLEWARE_CLASSES
  130. settings.MIGRATION_MODULES = {
  131. # these 'tests.migrations' modules don't actually exist, but this lets
  132. # us skip creating migrations for the test models.
  133. 'auth': 'django.contrib.auth.tests.migrations',
  134. 'contenttypes': 'contenttypes_tests.migrations',
  135. 'sessions': 'sessions_tests.migrations',
  136. }
  137. log_config = copy.deepcopy(DEFAULT_LOGGING)
  138. # Filter out non-error logging so we don't have to capture it in lots of
  139. # tests.
  140. log_config['loggers']['django']['level'] = 'ERROR'
  141. settings.LOGGING = log_config
  142. if verbosity > 0:
  143. # Ensure any warnings captured to logging are piped through a verbose
  144. # logging handler. If any -W options were passed explicitly on command
  145. # line, warnings are not captured, and this has no effect.
  146. logger = logging.getLogger('py.warnings')
  147. handler = logging.StreamHandler()
  148. logger.addHandler(handler)
  149. warnings.filterwarnings(
  150. 'ignore',
  151. 'The GeoManager class is deprecated.',
  152. RemovedInDjango20Warning
  153. )
  154. # Load all the ALWAYS_INSTALLED_APPS.
  155. django.setup()
  156. # Load all the test model apps.
  157. test_modules = get_test_modules()
  158. # Reduce given test labels to just the app module path
  159. test_labels_set = set()
  160. for label in test_labels:
  161. bits = label.split('.')[:1]
  162. test_labels_set.add('.'.join(bits))
  163. installed_app_names = set(get_installed())
  164. for modpath, module_name in test_modules:
  165. if modpath:
  166. module_label = '.'.join([modpath, module_name])
  167. else:
  168. module_label = module_name
  169. # if the module (or an ancestor) was named on the command line, or
  170. # no modules were named (i.e., run all), import
  171. # this module and add it to INSTALLED_APPS.
  172. if not test_labels:
  173. module_found_in_labels = True
  174. else:
  175. module_found_in_labels = any(
  176. # exact match or ancestor match
  177. module_label == label or module_label.startswith(label + '.')
  178. for label in test_labels_set)
  179. if module_name in CONTRIB_TESTS_TO_APPS and module_found_in_labels:
  180. settings.INSTALLED_APPS.append(CONTRIB_TESTS_TO_APPS[module_name])
  181. if module_found_in_labels and module_label not in installed_app_names:
  182. if verbosity >= 2:
  183. print("Importing application %s" % module_name)
  184. settings.INSTALLED_APPS.append(module_label)
  185. # Add contrib.gis to INSTALLED_APPS if needed (rather than requiring
  186. # @override_settings(INSTALLED_APPS=...) on all test cases.
  187. gis = 'django.contrib.gis'
  188. if connection.features.gis_enabled and gis not in settings.INSTALLED_APPS:
  189. if verbosity >= 2:
  190. print("Importing application %s" % gis)
  191. settings.INSTALLED_APPS.append(gis)
  192. apps.set_installed_apps(settings.INSTALLED_APPS)
  193. return state
  194. def teardown(state):
  195. # Restore the old settings.
  196. for key, value in state.items():
  197. setattr(settings, key, value)
  198. def actual_test_processes(parallel):
  199. if parallel == 0:
  200. # This doesn't work before django.setup() on some databases.
  201. if all(conn.features.can_clone_databases for conn in connections.all()):
  202. return default_test_processes()
  203. else:
  204. return 1
  205. else:
  206. return parallel
  207. def django_tests(verbosity, interactive, failfast, keepdb, reverse,
  208. test_labels, debug_sql, parallel):
  209. state = setup(verbosity, test_labels, parallel)
  210. extra_tests = []
  211. # Run the test suite, including the extra validation tests.
  212. if not hasattr(settings, 'TEST_RUNNER'):
  213. settings.TEST_RUNNER = 'django.test.runner.DiscoverRunner'
  214. TestRunner = get_runner(settings)
  215. test_runner = TestRunner(
  216. verbosity=verbosity,
  217. interactive=interactive,
  218. failfast=failfast,
  219. keepdb=keepdb,
  220. reverse=reverse,
  221. debug_sql=debug_sql,
  222. parallel=actual_test_processes(parallel),
  223. )
  224. failures = test_runner.run_tests(
  225. test_labels or get_installed(),
  226. extra_tests=extra_tests,
  227. )
  228. teardown(state)
  229. return failures
  230. def bisect_tests(bisection_label, options, test_labels):
  231. state = setup(options.verbosity, test_labels)
  232. test_labels = test_labels or get_installed()
  233. print('***** Bisecting test suite: %s' % ' '.join(test_labels))
  234. # Make sure the bisection point isn't in the test list
  235. # Also remove tests that need to be run in specific combinations
  236. for label in [bisection_label, 'model_inheritance_same_model_name']:
  237. try:
  238. test_labels.remove(label)
  239. except ValueError:
  240. pass
  241. subprocess_args = [
  242. sys.executable, upath(__file__), '--settings=%s' % options.settings]
  243. if options.failfast:
  244. subprocess_args.append('--failfast')
  245. if options.verbosity:
  246. subprocess_args.append('--verbosity=%s' % options.verbosity)
  247. if not options.interactive:
  248. subprocess_args.append('--noinput')
  249. iteration = 1
  250. while len(test_labels) > 1:
  251. midpoint = len(test_labels) // 2
  252. test_labels_a = test_labels[:midpoint] + [bisection_label]
  253. test_labels_b = test_labels[midpoint:] + [bisection_label]
  254. print('***** Pass %da: Running the first half of the test suite' % iteration)
  255. print('***** Test labels: %s' % ' '.join(test_labels_a))
  256. failures_a = subprocess.call(subprocess_args + test_labels_a)
  257. print('***** Pass %db: Running the second half of the test suite' % iteration)
  258. print('***** Test labels: %s' % ' '.join(test_labels_b))
  259. print('')
  260. failures_b = subprocess.call(subprocess_args + test_labels_b)
  261. if failures_a and not failures_b:
  262. print("***** Problem found in first half. Bisecting again...")
  263. iteration = iteration + 1
  264. test_labels = test_labels_a[:-1]
  265. elif failures_b and not failures_a:
  266. print("***** Problem found in second half. Bisecting again...")
  267. iteration = iteration + 1
  268. test_labels = test_labels_b[:-1]
  269. elif failures_a and failures_b:
  270. print("***** Multiple sources of failure found")
  271. break
  272. else:
  273. print("***** No source of failure found... try pair execution (--pair)")
  274. break
  275. if len(test_labels) == 1:
  276. print("***** Source of error: %s" % test_labels[0])
  277. teardown(state)
  278. def paired_tests(paired_test, options, test_labels):
  279. state = setup(options.verbosity, test_labels)
  280. test_labels = test_labels or get_installed()
  281. print('***** Trying paired execution')
  282. # Make sure the constant member of the pair isn't in the test list
  283. # Also remove tests that need to be run in specific combinations
  284. for label in [paired_test, 'model_inheritance_same_model_name']:
  285. try:
  286. test_labels.remove(label)
  287. except ValueError:
  288. pass
  289. subprocess_args = [
  290. sys.executable, upath(__file__), '--settings=%s' % options.settings]
  291. if options.failfast:
  292. subprocess_args.append('--failfast')
  293. if options.verbosity:
  294. subprocess_args.append('--verbosity=%s' % options.verbosity)
  295. if not options.interactive:
  296. subprocess_args.append('--noinput')
  297. for i, label in enumerate(test_labels):
  298. print('***** %d of %d: Check test pairing with %s' % (
  299. i + 1, len(test_labels), label))
  300. failures = subprocess.call(subprocess_args + [label, paired_test])
  301. if failures:
  302. print('***** Found problem pair with %s' % label)
  303. return
  304. print('***** No problem pair found')
  305. teardown(state)
  306. if __name__ == "__main__":
  307. parser = ArgumentParser(description="Run the Django test suite.")
  308. parser.add_argument('modules', nargs='*', metavar='module',
  309. help='Optional path(s) to test modules; e.g. "i18n" or '
  310. '"i18n.tests.TranslationTests.test_lazy_objects".')
  311. parser.add_argument(
  312. '-v', '--verbosity', default=1, type=int, choices=[0, 1, 2, 3],
  313. help='Verbosity level; 0=minimal output, 1=normal output, 2=all output')
  314. parser.add_argument(
  315. '--noinput', action='store_false', dest='interactive', default=True,
  316. help='Tells Django to NOT prompt the user for input of any kind.')
  317. parser.add_argument(
  318. '--failfast', action='store_true', dest='failfast', default=False,
  319. help='Tells Django to stop running the test suite after first failed '
  320. 'test.')
  321. parser.add_argument(
  322. '-k', '--keepdb', action='store_true', dest='keepdb', default=False,
  323. help='Tells Django to preserve the test database between runs.')
  324. parser.add_argument(
  325. '--settings',
  326. help='Python path to settings module, e.g. "myproject.settings". If '
  327. 'this isn\'t provided, either the DJANGO_SETTINGS_MODULE '
  328. 'environment variable or "test_sqlite" will be used.')
  329. parser.add_argument('--bisect',
  330. help='Bisect the test suite to discover a test that causes a test '
  331. 'failure when combined with the named test.')
  332. parser.add_argument('--pair',
  333. help='Run the test suite in pairs with the named test to find problem '
  334. 'pairs.')
  335. parser.add_argument('--reverse', action='store_true', default=False,
  336. help='Sort test suites and test cases in opposite order to debug '
  337. 'test side effects not apparent with normal execution lineup.')
  338. parser.add_argument('--liveserver',
  339. help='Overrides the default address where the live server (used with '
  340. 'LiveServerTestCase) is expected to run from. The default value '
  341. 'is localhost:8081-8179.')
  342. parser.add_argument(
  343. '--selenium', action='store_true', dest='selenium', default=False,
  344. help='Run the Selenium tests as well (if Selenium is installed).')
  345. parser.add_argument(
  346. '--debug-sql', action='store_true', dest='debug_sql', default=False,
  347. help='Turn on the SQL query logger within tests.')
  348. parser.add_argument(
  349. '--parallel', dest='parallel', nargs='?', default=0, type=int,
  350. const=default_test_processes(),
  351. help='Run tests in parallel processes.')
  352. options = parser.parse_args()
  353. # mock is a required dependency
  354. try:
  355. from django.test import mock # NOQA
  356. except ImportError:
  357. print(
  358. "Please install test dependencies first: \n"
  359. "$ pip install -r requirements/py%s.txt" % sys.version_info.major
  360. )
  361. sys.exit(1)
  362. # Allow including a trailing slash on app_labels for tab completion convenience
  363. options.modules = [os.path.normpath(labels) for labels in options.modules]
  364. if options.settings:
  365. os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
  366. else:
  367. if "DJANGO_SETTINGS_MODULE" not in os.environ:
  368. os.environ['DJANGO_SETTINGS_MODULE'] = 'test_sqlite'
  369. options.settings = os.environ['DJANGO_SETTINGS_MODULE']
  370. if options.liveserver is not None:
  371. os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = options.liveserver
  372. if options.selenium:
  373. os.environ['DJANGO_SELENIUM_TESTS'] = '1'
  374. if options.bisect:
  375. bisect_tests(options.bisect, options, options.modules)
  376. elif options.pair:
  377. paired_tests(options.pair, options, options.modules)
  378. else:
  379. failures = django_tests(options.verbosity, options.interactive,
  380. options.failfast, options.keepdb,
  381. options.reverse, options.modules,
  382. options.debug_sql, options.parallel)
  383. if failures:
  384. sys.exit(bool(failures))