如何用pytest实现多线程多进程执行用例?

摘要:有些项目的测试用例较多,测试用例时需要分布式执行,缩短运行时间。 pytest框架中提供可用于分布式执行测试用例的插件:pytest-parallel、pytest-xdist,接下来我们来学习这两个插件的使用方法。 pytest-para
有些项目的测试用例较多,测试用例时需要分布式执行,缩短运行时间。 pytest框架中提供可用于分布式执行测试用例的插件:pytest-parallel、pytest-xdist,接下来我们来学习这两个插件的使用方法。 pytest-parallel pytest-parallel 同时支持多线程、多进程两种方式执行测试用例。 安装 安装命令:pip install pytest-parallel==0.0.10 注意,虽然最新的版本为 0.1.1,但在windows系统中需要指定安装 0.0.10 版本,否则使用 pytest-parallel 参数执行用例时会报如下错误,其他系统暂未尝试。 AttributeError: Can't pickle local object 'pytest_addoption.<locals>.label_type.<locals>.a_label_type' 参数说明 pytest-parallel 提供参数执行测试用例,示例如下: if __name__ == '__main__': pytest.main(['-s', 'testcase/test_case.py', '--workers=1', '--tests-per-worker=3']) 参数说明: --workers=n 指定运行的进程数为 n,默认为1,windows系统中只能为1 --tests-per-worker=m 指定运行的线程数为 m 若两个参数都指定,则表示启动n个进程,每个进程最多启动m线程执行,总线程数=进程数*线程数 windows系统中不支持 --workers 取其他值,即只能为1,mac或linux系统中可取其他值 使用 接下来举例进行说明。 测试用例模块 test_case.py: import pytest import time def test_01(): print("执行test_01") time.sleep(3) def test_02(): print("执行test_02") time.sleep(4) def test_03(): print("执行test_03") time.sleep(5) def test_04(): print("执行test_04") time.sleep(6) 不使用 pytest-parallel 执行用例: if __name__ == '__main__': pytest.main(['-s', 'testcase/test_case.py']) # 执行结果如下: collected 4 items testcase\test_case.py .执行test_01 .执行test_02 .执行test_03 .执行test_04 ============================= 4 passed in 18.05s ============================== 使用 pytest-parallel 分布式执行用例: if __name__ == '__main__': pytest.main(['-s', 'testcase/test_case.py', '--workers=1', '--tests-per-worker=3']) # 执行结果如下: collected 4 items pytest-parallel: 1 worker (process), 3 tests per worker (threads) 执行test_01 执行test_03执行test_02 .执行test_04 ... ============================== 4 passed in 9.04s ============================== 从以上结果可以看出来: 不使用 pytest-parallel 执行 test_case.py 中的测试用例所用时间为18.05s 使用 pytest-parallel 执行 test_case.py 中的测试用例,当 --workers=1、--tests-per-worker=3 时所用时间为9.04s pytest-xdist pytest-xdist 只支持多进程执行测试用例,不支持多线程执行。
阅读全文