运行 并行测试时出错

Errors when running tests in parallel

当我尝试 运行 并行测试时出现多个问题。

根据文档,"test_" 被添加到 DATABASES 中指定的数据库名称之前。我用了名字"postgres",所以运行ning测试时创建的数据库叫test_postgres。 运行ning 并行测试时,会创建以下数据库(这是预期的):test_postgres_1test_postgres_2 test_postgres_3test_postgres_4。但是,当 运行 使用 --parallel=4 选项对所有测试进行测试时,每个测试都会失败并显示以下消息:django.db.utils.OperationalError: FATAL: database "postgres_x" does not exist 其中 x 可以是 1、2、3 或 4。我可以看到已创建以下数据库:test_postgres_x 其中 x 可以是 1、2、3 或 4。"postgres_x" 来自哪里?为什么 "test_" 没有放在这些前面?

此外,如果我手动创建预期的数据库 postgres_x(x = 1 到 4),应用于 "main" 数据库的迁移不会应用于克隆。这会导致如下错误:django.db.utils.ProgrammingError: relation "users_user" does not exist。使用 4 核时大约有 1/4 的测试通过。

最后,如果我尝试使用 migrate --database=postgres_x 迁移 postgres_x,我得到:django.db.utils.ConnectionDoesNotExist: The connection postgres_x doesn't exist

我已确保所有测试都是独立的,这样我就可以 运行 并行进行它们。我该怎么办?

我建议使用 pytestpytest-djangopytest-xdist,而不是自己构建测试工具,这将为每个并行工作程序处理数据库创建和迁移。 (pytest 可以 运行 Django UnitTest 测试无需修改)