2
0

runtests.py 13 KB

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