【问题标题】:Django: Use a read-only database within django test suiteDjango:在 Django 测试套件中使用只读数据库
【发布时间】:2022-07-05 19:12:55
【问题描述】:

在我的 Django 项目中,我使用了两个数据库,其中一个是我自己拥有读写权限的 PostgreSQL 数据库,另一个是我只有 read 权限的外部 PostgreSQL 数据库- 仅 权利。

它在项目上下文中完美运行,我可以访问两个数据库。但是,当我使用 ./manage.py test 使用 Django 测试套件时,Django 正在尝试为外部数据库创建一个测试数据库。

我不希望这样,我希望仍然能够访问测试套件中的外部 PostgreSQL 数据库,而无需在此外部 PostgreSQL 数据库上创建测试数据库。

它也给了我这个错误:

/usr/local/lib/python3.10/site-packages/django/db/backends/postgresql/base.py:323: RuntimeWarning:
Normally Django will use a connection to the 'postgres' database to avoid
running initialization queries against the production database when it's not needed
(for example, when running tests).
Django was unable to create a connection to the 'postgres' database
and will use the first PostgreSQL database instead.

但我无权访问外部数据库中的“postgres”数据库,我不想针对它运行初始化查询。

这是外部只读数据库连接的配置:

DATABASES["aact"] = {
    "ENGINE": "django.db.backends.postgresql_psycopg2",
    "OPTIONS": {"options": "-c search_path=ctgov"},
    "NAME": AACT_DATABASE_NAME,
    "USER": AACT_DATABASE_USER,
    "PASSWORD": AACT_DATABASE_PASS,
    "HOST": AACT_DATABASE_HOST,
    "PORT": AACT_DATABASE_PORT,
    "TEST": {"NAME": AACT_DATABASE_NAME, "MIGRATE": False},
}

【问题讨论】:

    标签: django postgresql unit-testing


    【解决方案1】:

    在测试中你可以选择任何你想要的数据库。

    在 settings.py 中,或者更好的是 local_settings.py:

    import sys
    
    DATABASES["aact"] = {...}
    if 'test' in sys.argv:
       DATABASES["aact"] = {settings for fake database with write permissions}
    

    其他方式 - 定义您的 DbRouter。 https://docs.djangoproject.com/en/4.0/topics/db/multi-db/#database-routers

    class BaseRouter:
        
        def db_for_read(self, model, **__):
            return "db for read"
    
        def db_for_write(self, model, **__):
            return "db for write"
    

    在 settings.py 之后:

    DATABASE_ROUTERS = ['somethere.whereis.BaseRouter']
    

    第一个例子如果快速启动。第二个帮助您更好地进行测试。

    【讨论】:

      猜你喜欢
      • 2014-07-26
      • 2014-12-07
      • 2019-02-13
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 2011-09-09
      相关资源
      最近更新 更多