runtests.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. # Load all the ALWAYS_INSTALLED_APPS.
  100. # (This import statement is intentionally delayed until after we
  101. # access settings because of the USE_I18N dependency.)
  102. from django.db.models.loading import get_apps, load_app
  103. get_apps()
  104. # Load all the test model apps.
  105. test_labels_set = set([label.split('.')[0] for label in test_labels])
  106. for model_dir, model_name in get_test_models():
  107. model_label = '.'.join([model_dir, model_name])
  108. # if the model was named on the command line, or
  109. # no models were named (i.e., run all), import
  110. # this model and add it to the list to test.
  111. if not test_labels or model_name in test_labels_set:
  112. if verbosity >= 1:
  113. print "Importing model %s" % model_name
  114. mod = load_app(model_label)
  115. if mod:
  116. if model_label not in settings.INSTALLED_APPS:
  117. settings.INSTALLED_APPS.append(model_label)
  118. # Add tests for invalid models.
  119. extra_tests = []
  120. for model_dir, model_name in get_invalid_models():
  121. model_label = '.'.join([model_dir, model_name])
  122. if not test_labels or model_name in test_labels:
  123. extra_tests.append(InvalidModelTestCase(model_label))
  124. try:
  125. # Invalid models are not working apps, so we cannot pass them into
  126. # the test runner with the other test_labels
  127. test_labels.remove(model_name)
  128. except ValueError:
  129. pass
  130. # Run the test suite, including the extra validation tests.
  131. from django.test.utils import get_runner
  132. if not hasattr(settings, 'TEST_RUNNER'):
  133. settings.TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
  134. TestRunner = get_runner(settings)
  135. if hasattr(TestRunner, 'func_name'):
  136. # Pre 1.2 test runners were just functions,
  137. # and did not support the 'failfast' option.
  138. import warnings
  139. warnings.warn(
  140. 'Function-based test runners are deprecated. Test runners should be classes with a run_tests() method.',
  141. PendingDeprecationWarning
  142. )
  143. failures = TestRunner(test_labels, verbosity=verbosity, interactive=interactive,
  144. extra_tests=extra_tests)
  145. else:
  146. test_runner = TestRunner(verbosity=verbosity, interactive=interactive, failfast=failfast)
  147. failures = test_runner.run_tests(test_labels, extra_tests=extra_tests)
  148. if failures:
  149. sys.exit(bool(failures))
  150. # Restore the old settings.
  151. settings.INSTALLED_APPS = old_installed_apps
  152. settings.ROOT_URLCONF = old_root_urlconf
  153. settings.TEMPLATE_DIRS = old_template_dirs
  154. settings.USE_I18N = old_use_i18n
  155. settings.LANGUAGE_CODE = old_language_code
  156. settings.LOGIN_URL = old_login_url
  157. settings.MIDDLEWARE_CLASSES = old_middleware_classes
  158. if __name__ == "__main__":
  159. from optparse import OptionParser
  160. usage = "%prog [options] [model model model ...]"
  161. parser = OptionParser(usage=usage)
  162. parser.add_option('-v','--verbosity', action='store', dest='verbosity', default='0',
  163. type='choice', choices=['0', '1', '2'],
  164. help='Verbosity level; 0=minimal output, 1=normal output, 2=all output')
  165. parser.add_option('--noinput', action='store_false', dest='interactive', default=True,
  166. help='Tells Django to NOT prompt the user for input of any kind.')
  167. parser.add_option('--failfast', action='store_true', dest='failfast', default=False,
  168. help='Tells Django to stop running the test suite after first failed test.')
  169. parser.add_option('--settings',
  170. help='Python path to settings module, e.g. "myproject.settings". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.')
  171. options, args = parser.parse_args()
  172. if options.settings:
  173. os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
  174. elif "DJANGO_SETTINGS_MODULE" not in os.environ:
  175. parser.error("DJANGO_SETTINGS_MODULE is not set in the environment. "
  176. "Set it or use --settings.")
  177. django_tests(int(options.verbosity), options.interactive, options.failfast, args)