python并行跑两个case_python-pytest使用(4)-多线程多进程运行

本文介绍了如何使用pytest-xdist和pytest-parallel进行Python测试的多进程、多线程并行运行。pytest-parallel在Windows上不支持多进程,但支持多线程,而pytest-xdist仅支持多进程。通过实例展示了不同参数配置对测试执行时间的影响,并给出了相应的命令行用法。
摘要由CSDN通过智能技术生成

本篇单独整理下,针对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 pytest

import time

def 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 I

gw0 [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 pytest

import time

def 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值