runtests.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. #!/usr/bin/env python
  2. import os
  3. import shutil
  4. import subprocess
  5. import sys
  6. import tempfile
  7. import warnings
  8. from django import contrib
  9. # databrowse is deprecated, but we still want to run its tests
  10. warnings.filterwarnings('ignore', "The Databrowse contrib app is deprecated",
  11. DeprecationWarning, 'django.contrib.databrowse')
  12. CONTRIB_DIR_NAME = 'django.contrib'
  13. MODEL_TESTS_DIR_NAME = 'modeltests'
  14. REGRESSION_TESTS_DIR_NAME = 'regressiontests'
  15. TEST_TEMPLATE_DIR = 'templates'
  16. RUNTESTS_DIR = os.path.dirname(__file__)
  17. CONTRIB_DIR = os.path.dirname(contrib.__file__)
  18. MODEL_TEST_DIR = os.path.join(RUNTESTS_DIR, MODEL_TESTS_DIR_NAME)
  19. REGRESSION_TEST_DIR = os.path.join(RUNTESTS_DIR, REGRESSION_TESTS_DIR_NAME)
  20. TEMP_DIR = tempfile.mkdtemp(prefix='django_')
  21. os.environ['DJANGO_TEST_TEMP_DIR'] = TEMP_DIR
  22. REGRESSION_SUBDIRS_TO_SKIP = []
  23. ALWAYS_INSTALLED_APPS = [
  24. 'django.contrib.contenttypes',
  25. 'django.contrib.auth',
  26. 'django.contrib.sites',
  27. 'django.contrib.flatpages',
  28. 'django.contrib.redirects',
  29. 'django.contrib.sessions',
  30. 'django.contrib.messages',
  31. 'django.contrib.comments',
  32. 'django.contrib.admin',
  33. 'django.contrib.admindocs',
  34. 'django.contrib.databrowse',
  35. 'django.contrib.staticfiles',
  36. 'django.contrib.humanize',
  37. 'regressiontests.staticfiles_tests',
  38. 'regressiontests.staticfiles_tests.apps.test',
  39. 'regressiontests.staticfiles_tests.apps.no_label',
  40. ]
  41. def geodjango(settings):
  42. # All databases must have spatial backends to run GeoDjango tests.
  43. spatial_dbs = [name for name, db_dict in settings.DATABASES.items()
  44. if db_dict['ENGINE'].startswith('django.contrib.gis')]
  45. return len(spatial_dbs) == len(settings.DATABASES)
  46. def get_test_modules():
  47. modules = []
  48. for loc, dirpath in (
  49. (MODEL_TESTS_DIR_NAME, MODEL_TEST_DIR),
  50. (REGRESSION_TESTS_DIR_NAME, REGRESSION_TEST_DIR),
  51. (CONTRIB_DIR_NAME, CONTRIB_DIR)):
  52. for f in os.listdir(dirpath):
  53. if (f.startswith('__init__') or
  54. f.startswith('.') or
  55. f == '__pycache__' or
  56. f.startswith('sql') or
  57. os.path.basename(f) in REGRESSION_SUBDIRS_TO_SKIP):
  58. continue
  59. modules.append((loc, f))
  60. return modules
  61. def setup(verbosity, test_labels):
  62. from django.conf import settings
  63. state = {
  64. 'INSTALLED_APPS': settings.INSTALLED_APPS,
  65. 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""),
  66. 'TEMPLATE_DIRS': settings.TEMPLATE_DIRS,
  67. 'USE_I18N': settings.USE_I18N,
  68. 'LOGIN_URL': settings.LOGIN_URL,
  69. 'LANGUAGE_CODE': settings.LANGUAGE_CODE,
  70. 'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES,
  71. 'STATIC_URL': settings.STATIC_URL,
  72. 'STATIC_ROOT': settings.STATIC_ROOT,
  73. }
  74. # Redirect some settings for the duration of these tests.
  75. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
  76. settings.ROOT_URLCONF = 'urls'
  77. settings.STATIC_URL = '/static/'
  78. settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static')
  79. settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR),)
  80. settings.USE_I18N = True
  81. settings.LANGUAGE_CODE = 'en'
  82. settings.LOGIN_URL = '/accounts/login/'
  83. settings.MIDDLEWARE_CLASSES = (
  84. 'django.contrib.sessions.middleware.SessionMiddleware',
  85. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  86. 'django.contrib.messages.middleware.MessageMiddleware',
  87. 'django.middleware.common.CommonMiddleware',
  88. )
  89. settings.SITE_ID = 1
  90. # For testing comment-utils, we require the MANAGERS attribute
  91. # to be set, so that a test email is sent out which we catch
  92. # in our tests.
  93. settings.MANAGERS = ("admin@djangoproject.com",)
  94. # Load all the ALWAYS_INSTALLED_APPS.
  95. # (This import statement is intentionally delayed until after we
  96. # access settings because of the USE_I18N dependency.)
  97. from django.db.models.loading import get_apps, load_app
  98. get_apps()
  99. # Load all the test model apps.
  100. test_labels_set = set([label.split('.')[0] for label in test_labels])
  101. test_modules = get_test_modules()
  102. # If GeoDjango, then we'll want to add in the test applications
  103. # that are a part of its test suite.
  104. if geodjango(settings):
  105. from django.contrib.gis.tests import geo_apps
  106. test_modules.extend(geo_apps(runtests=True))
  107. settings.INSTALLED_APPS.extend(['django.contrib.gis', 'django.contrib.sitemaps'])
  108. for module_dir, module_name in test_modules:
  109. module_label = '.'.join([module_dir, module_name])
  110. # if the module was named on the command line, or
  111. # no modules were named (i.e., run all), import
  112. # this module and add it to the list to test.
  113. if not test_labels or module_name in test_labels_set:
  114. if verbosity >= 2:
  115. print("Importing application %s" % module_name)
  116. mod = load_app(module_label)
  117. if mod:
  118. if module_label not in settings.INSTALLED_APPS:
  119. settings.INSTALLED_APPS.append(module_label)
  120. return state
  121. def teardown(state):
  122. from django.conf import settings
  123. # Removing the temporary TEMP_DIR. Ensure we pass in unicode
  124. # so that it will successfully remove temp trees containing
  125. # non-ASCII filenames on Windows. (We're assuming the temp dir
  126. # name itself does not contain non-ASCII characters.)
  127. shutil.rmtree(unicode(TEMP_DIR))
  128. # Restore the old settings.
  129. for key, value in state.items():
  130. setattr(settings, key, value)
  131. def django_tests(verbosity, interactive, failfast, test_labels):
  132. from django.conf import settings
  133. state = setup(verbosity, test_labels)
  134. extra_tests = []
  135. # If GeoDjango is used, add it's tests that aren't a part of
  136. # an application (e.g., GEOS, GDAL, Distance objects).
  137. if geodjango(settings) and (not test_labels or 'gis' in test_labels):
  138. from django.contrib.gis.tests import geodjango_suite
  139. extra_tests.append(geodjango_suite(apps=False))
  140. # Run the test suite, including the extra validation tests.
  141. from django.test.utils import get_runner
  142. if not hasattr(settings, 'TEST_RUNNER'):
  143. settings.TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
  144. TestRunner = get_runner(settings)
  145. test_runner = TestRunner(verbosity=verbosity, interactive=interactive,
  146. failfast=failfast)
  147. failures = test_runner.run_tests(test_labels, extra_tests=extra_tests)
  148. teardown(state)
  149. return failures
  150. def bisect_tests(bisection_label, options, test_labels):
  151. state = setup(int(options.verbosity), test_labels)
  152. if not test_labels:
  153. # Get the full list of test labels to use for bisection
  154. from django.db.models.loading import get_apps
  155. test_labels = [app.__name__.split('.')[-2] for app in get_apps()]
  156. print('***** Bisecting test suite: %s' % ' '.join(test_labels))
  157. # Make sure the bisection point isn't in the test list
  158. # Also remove tests that need to be run in specific combinations
  159. for label in [bisection_label, 'model_inheritance_same_model_name']:
  160. try:
  161. test_labels.remove(label)
  162. except ValueError:
  163. pass
  164. subprocess_args = [
  165. sys.executable, __file__, '--settings=%s' % options.settings]
  166. if options.failfast:
  167. subprocess_args.append('--failfast')
  168. if options.verbosity:
  169. subprocess_args.append('--verbosity=%s' % options.verbosity)
  170. if not options.interactive:
  171. subprocess_args.append('--noinput')
  172. iteration = 1
  173. while len(test_labels) > 1:
  174. midpoint = len(test_labels)/2
  175. test_labels_a = test_labels[:midpoint] + [bisection_label]
  176. test_labels_b = test_labels[midpoint:] + [bisection_label]
  177. print('***** Pass %da: Running the first half of the test suite' % iteration)
  178. print('***** Test labels: %s' % ' '.join(test_labels_a))
  179. failures_a = subprocess.call(subprocess_args + test_labels_a)
  180. print('***** Pass %db: Running the second half of the test suite' % iteration)
  181. print('***** Test labels: %s' % ' '.join(test_labels_b))
  182. print('')
  183. failures_b = subprocess.call(subprocess_args + test_labels_b)
  184. if failures_a and not failures_b:
  185. print("***** Problem found in first half. Bisecting again...")
  186. iteration = iteration + 1
  187. test_labels = test_labels_a[:-1]
  188. elif failures_b and not failures_a:
  189. print("***** Problem found in second half. Bisecting again...")
  190. iteration = iteration + 1
  191. test_labels = test_labels_b[:-1]
  192. elif failures_a and failures_b:
  193. print("***** Multiple sources of failure found")
  194. break
  195. else:
  196. print("***** No source of failure found... try pair execution (--pair)")
  197. break
  198. if len(test_labels) == 1:
  199. print("***** Source of error: %s" % test_labels[0])
  200. teardown(state)
  201. def paired_tests(paired_test, options, test_labels):
  202. state = setup(int(options.verbosity), test_labels)
  203. if not test_labels:
  204. print("")
  205. # Get the full list of test labels to use for bisection
  206. from django.db.models.loading import get_apps
  207. test_labels = [app.__name__.split('.')[-2] for app in get_apps()]
  208. print('***** Trying paired execution')
  209. # Make sure the constant member of the pair isn't in the test list
  210. # Also remove tests that need to be run in specific combinations
  211. for label in [paired_test, 'model_inheritance_same_model_name']:
  212. try:
  213. test_labels.remove(label)
  214. except ValueError:
  215. pass
  216. subprocess_args = [
  217. sys.executable, __file__, '--settings=%s' % options.settings]
  218. if options.failfast:
  219. subprocess_args.append('--failfast')
  220. if options.verbosity:
  221. subprocess_args.append('--verbosity=%s' % options.verbosity)
  222. if not options.interactive:
  223. subprocess_args.append('--noinput')
  224. for i, label in enumerate(test_labels):
  225. print('***** %d of %d: Check test pairing with %s' % (
  226. i + 1, len(test_labels), label))
  227. failures = subprocess.call(subprocess_args + [label, paired_test])
  228. if failures:
  229. print('***** Found problem pair with %s' % label)
  230. return
  231. print('***** No problem pair found')
  232. teardown(state)
  233. if __name__ == "__main__":
  234. from optparse import OptionParser
  235. usage = "%prog [options] [module module module ...]"
  236. parser = OptionParser(usage=usage)
  237. parser.add_option(
  238. '-v','--verbosity', action='store', dest='verbosity', default='1',
  239. type='choice', choices=['0', '1', '2', '3'],
  240. help='Verbosity level; 0=minimal output, 1=normal output, 2=all '
  241. 'output')
  242. parser.add_option(
  243. '--noinput', action='store_false', dest='interactive', default=True,
  244. help='Tells Django to NOT prompt the user for input of any kind.')
  245. parser.add_option(
  246. '--failfast', action='store_true', dest='failfast', default=False,
  247. help='Tells Django to stop running the test suite after first failed '
  248. 'test.')
  249. parser.add_option(
  250. '--settings',
  251. help='Python path to settings module, e.g. "myproject.settings". If '
  252. 'this isn\'t provided, the DJANGO_SETTINGS_MODULE environment '
  253. 'variable will be used.')
  254. parser.add_option(
  255. '--bisect', action='store', dest='bisect', default=None,
  256. help='Bisect the test suite to discover a test that causes a test '
  257. 'failure when combined with the named test.')
  258. parser.add_option(
  259. '--pair', action='store', dest='pair', default=None,
  260. help='Run the test suite in pairs with the named test to find problem '
  261. 'pairs.')
  262. parser.add_option(
  263. '--liveserver', action='store', dest='liveserver', default=None,
  264. help='Overrides the default address where the live server (used with '
  265. 'LiveServerTestCase) is expected to run from. The default value '
  266. 'is localhost:8081.'),
  267. options, args = parser.parse_args()
  268. if options.settings:
  269. os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
  270. elif "DJANGO_SETTINGS_MODULE" not in os.environ:
  271. parser.error("DJANGO_SETTINGS_MODULE is not set in the environment. "
  272. "Set it or use --settings.")
  273. else:
  274. options.settings = os.environ['DJANGO_SETTINGS_MODULE']
  275. if options.liveserver is not None:
  276. os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = options.liveserver
  277. if options.bisect:
  278. bisect_tests(options.bisect, options, args)
  279. elif options.pair:
  280. paired_tests(options.pair, options, args)
  281. else:
  282. failures = django_tests(int(options.verbosity), options.interactive,
  283. options.failfast, args)
  284. if failures:
  285. sys.exit(bool(failures))