Created
July 25, 2012 04:45
-
-
Save squidsoup/3174450 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.test import TestCase | |
from django.test.simple import build_test, reorder_suite, build_suite | |
from django.test.utils import setup_test_environment, teardown_test_environment | |
from django.db.models import get_app, get_apps | |
from django.conf import settings | |
import unittest | |
def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]): | |
""" | |
works exactly as per normal test, but without db creation or destruction | |
tables are flushed and fixtures loaded between tests as per usual | |
Run the unit tests for all the test labels in the provided list. | |
Labels must be of the form: | |
- app.TestClass.test_method | |
Run a single specific test method | |
- app.TestClass | |
Run all the test methods in a given class | |
- app | |
Search for doctests and unittests in the named application. | |
When looking for tests, the test runner will look in the models and | |
tests modules for the application. | |
A list of 'extra' tests may also be provided; these tests | |
will be added to the test suite. | |
Returns the number of tests that failed. | |
""" | |
setup_test_environment() | |
settings.DEBUG = False | |
suite = unittest.TestSuite() | |
if test_labels: | |
for label in test_labels: | |
if '.' in label: | |
suite.addTest(build_test(label)) | |
else: | |
app = get_app(label) | |
suite.addTest(build_suite(app)) | |
else: | |
for app in get_apps(): | |
suite.addTest(build_suite(app)) | |
for test in extra_tests: | |
suite.addTest(test) | |
suite = reorder_suite(suite, (TestCase,)) | |
old_name = settings.DATABASES['default']['NAME'] | |
old_name_alt = settings.DATABASES['alt_db']['NAME'] | |
from django.db import connection | |
if settings.DATABASES['alt_db']['TEST_NAME'] and settings.DATABASES['alt_db']['TEST_NAME']: | |
settings.DATABASES['alt_db']['NAME'] = settings.DATABASES['alt_db']['TEST_NAME'] | |
settings.DATABASES['default']['NAME'] = settings.DATABASES['default']['TEST_NAME'] | |
connection.settings_dict["DATABASE_NAME"] = settings.DATABASES['default']['NAME'] | |
result = unittest.TextTestRunner(verbosity=verbosity).run(suite) | |
#Since we don't call destory_test_db, we need to set the db name back. | |
settings.DATABASES['default']['NAME'] = old_name | |
settings.DATABASES['alt_db']['NAME'] = old_name_alt | |
connection.settings_dict["DATABASE_NAME"] = old_name | |
teardown_test_environment() | |
return len(result.failures) + len(result.errors) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment