网络编程
位置:首页>> 网络编程>> Python编程>> pytest实现多进程与多线程运行超好用的插件

pytest实现多进程与多线程运行超好用的插件

作者:好好先生&Mr.Li  发布时间:2023-03-23 15:56:23 

标签:pytest,多进程,多线程

前言

如果想分布式执行用例,用例设计必须遵循以下原则:

1、用例之间都是独立的,
2、用例a不要去依赖用例b
3、用例执行没先后顺序,
4、随机都能执行每个用例都能独立运行成功每个用例都能重复运行,不影响其它用例
这跟就我们平常多个人工测试一样,用例都是独立的,可以随机分配不同人员执行,互相不依赖,用例之间也不存在先后顺序

一、pytest-parallel

安装:pip install pytest-parallel

常用参数配置:

  • --workers=n:多进程运行需要加此参数, n是进程数。默认为1

  • --tests-per-worker=n:多线程需要添加此参数,n是线程数

如果两个参数都配置了,就是进程并行,每个进程最多n个线程,总线程数:进程数*线程数

注意:在windows上进程数永远为1。

需要使用 if name == “main”:,在dos中运行会报错

#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @project : API_Service
# @File    : test_1.py
# @Date    : 2021/6/15 3:07 下午
# @Author  : 李文良

# demo:
import pytest

def test_01():
   print('测试用例1操作')

def test_02():
   print('测试用例2操作')

def test_03():
   print('测试用例3操作')

def test_04():
   print('测试用例4操作')

def test_05():
   print('测试用例5操作')

def test_06():
   print('测试用例6操作')

def test_07():
   print('测试用例7操作')

def test_08():
   print('测试用例8操作')

if __name__ == "__main__":
   pytest.main(["-s", "test_1.py",'--workers=2', '--tests-per-worker=4'])

pytest实现多进程与多线程运行超好用的插件

二、pytest-xdist

安装:pip install pytest-xdist

不支持多线程

常用参数配置:

  • -n=*:*代表进程数

多cpu并行执行用例,直接加个-n参数即可,后面num参数就是并行数量,比如num设置为3

  • -n auto 自动侦测系统里的CPU数目

  • -n num 指定运行测试的处理器进程数

三、对比说明

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

pytst-xdist不支持多线程,而pytest-parallel支持python3.6及以上版本,如果想做多进程并发在linux或者mac上做,在Windows上不起作用(Workers=1),如果做多线程linux/mac/windows平台都支持,进程数为workers的值。

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个线程运行。

四、特别注意

1、pytest-parallel的workers参数在windows系统下永远是1,在linux和mac下可以取不同值。
2、pytest-parallel加了多线程处理后,最后执行时间是运行时间最长的线程的时间。
3、在windows下想用多进程的选pytst-xdist; 想用多线程的选pytest-parallel

来源:https://blog.csdn.net/weixin_44275820/article/details/112169328

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com