PageRenderTime 25ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/runtests.py

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