2
0

runtests.py 13 KB

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