4
from django.core.management.validation import get_validation_errors
5
from django.db.models.loading import cache, load_app
7
from django.test.utils import override_settings
8
from django.utils import unittest
9
from django.utils.six import StringIO
12
class InvalidModelTestCase(unittest.TestCase):
13
"""Import an appliation with invalid models and test the exceptions."""
16
# Make sure sys.stdout is not a tty so that we get errors without
17
# coloring attached (makes matching the results easier). We restore
18
# sys.stderr afterwards.
19
self.old_stdout = sys.stdout
20
self.stdout = StringIO()
21
sys.stdout = self.stdout
23
# This test adds dummy applications to the app cache. These
24
# need to be removed in order to prevent bad interactions
25
# with the flush operation in other tests.
26
self.old_app_models = copy.deepcopy(cache.app_models)
27
self.old_app_store = copy.deepcopy(cache.app_store)
30
cache.app_models = self.old_app_models
31
cache.app_store = self.old_app_store
32
cache._get_models_cache = {}
33
sys.stdout = self.old_stdout
35
# Technically, this isn't an override -- TEST_SWAPPED_MODEL must be
36
# set to *something* in order for the test to work. However, it's
37
# easier to set this up as an override than to require every developer
38
# to specify a value in their test settings.
40
TEST_SWAPPED_MODEL='invalid_models.ReplacementModel',
41
TEST_SWAPPED_MODEL_BAD_VALUE='not-a-model',
42
TEST_SWAPPED_MODEL_BAD_MODEL='not_an_app.Target',
44
def test_invalid_models(self):
46
module = load_app("invalid_models.invalid_models")
48
self.fail('Unable to load invalid model module')
50
get_validation_errors(self.stdout, module)
52
error_log = self.stdout.read()
53
actual = error_log.split('\n')
54
expected = module.model_errors.split('\n')
56
unexpected = [err for err in actual if err not in expected]
57
missing = [err for err in expected if err not in actual]
58
self.assertFalse(unexpected, "Unexpected Errors: " + '\n'.join(unexpected))
59
self.assertFalse(missing, "Missing Errors: " + '\n'.join(missing))