File: test_multi_db.py

package info (click to toggle)
python-django 3%3A5.2.5-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 61,236 kB
  • sloc: python: 361,585; javascript: 19,250; xml: 211; makefile: 182; sh: 28
file content (43 lines) | stat: -rw-r--r-- 1,726 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from unittest import mock

from django.db import connections, models
from django.test import SimpleTestCase
from django.test.utils import isolate_apps, override_settings


class TestRouter:
    """
    Routes to the 'other' database if the model name starts with 'Other'.
    """

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        return db == ("other" if model_name.startswith("other") else "default")


@override_settings(DATABASE_ROUTERS=[TestRouter()])
@isolate_apps("check_framework")
class TestMultiDBChecks(SimpleTestCase):
    def _patch_check_field_on(self, db):
        return mock.patch.object(connections[db].validation, "check_field")

    def test_checks_called_on_the_default_database(self):
        class Model(models.Model):
            field = models.CharField(max_length=100)

        model = Model()
        with self._patch_check_field_on("default") as mock_check_field_default:
            with self._patch_check_field_on("other") as mock_check_field_other:
                model.check(databases={"default", "other"})
                self.assertTrue(mock_check_field_default.called)
                self.assertFalse(mock_check_field_other.called)

    def test_checks_called_on_the_other_database(self):
        class OtherModel(models.Model):
            field = models.CharField(max_length=100)

        model = OtherModel()
        with self._patch_check_field_on("other") as mock_check_field_other:
            with self._patch_check_field_on("default") as mock_check_field_default:
                model.check(databases={"default", "other"})
                self.assertTrue(mock_check_field_other.called)
                self.assertFalse(mock_check_field_default.called)