runtests.py 16 KB

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