首页 > 解决方案 > Pytest Xdist 并行执行,防止重新创建数据库

问题描述

我正在尝试通过使用 4 个线程的并行执行 (-n=4) 来加速我的 python Django Web 应用程序中的 Selenium 测试

在前 4 个测试中,3 个给出以下错误:

[test setup] [Test Error Output]
Got an error creating the test database: (1007, "Can't create database 'test1database'; database exists")

我知道我必须指定在并行测试执行之前运行一次设置,以防止多次尝试创建数据库,但是我将如何在 pytest xdist 配置中强制执行此操作?

标签: seleniumpytestxdistpytest-xdist

解决方案


对于每个线程,您可能有一个不同的数据库。夹具允许您这样worker_idhttps://github.com/pytest-dev/pytest-xdist#identifying-the-worker-process-during-a-test

@pytest.fixture()
def test_database(worker_id):
    return CreateDatabase("test{}database".format(worker_id))

更新

github 问题评论显示了 OP 原始问题的解决方案。它还使用共享模板创建 N 个数据库。这带来了一个有趣的转折,即同步对夹具中共享资源的访问。


推荐阅读