我使用 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/