Django Pytest parallel 运行 - 数据库不存在

Django Pytest parallel run - Database does not exist

我正在使用 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

您可以首先确保您没有覆盖 conftest.py 中的 django_db_setup https://pytest-django.readthedocs.io/en/latest/database.html#django-db-setup

在我的例子中,我通过将 CPU 数量从 -n auto(在我的服务器上使用 12 个)减少到 -n 6 来降低它出现的频率,但我看到你是 运行 已经只有 4 个 CPU。也许将其减少到 -n 2 以进行测试。

我在这篇文章 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)