runtests.py 13 KB

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