PageRenderTime 42ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/django/branches/soc2010/app-loading/tests/runtests.py

https://bitbucket.org/mirror/django/
Python | 201 lines | 180 code | 17 blank | 4 comment | 20 complexity | 8aeb8168a28644884e16efeaa8c66a98 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. #!/usr/bin/env python
  2. import os, sys, traceback
  3. import unittest
  4. import django.contrib as contrib
  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. ]
  25. def get_test_models():
  26. models = []
  27. for loc, dirpath in (MODEL_TESTS_DIR_NAME, MODEL_TEST_DIR), (REGRESSION_TESTS_DIR_NAME, REGRESSION_TEST_DIR), (CONTRIB_DIR_NAME, CONTRIB_DIR):
  28. for f in os.listdir(dirpath):
  29. if f.startswith('__init__') or f.startswith('.') or \
  30. f.startswith('sql') or f.startswith('invalid') or \
  31. os.path.basename(f) in REGRESSION_SUBDIRS_TO_SKIP:
  32. continue
  33. models.append((loc, f))
  34. return models
  35. def get_invalid_models():
  36. models = []
  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 f.startswith('sql'):
  40. continue
  41. if f.startswith('invalid'):
  42. models.append((loc, f))
  43. return models
  44. class InvalidModelTestCase(unittest.TestCase):
  45. def __init__(self, model_label):
  46. unittest.TestCase.__init__(self)
  47. self.model_label = model_label
  48. def runTest(self):
  49. from django.core.management.validation import get_validation_errors
  50. from django.db.models.loading import load_app
  51. from cStringIO import StringIO
  52. try:
  53. module = load_app(self.model_label)
  54. except Exception, e:
  55. self.fail('Unable to load invalid model module')
  56. # Make sure sys.stdout is not a tty so that we get errors without
  57. # coloring attached (makes matching the results easier). We restore
  58. # sys.stderr afterwards.
  59. orig_stdout = sys.stdout
  60. s = StringIO()
  61. sys.stdout = s
  62. count = get_validation_errors(s, module)
  63. sys.stdout = orig_stdout
  64. s.seek(0)
  65. error_log = s.read()
  66. actual = error_log.split('\n')
  67. expected = module.model_errors.split('\n')
  68. unexpected = [err for err in actual if err not in expected]
  69. missing = [err for err in expected if err not in actual]
  70. self.assert_(not unexpected, "Unexpected Errors: " + '\n'.join(unexpected))
  71. self.assert_(not missing, "Missing Errors: " + '\n'.join(missing))
  72. def django_tests(verbosity, interactive, failfast, test_labels):
  73. from django.conf import settings
  74. old_installed_apps = settings.INSTALLED_APPS
  75. old_root_urlconf = getattr(settings, "ROOT_URLCONF", "")
  76. old_template_dirs = settings.TEMPLATE_DIRS
  77. old_use_i18n = settings.USE_I18N
  78. old_login_url = settings.LOGIN_URL
  79. old_language_code = settings.LANGUAGE_CODE
  80. old_middleware_classes = settings.MIDDLEWARE_CLASSES
  81. # Redirect some settings for the duration of these tests.
  82. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
  83. settings.ROOT_URLCONF = 'urls'
  84. settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), TEST_TEMPLATE_DIR),)
  85. settings.USE_I18N = True
  86. settings.LANGUAGE_CODE = 'en'
  87. settings.LOGIN_URL = '/accounts/login/'
  88. settings.MIDDLEWARE_CLASSES = (
  89. 'django.contrib.sessions.middleware.SessionMiddleware',
  90. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  91. 'django.contrib.messages.middleware.MessageMiddleware',
  92. 'django.middleware.common.CommonMiddleware',
  93. )
  94. settings.SITE_ID = 1
  95. # For testing comment-utils, we require the MANAGERS attribute
  96. # to be set, so that a test email is sent out which we catch
  97. # in our tests.
  98. settings.MANAGERS = ("admin@djangoproject.com",)
  99. # This import statement is intentionally delayed until after we
  100. # access settings because of the USE_I18N dependency.
  101. from django.db.models.loading import load_app
  102. # Load all the test model apps.
  103. test_labels_set = set([label.split('.')[0] for label in test_labels])
  104. for model_dir, model_name in get_test_models():
  105. model_label = '.'.join([model_dir, model_name])
  106. # if the model was named on the command line, or
  107. # no models were named (i.e., run all), import
  108. # this model and add it to the list to test.
  109. if not test_labels or model_name in test_labels_set:
  110. if verbosity >= 2:
  111. print "Importing model %s" % model_name
  112. mod = load_app(model_label)
  113. if mod:
  114. if model_label not in settings.INSTALLED_APPS:
  115. settings.INSTALLED_APPS.append(model_label)
  116. # Add tests for invalid models.
  117. extra_tests = []
  118. for model_dir, model_name in get_invalid_models():
  119. model_label = '.'.join([model_dir, model_name])
  120. if not test_labels or model_name in test_labels:
  121. extra_tests.append(InvalidModelTestCase(model_label))
  122. try:
  123. # Invalid models are not working apps, so we cannot pass them into
  124. # the test runner with the other test_labels
  125. test_labels.remove(model_name)
  126. except ValueError:
  127. pass
  128. # Run the test suite, including the extra validation tests.
  129. from django.test.utils import get_runner
  130. if not hasattr(settings, 'TEST_RUNNER'):
  131. settings.TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
  132. TestRunner = get_runner(settings)
  133. if hasattr(TestRunner, 'func_name'):
  134. # Pre 1.2 test runners were just functions,
  135. # and did not support the 'failfast' option.
  136. import warnings
  137. warnings.warn(
  138. 'Function-based test runners are deprecated. Test runners should be classes with a run_tests() method.',
  139. PendingDeprecationWarning
  140. )
  141. failures = TestRunner(test_labels, verbosity=verbosity, interactive=interactive,
  142. extra_tests=extra_tests)
  143. else:
  144. test_runner = TestRunner(verbosity=verbosity, interactive=interactive, failfast=failfast)
  145. failures = test_runner.run_tests(test_labels, extra_tests=extra_tests)
  146. if failures:
  147. sys.exit(bool(failures))
  148. # Restore the old settings.
  149. settings.INSTALLED_APPS = old_installed_apps
  150. settings.ROOT_URLCONF = old_root_urlconf
  151. settings.TEMPLATE_DIRS = old_template_dirs
  152. settings.USE_I18N = old_use_i18n
  153. settings.LANGUAGE_CODE = old_language_code
  154. settings.LOGIN_URL = old_login_url
  155. settings.MIDDLEWARE_CLASSES = old_middleware_classes
  156. if __name__ == "__main__":
  157. from optparse import OptionParser
  158. usage = "%prog [options] [model model model ...]"
  159. parser = OptionParser(usage=usage)
  160. parser.add_option('-v','--verbosity', action='store', dest='verbosity', default='1',
  161. type='choice', choices=['0', '1', '2', '3'],
  162. help='Verbosity level; 0=minimal output, 1=normal output, 2=all output')
  163. parser.add_option('--noinput', action='store_false', dest='interactive', default=True,
  164. help='Tells Django to NOT prompt the user for input of any kind.')
  165. parser.add_option('--failfast', action='store_true', dest='failfast', default=False,
  166. help='Tells Django to stop running the test suite after first failed test.')
  167. parser.add_option('--settings',
  168. help='Python path to settings module, e.g. "myproject.settings". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.')
  169. options, args = parser.parse_args()
  170. if options.settings:
  171. os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
  172. elif "DJANGO_SETTINGS_MODULE" not in os.environ:
  173. parser.error("DJANGO_SETTINGS_MODULE is not set in the environment. "
  174. "Set it or use --settings.")
  175. django_tests(int(options.verbosity), options.interactive, options.failfast, args)