python - 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
解决方案
我在这篇文章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)
推荐阅读
- ecmascript-6 - 从 ES6 箭头函数返回对象文字
- java - Java 11 中的 VertX 服务代理引发 TimeTrackingProcessor 警告
- c# - 在后端使用 TFL api - C#,在前端使用 React.js
- javascript - 如何动态(通过路径)更新 React 状态属性
- javascript - JavaScript 中的石头剪刀布游戏。无限循环问题
- flutter - Dart jsonEncode 给我错误 Unhandled Exception: Converting object to an encodable object failed
- java - 如何在 java 中获得对 http 的响应?
- javascript - 客户端 JS 函数中 Facebook / Instagram 的访问令牌
- java - Libgdx 使 scrollPane 不需要单击交互来启动滚动
- r - 带有百分比的 R 饼图