runtests.py 13 KB

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