Django

Code

root/django/branches/0.91-bugfixes/tests/runtests.py

Revision 2336, 9.7 kB (checked in by adrian, 3 years ago)

Added usage to unit-test OptionParser?

  • Property svn:executable set to *
Line 
1 #!/usr/bin/env python
2
3 import os, re, sys, time, traceback
4
5 # doctest is included in the same package as this module, because this testing
6 # framework uses features only available in the Python 2.4 version of doctest,
7 # and Django aims to work with Python 2.3+.
8 import doctest
9
10 APP_NAME = 'testapp'
11 OTHER_TESTS_DIR = "othertests"
12 TEST_DATABASE_NAME = 'django_test_db'
13
14 error_list = []
15 def log_error(model_name, title, description):
16     error_list.append({
17         'title': "%r module: %s" % (model_name, title),
18         'description': description,
19     })
20
21 MODEL_DIR = os.path.join(os.path.dirname(__file__), APP_NAME, 'models')
22
23 def get_test_models():
24     return [f[:-3] for f in os.listdir(MODEL_DIR) if f.endswith('.py') and not f.startswith('__init__')]
25
26 class DjangoDoctestRunner(doctest.DocTestRunner):
27     def __init__(self, verbosity_level, *args, **kwargs):
28         self.verbosity_level = verbosity_level
29         doctest.DocTestRunner.__init__(self, *args, **kwargs)
30         self._checker = DjangoDoctestOutputChecker()
31         self.optionflags = doctest.ELLIPSIS
32
33     def report_start(self, out, test, example):
34         if self.verbosity_level > 1:
35             out("  >>> %s\n" % example.source.strip())
36
37     def report_failure(self, out, test, example, got):
38         log_error(test.name, "API test failed",
39             "Code: %r\nLine: %s\nExpected: %r\nGot: %r" % (example.source.strip(), example.lineno, example.want, got))
40
41     def report_unexpected_exception(self, out, test, example, exc_info):
42         tb = ''.join(traceback.format_exception(*exc_info)[1:])
43         log_error(test.name, "API test raised an exception",
44             "Code: %r\nLine: %s\nException: %s" % (example.source.strip(), example.lineno, tb))
45
46 normalize_long_ints = lambda s: re.sub(r'(?<![\w])(\d+)L(?![\w])', '\\1', s)
47
48 class DjangoDoctestOutputChecker(doctest.OutputChecker):
49     def check_output(self, want, got, optionflags):
50         ok = doctest.OutputChecker.check_output(self, want, got, optionflags)
51
52         # Doctest does an exact string comparison of output, which means long
53         # integers aren't equal to normal integers ("22L" vs. "22"). The
54         # following code normalizes long integers so that they equal normal
55         # integers.
56         if not ok:
57             return normalize_long_ints(want) == normalize_long_ints(got)
58         return ok
59
60 class TestRunner:
61     def __init__(self, verbosity_level=0, which_tests=None):
62         self.verbosity_level = verbosity_level
63         self.which_tests = which_tests
64
65     def output(self, required_level, message):
66         if self.verbosity_level > required_level - 1:
67             print message
68
69     def run_tests(self):
70         from django.conf import settings
71         from django.core.db import db
72         from django.core import management, meta
73
74         # Manually set INSTALLED_APPS to point to the test app.
75         settings.INSTALLED_APPS = (APP_NAME,)
76
77         # Determine which models we're going to test.
78         test_models = get_test_models()
79         if self.which_tests:
80             # Only run the specified tests.
81             bad_models = [m for m in self.which_tests if m not in test_models]
82             if bad_models:
83                 sys.stderr.write("Models not found: %s\n" % bad_models)
84                 sys.exit(1)
85             else:
86                 test_models = self.which_tests
87
88         self.output(0, "Running tests with database %r" % settings.DATABASE_ENGINE)
89
90         # If we're using SQLite, it's more convenient to test against an
91         # in-memory database.
92         if settings.DATABASE_ENGINE == "sqlite3":
93             global TEST_DATABASE_NAME
94             TEST_DATABASE_NAME = ":memory:"
95         else:
96             # Create the test database and connect to it. We need autocommit()
97             # because PostgreSQL doesn't allow CREATE DATABASE statements
98             # within transactions.
99             cursor = db.cursor()
100             try:
101                 db.connection.autocommit(1)
102             except AttributeError:
103                 pass
104             self.output(1, "Creating test database")
105             try:
106                 cursor.execute("CREATE DATABASE %s" % TEST_DATABASE_NAME)
107             except Exception, e:
108                 sys.stderr.write("Got an error creating the test database: %s\n" % e)
109                 confirm = raw_input("It appears the test database, %s, already exists. Type 'yes' to delete it, or 'no' to cancel: " % TEST_DATABASE_NAME)
110                 if confirm == 'yes':
111                     cursor.execute("DROP DATABASE %s" % TEST_DATABASE_NAME)
112                     cursor.execute("CREATE DATABASE %s" % TEST_DATABASE_NAME)
113                 else:
114                     print "Tests cancelled."
115                     return
116         db.close()
117         old_database_name = settings.DATABASE_NAME
118         settings.DATABASE_NAME = TEST_DATABASE_NAME
119
120         # Initialize the test database.
121         cursor = db.cursor()
122         self.output(1, "Initializing test database")
123         management.init()
124
125         # Run the tests for each test model.
126         self.output(1, "Running app tests")
127         for model_name in test_models:
128             self.output(1, "%s model: Importing" % model_name)
129             try:
130                 mod = meta.get_app(model_name)
131             except Exception, e:
132                 log_error(model_name, "Error while importing", ''.join(traceback.format_exception(*sys.exc_info())[1:]))
133                 continue
134             self.output(1, "%s model: Installing" % model_name)
135             management.install(mod)
136
137             # Run the API tests.
138             p = doctest.DocTestParser()
139             test_namespace = dict([(m._meta.module_name, getattr(mod, m._meta.module_name)) for m in mod._MODELS])
140             dtest = p.get_doctest(mod.API_TESTS, test_namespace, model_name, None, None)
141             # Manually set verbose=False, because "-v" command-line parameter
142             # has side effects on doctest TestRunner class.
143             runner = DjangoDoctestRunner(verbosity_level=verbosity_level, verbose=False)
144             self.output(1, "%s model: Running tests" % model_name)
145             try:
146                 runner.run(dtest, clear_globs=True, out=sys.stdout.write)
147             finally:
148                 # Rollback, in case of database errors. Otherwise they'd have
149                 # side effects on other tests.
150                 db.rollback()
151
152         if not self.which_tests:
153             # Run the non-model tests in the other tests dir
154             self.output(1, "Running other tests")
155             other_tests_dir = os.path.join(os.path.dirname(__file__), OTHER_TESTS_DIR)
156             test_modules = [f[:-3] for f in os.listdir(other_tests_dir) if f.endswith('.py') and not f.startswith('__init__')]
157             for module in test_modules:
158                 self.output(1, "%s module: Importing" % module)
159                 try:
160                     mod = __import__("othertests." + module, '', '', [''])
161                 except Exception, e:
162                     log_error(module, "Error while importing", ''.join(traceback.format_exception(*sys.exc_info())[1:]))
163                     continue
164                 if mod.__doc__:
165                     p = doctest.DocTestParser()
166                     dtest = p.get_doctest(mod.__doc__, mod.__dict__, module, None, None)
167                     runner = DjangoDoctestRunner(verbosity_level=verbosity_level, verbose=False)
168                     self.output(1, "%s module: running tests" % module)
169                     runner.run(dtest, clear_globs=True, out=sys.stdout.write)
170                 if hasattr(mod, "run_tests") and callable(mod.run_tests):
171                     self.output(1, "%s module: running tests" % module)
172                     try:
173                         mod.run_tests(verbosity_level)
174                     except Exception, e:
175                         log_error(module, "Exception running tests", ''.join(traceback.format_exception(*sys.exc_info())[1:]))
176                         continue
177
178         # Unless we're using SQLite, remove the test database to clean up after
179         # ourselves. Connect to the previous database (not the test database)
180         # to do so, because it's not allowed to delete a database while being
181         # connected to it.
182         if settings.DATABASE_ENGINE != "sqlite3":
183             db.close()
184             settings.DATABASE_NAME = old_database_name
185             cursor = db.cursor()
186             self.output(1, "Deleting test database")
187             try:
188                 db.connection.autocommit(1)
189             except AttributeError:
190                 pass
191             else:
192                 time.sleep(1) # To avoid "database is being accessed by other users" errors.
193             cursor.execute("DROP DATABASE %s" % TEST_DATABASE_NAME)
194
195         # Display output.
196         if error_list:
197             for d in error_list:
198                 print
199                 print d['title']
200                 print "=" * len(d['title'])
201                 print d['description']
202             print "%s error%s:" % (len(error_list), len(error_list) != 1 and 's' or '')
203         else:
204             print "All tests passed."
205
206 if __name__ == "__main__":
207     from optparse import OptionParser
208     usage = "%prog [options] [model model model ...]"
209     parser = OptionParser(usage=usage)
210     parser.add_option('-v', help='How verbose should the output be? Choices are 0, 1 and 2, where 2 is most verbose. Default is 0.',
211         type='choice', choices=['0', '1', '2'])
212     parser.add_option('--settings',
213         help='Python path to settings module, e.g. "myproject.settings". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.')
214     options, args = parser.parse_args()
215     verbosity_level = 0
216     if options.v:
217         verbosity_level = int(options.v)
218     if options.settings:
219         os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
220     t = TestRunner(verbosity_level, args)
221     t.run_tests()
Note: See TracBrowser for help on using the browser.