Django

Code

root/django/branches/per-object-permissions/tests/runtests.py

Revision 5488, 6.4 kB (checked in by clong, 1 year ago)

per-object-permissions: Merged to trunk [5486] NOTE: Not fully tested, will be working on this over the next few weeks.

  • Property svn:executable set to *
Line 
1 #!/usr/bin/env python
2
3 import os, sys, traceback
4 import unittest
5
6 import django.contrib as contrib
7 CONTRIB_DIR_NAME = 'django.contrib'
8 MODEL_TESTS_DIR_NAME = 'modeltests'
9 REGRESSION_TESTS_DIR_NAME = 'regressiontests'
10
11 TEST_DATABASE_NAME = 'django_test_db'
12 TEST_TEMPLATE_DIR = 'templates'
13
14 CONTRIB_DIR = os.path.dirname(contrib.__file__)
15 MODEL_TEST_DIR = os.path.join(os.path.dirname(__file__), MODEL_TESTS_DIR_NAME)
16 REGRESSION_TEST_DIR = os.path.join(os.path.dirname(__file__), REGRESSION_TESTS_DIR_NAME)
17
18 ALWAYS_INSTALLED_APPS = [
19     'django.contrib.contenttypes',
20     'django.contrib.auth',
21     'django.contrib.sites',
22     'django.contrib.flatpages',
23     'django.contrib.redirects',
24     'django.contrib.sessions',
25     'django.contrib.comments',
26     'django.contrib.admin',
27 ]
28
29 def get_test_models():
30     models = []
31     for loc, dirpath in (MODEL_TESTS_DIR_NAME, MODEL_TEST_DIR), (REGRESSION_TESTS_DIR_NAME, REGRESSION_TEST_DIR), (CONTRIB_DIR_NAME, CONTRIB_DIR):
32         for f in os.listdir(dirpath):
33             if f.startswith('__init__') or f.startswith('.') or f.startswith('sql') or f.startswith('invalid'):
34                 continue
35             models.append((loc, f))
36     return models
37
38 def get_invalid_models():
39     models = []
40     for loc, dirpath in (MODEL_TESTS_DIR_NAME, MODEL_TEST_DIR), (REGRESSION_TESTS_DIR_NAME, REGRESSION_TEST_DIR), (CONTRIB_DIR_NAME, CONTRIB_DIR):
41         for f in os.listdir(dirpath):
42             if f.startswith('__init__') or f.startswith('.') or f.startswith('sql'):
43                 continue
44             if f.startswith('invalid'):
45                 models.append((loc, f))
46     return models
47
48 class InvalidModelTestCase(unittest.TestCase):
49     def __init__(self, model_label):
50         unittest.TestCase.__init__(self)
51         self.model_label = model_label
52
53     def runTest(self):
54         from django.core import management
55         from django.db.models.loading import load_app
56         from cStringIO import StringIO
57
58         try:
59             module = load_app(self.model_label)
60         except Exception, e:
61             self.fail('Unable to load invalid model module')
62
63         s = StringIO()
64         count = management.get_validation_errors(s, module)
65         s.seek(0)
66         error_log = s.read()
67         actual = error_log.split('\n')
68         expected = module.model_errors.split('\n')
69
70         unexpected = [err for err in actual if err not in expected]
71         missing = [err for err in expected if err not in actual]
72
73         self.assert_(not unexpected, "Unexpected Errors: " + '\n'.join(unexpected))
74         self.assert_(not missing, "Missing Errors: " + '\n'.join(missing))
75
76 def django_tests(verbosity, tests_to_run):
77     from django.conf import settings
78
79     old_installed_apps = settings.INSTALLED_APPS
80     old_test_database_name = settings.TEST_DATABASE_NAME
81     old_root_urlconf = settings.ROOT_URLCONF
82     old_template_dirs = settings.TEMPLATE_DIRS
83     old_use_i18n = settings.USE_I18N
84     old_middleware_classes = settings.MIDDLEWARE_CLASSES
85
86     # Redirect some settings for the duration of these tests.
87     settings.TEST_DATABASE_NAME = TEST_DATABASE_NAME
88     settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
89     settings.ROOT_URLCONF = 'urls'
90     settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), TEST_TEMPLATE_DIR),)
91     settings.USE_I18N = True
92     settings.MIDDLEWARE_CLASSES = (
93         'django.contrib.sessions.middleware.SessionMiddleware',
94         'django.contrib.auth.middleware.AuthenticationMiddleware',
95         'django.middleware.common.CommonMiddleware',
96     )
97
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
104     # Load all the test model apps.
105     test_models = []
106     for model_dir, model_name in get_test_models():
107         model_label = '.'.join([model_dir, model_name])
108         try:
109             # if the model was named on the command line, or
110             # no models were named (i.e., run all), import
111             # this model and add it to the list to test.
112             if not tests_to_run or model_name in tests_to_run:
113                 if verbosity >= 1:
114                     print "Importing model %s" % model_name
115                 mod = load_app(model_label)
116                 if mod:
117                     if model_label not in settings.INSTALLED_APPS:
118                         settings.INSTALLED_APPS.append(model_label)
119                     test_models.append(mod)
120         except Exception, e:
121             sys.stderr.write("Error while importing %s:" % model_name + ''.join(traceback.format_exception(*sys.exc_info())[1:]))
122             continue
123
124     # Add tests for invalid models.
125     extra_tests = []
126     for model_dir, model_name in get_invalid_models():
127         model_label = '.'.join([model_dir, model_name])
128         if not tests_to_run or model_name in tests_to_run:
129             extra_tests.append(InvalidModelTestCase(model_label))
130
131     # Run the test suite, including the extra validation tests.
132     from django.test.simple import run_tests
133     failures = run_tests(test_models, verbosity, extra_tests=extra_tests)
134     if failures:
135         sys.exit(failures)
136
137     # Restore the old settings.
138     settings.INSTALLED_APPS = old_installed_apps
139     settings.TESTS_DATABASE_NAME = old_test_database_name
140     settings.ROOT_URLCONF = old_root_urlconf
141     settings.TEMPLATE_DIRS = old_template_dirs
142     settings.USE_I18N = old_use_i18n
143     settings.MIDDLEWARE_CLASSES = old_middleware_classes
144
145 if __name__ == "__main__":
146     from optparse import OptionParser
147     usage = "%prog [options] [model model model ...]"
148     parser = OptionParser(usage=usage)
149     parser.add_option('-v','--verbosity', action='store', dest='verbosity', default='0',
150         type='choice', choices=['0', '1', '2'],
151         help='Verbosity level; 0=minimal output, 1=normal output, 2=all output')
152     parser.add_option('--settings',
153         help='Python path to settings module, e.g. "myproject.settings". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.')
154     options, args = parser.parse_args()
155     if options.settings:
156         os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
157     elif "DJANGO_SETTINGS_MODULE" not in os.environ:
158         parser.error("DJANGO_SETTINGS_MODULE is not set in the environment. "
159                       "Set it or use --settings.")
160     django_tests(int(options.verbosity), args)
Note: See TracBrowser for help on using the browser.