python 您所在的位置:网站首页 python多线程并发执行用例 python

python

2024-07-15 15:32| 来源: 网络整理| 查看: 265

python-pytest使用(4)-多线程多进程运行

原创:George555    公众号:测试江湖路 天

如果这些内容对你有帮助,也可以打开微信扫一扫,加关注:

    本篇单独整理下,针对pytest中关于pytest-xdist和pytest-parallel 的多进程,多线程使用,主要以案例为主进行说明。

一、需要安装如下环境:

    pip install pytest-xdist 或  

    pip install pytest-parallel

二、对比说明:

    pytest-parallel比pytst-xdist相对好用,功能支持多。

    pytest-xdist不支持多线程,

    而pytest-parallel支持python3.6及以上版本,如果是想做多进程并发的需要在linux平台或mac上做,windows上不起作用即(workers永远=1),如果是做多线程的Linux/Mac/Windows平台都支持,进程数为workers设置的值。

三、pytest-xdist常用命令配置如下:

    -n:进程数,也就是cpu个数 可以指定个数,最大值为当前机器cpu个数,也可以设置为auto,自动识别cpu个数。

    示例:pytest -s test_multiProcess.py -n=2    #用2个进程运行py用例文件

    细节使用参照官网:https://pypi.org/project/pytest-xdist/

import pytestimport timedef testcase_01(): time.sleep(2) print('这里是testcase_01')def testcase_02(): time.sleep(4) print('这里是testcase_02')def testcase_03(): time.sleep(5) print('这里是testcase_03')if __name__ == '__main__': pytest.main(['-s',__file__,'-n=4']) #输出......gw0 I / gw1 I / gw2 I / gw3 Igw0 [3] / gw1 [3] / gw2 [3] / gw3 [3]...============ 3 passed in 6.81s ======== #总结:非多进程:9.07s 1cpu:10.59s 2cpu:7.72s 3cpu:4.98s 4cpu:5.32s

四、pytest-parallel常用配置命令如下:

    –workers (optional)  *:多进程运行需要加此参数,  *是进程数。默认为1。

    –tests-per-worker (optional)  *:多线程运行, *是每个worker运行的最大并发线程数。默认为1

    使用示例:

    pytest test.py --workers 3:3个进程运行

    pytest test.py --tests-per-worker 4:4个线程运行

    pytest test.py --workers 2 --tests-per-worker 4:2个进程并行,且每个进程最多4个线程运行,即总共最多8个线程运行。

    参考:https://pypi.org/project/pytest-parallel/

代码示例:

import pytestimport timedef testcase_01(): time.sleep(2) print('这里是testcase_01')def testcase_02(): time.sleep(4) print('这里是testcase_02')def testcase_03(): time.sleep(5) print('这里是testcase_03')def testcase_04(): time.sleep(9) print('这里是testcase_04')if __name__ == '__main__':    pytest.main(['-s', __file__,'--workers=1','--tests-per-worker=4'])  #总结:单线程:20.08s(单个线程累计时长) #2个线程:13.06    3个线程:11.05    4个线程:9.06

【特别注意】:

    1.pytest-parallel的workers参数在windows系统下永远是1,在linux和mac下可以取不同值。

    2..pytest-parallel加了多线程处理后,最后执行时间是运行时间最长的线程的时间。

    3.在windows下想用多进程的选pytst-xdist; 想用多线程的选pytest-parallel

 

 

#####欢迎大家加群交流####

QQ:464314378

微信群请先加群主微信,群主会拉各位小伙伴进群,注意添加备注。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有