首页 > 解决方案 > Django Pytest 并行运行 - 数据库不存在

问题描述

我正在使用 pytest 运行我的 django 测试,并试图通过并行运行它们来加速它们。我尝试使用环境变量修改我的数据库名称,PYTEST_XDIST_WORKER但我的测试仍然无法访问数据库。

我需要如何在我的 django 配置中设置我的数据库设置,以便创建和使用并行数据库。

db_suffix = env.str("PYTEST_XDIST_WORKER", "")
DATABASES["default"]["NAME"] = f"""{DATABASES["default"]["NAME"]}_{db_suffix}"""

pytest.ini

[pytest]
addopts = --ds=config.settings.test --create-db
python_files = tests.py test_*.py
norecursedirs = node_modules
env_files=
    .env.tests

运行测试的命令:pytest -n 4

错误:database "auto_tests_gw0" does not exist

标签: pythondjangopytest

解决方案


我在这篇文章https://iurisilv.io/2021/03/faster-parallel-pytest-django.html中找到了解决这个问题的方法。您需要覆盖数据库后缀夹具。

@pytest.fixture(scope="session")
def django_db_modify_db_settings_xdist_suffix(request):
    skip_if_no_django()

    xdist_suffix = getattr(request.config, "workerinput", {}).get("workerid")
    if xdist_suffix:
        # 'gw0' -> '1', 'gw1' -> '2', ...
        suffix = str(int(xdist_suffix.replace("gw", "")) + 1)
        _set_suffix_to_test_databases(suffix=suffix)

推荐阅读