有些项目的测试用例较多,测试用例时需要分布式执行,缩短运行时间。
pytest框架中提供可用于分布式执行测试用例的插件:pytest-parallel、pytest-xdist,接下来我们来学习这两个插件的使用方法。
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接下来举例进行说明。
测试用例模块test_case.py:
import pytestimport timedef 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 itemstestcase\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 itemspytest-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只支持多进程执行测试用例,不支持多线程执行。
安装命令:pip install pytest-xdist
pytest-xdist 提供参数执行测试用例,示例如下:
if __name__ == '__main__': pytest.main(['-s', 'testcase/test_case.py', '-n=4'])参数说明:
-n= 指定进程数,如 -n=4 表示开启4个cpu进行执行测试用例。pytest-xdist支持windows系统使用,同样也支持mac、linux。使用 pytest-xdist 分布式执行用例:
if __name__ == '__main__': pytest.main(['-s', 'testcase/test_case.py', '-n=4']) # 执行结果如下:plugins: allure-pytest-2.9.45, forked-1.4.0, html-2.1.1, metadata-1.10.0, ordering-0.6, parallel-0.0.10, rerunfailures-9.1.1, xdist-2.5.0gw0 I / gw1 I / gw2 I / gw3 Igw0 [4] / gw1 [4] / gw2 [4] / gw3 [4]....============================== 4 passed in 7.19s ==============================从结果可以看出来,使用pytest-xdist执行 test_case.py 中的测试用例,当 -n=4 时所用时间为7.19s
pytest-parallel支持多线程执行用例,但在windows系统中只支持单个进程执行,即windows中只能--workers=1。
pytest-xdist只支持多进程执行用例,但可以在windows系统中进行参数设置。
推荐使用pytest-parallel,因为支持多线程执行,且自动化测试项目一般会搭建在mac或linux系统中运行,--workers 可以取别的值。
在使用过程中可能会遇到其他一些问题,欢迎评论探讨。