runtests.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. #!/usr/bin/env python
  2. import os, sys, traceback
  3. import unittest
  4. import django.contrib as contrib
  5. try:
  6. set
  7. except NameError:
  8. from sets import Set as set # For Python 2.3
  9. CONTRIB_DIR_NAME = 'django.contrib'
  10. MODEL_TESTS_DIR_NAME = 'modeltests'
  11. REGRESSION_TESTS_DIR_NAME = 'regressiontests'
  12. TEST_TEMPLATE_DIR = 'templates'
  13. CONTRIB_DIR = os.path.dirname(contrib.__file__)
  14. MODEL_TEST_DIR = os.path.join(os.path.dirname(__file__), MODEL_TESTS_DIR_NAME)
  15. REGRESSION_TEST_DIR = os.path.join(os.path.dirname(__file__), REGRESSION_TESTS_DIR_NAME)
  16. ALWAYS_INSTALLED_APPS = [
  17. 'django.contrib.contenttypes',
  18. 'django.contrib.auth',
  19. 'django.contrib.sites',
  20. 'django.contrib.flatpages',
  21. 'django.contrib.redirects',
  22. 'django.contrib.sessions',
  23. 'django.contrib.comments',
  24. 'django.contrib.admin',
  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 f.startswith('sql') or f.startswith('invalid'):
  31. continue
  32. models.append((loc, f))
  33. return models
  34. def get_invalid_models():
  35. models = []
  36. for loc, dirpath in (MODEL_TESTS_DIR_NAME, MODEL_TEST_DIR), (REGRESSION_TESTS_DIR_NAME, REGRESSION_TEST_DIR), (CONTRIB_DIR_NAME, CONTRIB_DIR):
  37. for f in os.listdir(dirpath):
  38. if f.startswith('__init__') or f.startswith('.') or f.startswith('sql'):
  39. continue
  40. if f.startswith('invalid'):
  41. models.append((loc, f))
  42. return models
  43. class InvalidModelTestCase(unittest.TestCase):
  44. def __init__(self, model_label):
  45. unittest.TestCase.__init__(self)
  46. self.model_label = model_label
  47. def runTest(self):
  48. from django.core.management.validation import get_validation_errors
  49. from django.db.models.loading import load_app
  50. from cStringIO import StringIO
  51. try:
  52. module = load_app(self.model_label)
  53. except Exception, e:
  54. self.fail('Unable to load invalid model module')
  55. # Make sure sys.stdout is not a tty so that we get errors without
  56. # coloring attached (makes matching the results easier). We restore
  57. # sys.stderr afterwards.
  58. orig_stdout = sys.stdout
  59. s = StringIO()
  60. sys.stdout = s
  61. count = get_validation_errors(s, module)
  62. sys.stdout = orig_stdout
  63. s.seek(0)
  64. error_log = s.read()
  65. actual = error_log.split('\n')
  66. expected = module.model_errors.split('\n')
  67. unexpected = [err for err in actual if err not in expected]
  68. missing = [err for err in expected if err not in actual]
  69. self.assert_(not unexpected, "Unexpected Errors: " + '\n'.join(unexpected))
  70. self.assert_(not missing, "Missing Errors: " + '\n'.join(missing))
  71. def django_tests(verbosity, interactive, test_labels):
  72. from django.conf import settings
  73. old_installed_apps = settings.INSTALLED_APPS
  74. old_test_database_name = settings.TEST_DATABASE_NAME
  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.middleware.common.CommonMiddleware',
  92. )
  93. settings.SITE_ID = 1
  94. # For testing comment-utils, we require the MANAGERS attribute
  95. # to be set, so that a test email is sent out which we catch
  96. # in our tests.
  97. settings.MANAGERS = ("admin@djangoproject.com",)
  98. # Load all the ALWAYS_INSTALLED_APPS.
  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 get_apps, load_app
  102. get_apps()
  103. # Load all the test model apps.
  104. for model_dir, model_name in get_test_models():
  105. model_label = '.'.join([model_dir, model_name])
  106. try:
  107. # if the model was named on the command line, or
  108. # no models were named (i.e., run all), import
  109. # this model and add it to the list to test.
  110. if not test_labels or model_name in set([label.split('.')[0] for label in test_labels]):
  111. if verbosity >= 1:
  112. print "Importing model %s" % model_name
  113. mod = load_app(model_label)
  114. if mod:
  115. if model_label not in settings.INSTALLED_APPS:
  116. settings.INSTALLED_APPS.append(model_label)
  117. except Exception, e:
  118. sys.stderr.write("Error while importing %s:" % model_name + ''.join(traceback.format_exception(*sys.exc_info())[1:]))
  119. continue
  120. # Add tests for invalid models.
  121. extra_tests = []
  122. for model_dir, model_name in get_invalid_models():
  123. model_label = '.'.join([model_dir, model_name])
  124. if not test_labels or model_name in test_labels:
  125. extra_tests.append(InvalidModelTestCase(model_label))
  126. try:
  127. # Invalid models are not working apps, so we cannot pass them into
  128. # the test runner with the other test_labels
  129. test_labels.remove(model_name)
  130. except ValueError:
  131. pass
  132. # Run the test suite, including the extra validation tests.
  133. from django.test.utils import get_runner
  134. if not hasattr(settings, 'TEST_RUNNER'):
  135. settings.TEST_RUNNER = 'django.test.simple.run_tests'
  136. test_runner = get_runner(settings)
  137. failures = test_runner(test_labels, verbosity=verbosity, interactive=interactive, extra_tests=extra_tests)
  138. if failures:
  139. sys.exit(failures)
  140. # Restore the old settings.
  141. settings.INSTALLED_APPS = old_installed_apps
  142. settings.ROOT_URLCONF = old_root_urlconf
  143. settings.TEMPLATE_DIRS = old_template_dirs
  144. settings.USE_I18N = old_use_i18n
  145. settings.LANGUAGE_CODE = old_language_code
  146. settings.LOGIN_URL = old_login_url
  147. settings.MIDDLEWARE_CLASSES = old_middleware_classes
  148. if __name__ == "__main__":
  149. from optparse import OptionParser
  150. usage = "%prog [options] [model model model ...]"
  151. parser = OptionParser(usage=usage)
  152. parser.add_option('-v','--verbosity', action='store', dest='verbosity', default='0',
  153. type='choice', choices=['0', '1', '2'],
  154. help='Verbosity level; 0=minimal output, 1=normal output, 2=all output')
  155. parser.add_option('--noinput', action='store_false', dest='interactive', default=True,
  156. help='Tells Django to NOT prompt the user for input of any kind.')
  157. parser.add_option('--settings',
  158. help='Python path to settings module, e.g. "myproject.settings". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.')
  159. options, args = parser.parse_args()
  160. if options.settings:
  161. os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
  162. elif "DJANGO_SETTINGS_MODULE" not in os.environ:
  163. parser.error("DJANGO_SETTINGS_MODULE is not set in the environment. "
  164. "Set it or use --settings.")
  165. django_tests(int(options.verbosity), options.interactive, args)