django - 如何配置 Postgres 与 pytest 一起使用

标签 django postgresql django-rest-framework pytest

我使用 django 作为我的后端,并使用 pytest 来处理我的测试。

我将项目数据库从 sqlite3 切换到了 postgres,除了测试之外,一切都正常,由于某种原因,我的所有数据库都失败了。

在切换之前,我能够在测试期间使用以下行访问我的数据库:

pytestmark = pytest.mark.django_db

但现在使用 Postgres 作为我的数据库后,我在所有测试中都会遇到此错误

UndefinedTable

The above exception was the direct cause of the following exception:

request = <SubRequest '_django_db_marker' for <Function test_logged_user_saved_recipes_url_reverse>>

    @pytest.fixture(autouse=True)
    def _django_db_marker(request):
        """Implement the django_db marker, internal to pytest-django.

        This will dynamically request the ``db``, ``transactional_db`` or
        ``django_db_reset_sequences`` fixtures as required by the django_db marker.   
        """
        marker = request.node.get_closest_marker("django_db")
        if marker:
            transaction, reset_sequences = validate_django_db(marker)
            if reset_sequences:
                request.getfixturevalue("django_db_reset_sequences")
            elif transaction:
                request.getfixturevalue("transactional_db")
            else:
>               request.getfixturevalue("db")

有谁知道使用 pytest 时访问 Postgres 数据库的正确方法吗? 或者也许有办法仅在测试时切换到 sqlite3 db?

提前致谢

最佳答案

因此将此代码添加到 conftest.py 解决了我的问题

@pytest.fixture(scope='session')
def django_db_setup():
    settings.DATABASES['default'] = {
        'ENGINE': 'django.db.backends.postgres',
        'HOST': 'localhost',
        'NAME': 'postgres',
}

关于django - 如何配置 Postgres 与 pytest 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70024853/

相关文章:

python - Django 可以将多个 LDAP 身份验证映射到单个 User 对象吗?

python - 使用pygresql(pg模块)执行SQL select in语句

django - 在 Django REST 框架中进行 SlugField 验证的推荐方法是什么?

python - 从 django rest 框架中使用 api

python - 为什么我收到无反向匹配错误

django - 在 Django 模板中将 Markdown 渲染为 HTML

windows - 缓慢的本地 Windows django 开发环境

java - 如何将 Java 模式转换为 Postgres 正则表达式

sql - 使用 SQL 查询选择月销售高峰

python - 如何使用从登录 View 获得的 jwt token 进行身份验证