runtests.py 16 KB

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