runtests.py 13 KB

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