如何配置 Postgres 以与 pytest 一起工作

how to configure Postgres to work with 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',
}