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

pytest是否支持并行执行同一组测试用例?

如何在pytest中并行执行同一组测试?

当然可以实现!pytest本身没有直接提供“重复运行同一测试并并行执行”的原生功能,但搭配两个常用插件就能轻松搞定——pytest-repeat负责重复测试,pytest-xdist负责并行调度,完美匹配你的需求。

步骤1:安装所需插件

先通过pip安装这两个插件:

pip install pytest-repeat pytest-xdist

步骤2:执行并行重复测试

假设你想把示例中的test_add测试重复运行5次,并且让这些重复的测试并行执行,只需要在命令行运行:

pytest -n auto --count=5 your_test_file.py

这里的参数解释下:

  • -n auto:让pytest-xdist自动检测你机器的可用CPU核心数,分配对应数量的并行进程
  • --count=5:告诉pytest-repeat要把每个测试用例重复执行5次

结合你提供的示例代码,你的user_number fixture用到了worker_id参数,所以每一次并行运行的测试都会拿到不同的worker标识(比如gw0、gw1等),运行后你会看到类似这样的输出,证明多个测试在同时执行:

Adding 1+1 and returning the result and user number: user number : gw0
Adding 1+1 and returning the result and user number: user number : gw1
Adding 1+1 and returning the result and user number: user number : gw2
...

进阶用法

  • 如果你只想重复并并行执行特定测试(而不是整个文件的所有测试),可以用-k参数指定测试名:
pytest -n 3 --count=10 -k test_add your_test_file.py

这里-n 3是手动指定用3个并行进程,--count=10是重复10次,-k test_add只针对这个测试生效。

  • 如果你希望重复的测试在报告中显示为独立条目(比如带编号),可以加上--repeat-scope=function(默认就是function级,所以不加也没问题,但明确指定会更清晰)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:36:27