test_multi_db.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from unittest import mock
  2. from django.db import connections, models
  3. from django.test import SimpleTestCase
  4. from django.test.utils import isolate_apps, override_settings
  5. class TestRouter:
  6. """
  7. Routes to the 'other' database if the model name starts with 'Other'.
  8. """
  9. def allow_migrate(self, db, app_label, model_name=None, **hints):
  10. return db == ('other' if model_name.startswith('other') else 'default')
  11. @override_settings(DATABASE_ROUTERS=[TestRouter()])
  12. @isolate_apps('check_framework')
  13. class TestMultiDBChecks(SimpleTestCase):
  14. def _patch_check_field_on(self, db):
  15. return mock.patch.object(connections[db].validation, 'check_field')
  16. def test_checks_called_on_the_default_database(self):
  17. class Model(models.Model):
  18. field = models.CharField(max_length=100)
  19. model = Model()
  20. with self._patch_check_field_on('default') as mock_check_field_default:
  21. with self._patch_check_field_on('other') as mock_check_field_other:
  22. model.check()
  23. self.assertTrue(mock_check_field_default.called)
  24. self.assertFalse(mock_check_field_other.called)
  25. def test_checks_called_on_the_other_database(self):
  26. class OtherModel(models.Model):
  27. field = models.CharField(max_length=100)
  28. model = OtherModel()
  29. with self._patch_check_field_on('other') as mock_check_field_other:
  30. with self._patch_check_field_on('default') as mock_check_field_default:
  31. model.check()
  32. self.assertTrue(mock_check_field_other.called)
  33. self.assertFalse(mock_check_field_default.called)