You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

配置Heroku以并行运行Django单元测试(基于pytest)

在Heroku上配置pytest并行运行Django单元测试

1. 安装并行测试依赖

需要添加pytest-xdist(pytest官方并行插件)到项目依赖中:

  • 若使用requirements.txt,添加:
pytest-xdist>=3.5.0
  • 若使用pyproject.toml,在开发依赖中添加:
[project.dev-dependencies]
pytest-xdist = ">=3.5.0"

2. 修改app.json的测试脚本

更新测试命令,加入并行运行参数:

  • -n auto:让pytest根据测试实例的CPU核心数自动分配进程
  • 也可指定固定进程数,比如-n 4强制用4个进程

修改后的app.json测试环境配置:

{
  ...
  "environments": {
    "review": {
      ...
    },
    "test": {
      "scripts": {
        "test": "pytest -v -n auto --cov=app-name --cov-fail-under=90",
        "integration-test": "pytest -v -n auto -m integration"
      },
      "env": {
        ...
      },
      "formation": {
        "test": {
          "quantity": 1,
          "size": "standard-1x"
        }
      },
      "buildpacks": [
        {
          "url": "heroku/python"
        }
      ]
    }
  }
}

3. 关键注意事项

  • 确保测试用例进程安全:不要依赖全局共享状态,Django的pytest插件默认会处理数据库隔离,但自定义全局变量需额外清理
  • 覆盖率统计兼容:pytest-cov已支持并行模式,无需额外配置,会自动合并各进程的覆盖率数据
  • 匹配实例资源:Heroku standard-1x实例有2个CPU核心,-n auto会自动启用2个进程;若需更多进程,可升级实例规格(如standard-2x有4核心)

内容的提问来源于stack exchange,提问作者Dos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 09:42:31