7

我正在尝试对我的 Django 应用程序进行一些测试。我在整个应用程序中使用数据库镜像进行一些读取。当我尝试测试这些部分时,通过在数据库中创建模拟数据然后尝试读取它,看起来好像数据不在镜像数据库中,尽管被配置为TEST_MIRROR.

用于测试的数据库配置如下所示:

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'maindb',
    'HOST': 'localhost'
  },
  'mirror1': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'maindb',
    'HOST': 'localhost',
    'TEST_MIRROR': 'default'
  }
}

然后在我的测试中我做了这样的事情(Foo是一个模型)

Foo.objects.create(name='bar')
self.assertTrue(Foo.objects.filter(name='bar').exists()) # passes
self.assertTrue(Foo.objects.using('mirror1').filter(name='bar').exists()) # fails

这让我很困惑,因为我认为这样做的目的TEST_MIRROR是让对镜像的调用直接传递到默认值?

4

2 回答 2

5

If your setup contains multiple databases, and you have a test that requires every database, you can use the multi_db attribute on the test suite to request a full flush.

For example:

class TestMyViews(TestCase):
    multi_db = True        # for Django < 3.1 (deprecated since 2.2)
    databases = '__all__'  # for Django >= 2.2
    # databases = {'default', 'other'}  # or explicit databases


    def testIndexPageView(self):
        call_some_test_code()

That documentation (multi-database support testing) is not exact, because the condition multi_db (indirectly in _databases_names) is not used only for flush (tearDown) in Django source, but also for '_fixture_setup'. (Django-1.5.1/django/test/testcases.py:834) Therefore it seems to be a basic condition independent on master/slave settings.

于 2013-09-28T12:53:44.260 回答
1

我想答案可能就在这里

配置测试环境时,不会创建slave的测试版本 。相反,与从站的连接将被重定向到默认指向

由于从机在测试中并不真正存在,因此尝试直接调用它失败是有道理的

于 2013-10-03T16:07:41.290 回答