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