runtests.py 15 KB

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