runtests.py 14 KB

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