Django

Code

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

Revision 805, 9.4 kB (checked in by adrian, 3 years ago)

Fixed bug in tests/runtests.py -- some versions of MySQLdb require an argument to connection.autocommit()

  • Property svn:executable set to *
Line 
1 #!/usr/bin/env python
2
3 import os, 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 class DjangoDoctestOutputChecker(doctest.OutputChecker):
47     def check_output(self, want, got, optionflags):
48         ok = doctest.OutputChecker.check_output(self, want, got, optionflags)
49         if not ok and (want.strip().endswith("L") or got.strip().endswith("L")):
50             try:
51                 return long(want.strip()) == long(got.strip())
52             except ValueError:
53                 return False
54         return ok
55
56 class TestRunner:
57     def __init__(self, verbosity_level=0, which_tests=None):
58         self.verbosity_level = verbosity_level
59         self.which_tests = which_tests
60
61     def output(self, required_level, message):
62         if self.verbosity_level > required_level - 1:
63             print message
64
65     def run_tests(self):
66         from django.conf import settings
67         from django.core.db import db
68         from django.core import management, meta
69
70         # Manually set INSTALLED_APPS to point to the test app.
71         settings.INSTALLED_APPS = (APP_NAME,)
72
73         # Determine which models we're going to test.
74         test_models = get_test_models()
75         if self.which_tests:
76             # Only run the specified tests.
77             bad_models = [m for m in self.which_tests if m not in test_models]
78             if bad_models:
79                 sys.stderr.write("Models not found: %s\n" % bad_models)
80                 sys.exit(1)
81             else:
82                 test_models = self.which_tests
83
84         self.output(0, "Running tests with database %r" % settings.DATABASE_ENGINE)
85
86         # If we're using SQLite, it's more convenient to test against an
87         # in-memory database.
88         if settings.DATABASE_ENGINE == "sqlite3":
89             global TEST_DATABASE_NAME
90             TEST_DATABASE_NAME = ":memory:"
91         else:
92             # Create the test database and connect to it. We need autocommit()
93             # because PostgreSQL doesn't allow CREATE DATABASE statements
94             # within transactions.
95             cursor = db.cursor()
96             try:
97                 db.connection.autocommit(1)
98             except AttributeError:
99                 pass
100             self.output(1, "Creating test database")
101             try:
102                 cursor.execute("CREATE DATABASE %s" % TEST_DATABASE_NAME)
103             except:
104                 confirm = raw_input("The test database, %s, already exists. Type 'yes' to delete it, or 'no' to cancel: " % TEST_DATABASE_NAME)
105                 if confirm == 'yes':
106                     cursor.execute("DROP DATABASE %s" % TEST_DATABASE_NAME)
107                     cursor.execute("CREATE DATABASE %s" % TEST_DATABASE_NAME)
108                 else:
109                     print "Tests cancelled."
110                     return
111         db.close()
112         old_database_name = settings.DATABASE_NAME
113         settings.DATABASE_NAME = TEST_DATABASE_NAME
114
115         # Initialize the test database.
116         cursor = db.cursor()
117         self.output(1, "Initializing test database")
118         management.init()
119
120         # Run the tests for each test model.
121         self.output(1, "Running app tests")
122         for model_name in test_models:
123             self.output(1, "%s model: Importing" % model_name)
124             try:
125                 mod = meta.get_app(model_name)
126             except Exception, e:
127                 log_error(model_name, "Error while importing", ''.join(traceback.format_exception(*sys.exc_info())[1:]))
128                 continue
129             self.output(1, "%s model: Installing" % model_name)
130             management.install(mod)
131
132             # Run the API tests.
133             p = doctest.DocTestParser()
134             test_namespace = dict([(m._meta.module_name, getattr(mod, m._meta.module_name)) for m in mod._MODELS])
135             dtest = p.get_doctest(mod.API_TESTS, test_namespace, model_name, None, None)
136             # Manually set verbose=False, because "-v" command-line parameter
137             # has side effects on doctest TestRunner class.
138             runner = DjangoDoctestRunner(verbosity_level=verbosity_level, verbose=False)
139             self.output(1, "%s model: Running tests" % model_name)
140             try:
141                 runner.run(dtest, clear_globs=True, out=sys.stdout.write)
142             finally:
143                 # Rollback, in case of database errors. Otherwise they'd have
144                 # side effects on other tests.
145                 db.rollback()
146
147         if not self.which_tests:
148             # Run the non-model tests in the other tests dir
149             self.output(1, "Running other tests")
150             other_tests_dir = os.path.join(os.path.dirname(__file__), OTHER_TESTS_DIR)
151             test_modules = [f[:-3] for f in os.listdir(other_tests_dir) if f.endswith('.py') and not f.startswith('__init__')]
152             for module in test_modules:
153                 self.output(1, "%s module: Importing" % module)
154                 try:
155                     mod = __import__("othertests." + module, '', '', [''])
156                 except Exception, e:
157                     log_error(module, "Error while importing", ''.join(traceback.format_exception(*sys.exc_info())[1:]))
158                     continue
159                 if mod.__doc__:
160                     p = doctest.DocTestParser()
161                     dtest = p.get_doctest(mod.__doc__, mod.__dict__, module, None, None)
162                     runner = DjangoDoctestRunner(verbosity_level=verbosity_level, verbose=False)
163                     self.output(1, "%s module: running tests" % module)
164                     runner.run(dtest, clear_globs=True, out=sys.stdout.write)
165                 if hasattr(mod, "run_tests") and callable(mod.run_tests):
166                     self.output(1, "%s module: running tests" % module)
167                     try:
168                         mod.run_tests(verbosity_level)
169                     except Exception, e:
170                         log_error(module, "Exception running tests", ''.join(traceback.format_exception(*sys.exc_info())[1:]))
171                         continue
172
173         # Unless we're using SQLite, remove the test database to clean up after
174         # ourselves. Connect to the previous database (not the test database)
175         # to do so, because it's not allowed to delete a database while being
176         # connected to it.
177         if settings.DATABASE_ENGINE != "sqlite3":
178             db.close()
179             settings.DATABASE_NAME = old_database_name
180             cursor = db.cursor()
181             self.output(1, "Deleting test database")
182             try:
183                 db.connection.autocommit(1)
184             except AttributeError:
185                 pass
186             else:
187                 time.sleep(1) # To avoid "database is being accessed by other users" errors.
188             cursor.execute("DROP DATABASE %s" % TEST_DATABASE_NAME)
189
190         # Display output.
191         if error_list:
192             for d in error_list:
193                 print
194                 print d['title']
195                 print "=" * len(d['title'])
196                 print d['description']
197             print "%s error%s:" % (len(error_list), len(error_list) != 1 and 's' or '')
198         else:
199             print "All tests passed."
200
201 if __name__ == "__main__":
202     from optparse import OptionParser
203     usage = "%prog [options] [model model model ...]"
204     parser = OptionParser()
205     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.',
206         type='choice', choices=['0', '1', '2'])
207     parser.add_option('--settings',
208         help='Python path to settings module, e.g. "myproject.settings.main". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.')
209     options, args = parser.parse_args()
210     verbosity_level = 0
211     if options.v:
212         verbosity_level = int(options.v)
213     if options.settings:
214         os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
215     t = TestRunner(verbosity_level, args)
216     t.run_tests()
Note: See TracBrowser for help on using the browser.