runtests.py 13 KB

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