tests.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import copy
  2. import sys
  3. from io import BytesIO
  4. from django.core.management.validation import get_validation_errors
  5. from django.db.models.loading import cache, load_app
  6. from django.utils import unittest
  7. class InvalidModelTestCase(unittest.TestCase):
  8. """Import an appliation with invalid models and test the exceptions."""
  9. def setUp(self):
  10. # Make sure sys.stdout is not a tty so that we get errors without
  11. # coloring attached (makes matching the results easier). We restore
  12. # sys.stderr afterwards.
  13. self.old_stdout = sys.stdout
  14. self.stdout = BytesIO()
  15. sys.stdout = self.stdout
  16. # This test adds dummy applications to the app cache. These
  17. # need to be removed in order to prevent bad interactions
  18. # with the flush operation in other tests.
  19. self.old_app_models = copy.deepcopy(cache.app_models)
  20. self.old_app_store = copy.deepcopy(cache.app_store)
  21. def tearDown(self):
  22. cache.app_models = self.old_app_models
  23. cache.app_store = self.old_app_store
  24. cache._get_models_cache = {}
  25. sys.stdout = self.old_stdout
  26. def test_invalid_models(self):
  27. try:
  28. module = load_app("modeltests.invalid_models.invalid_models")
  29. except Exception:
  30. self.fail('Unable to load invalid model module')
  31. count = get_validation_errors(self.stdout, module)
  32. self.stdout.seek(0)
  33. error_log = self.stdout.read()
  34. actual = error_log.split('\n')
  35. expected = module.model_errors.split('\n')
  36. unexpected = [err for err in actual if err not in expected]
  37. missing = [err for err in expected if err not in actual]
  38. self.assertFalse(unexpected, "Unexpected Errors: " + '\n'.join(unexpected))
  39. self.assertFalse(missing, "Missing Errors: " + '\n'.join(missing))