日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

pytest實現(xiàn)多進程與多線程運行超好用的插件_python

作者:好好先生&Mr.Li ? 更新時間: 2022-09-08 編程語言

前言

如果想分布式執(zhí)行用例,用例設(shè)計必須遵循以下原則:

1、用例之間都是獨立的,
2、用例a不要去依賴用例b
3、用例執(zhí)行沒先后順序,
4、隨機都能執(zhí)行每個用例都能獨立運行成功每個用例都能重復(fù)運行,不影響其它用例
這跟就我們平常多個人工測試一樣,用例都是獨立的,可以隨機分配不同人員執(zhí)行,互相不依賴,用例之間也不存在先后順序

一、pytest-parallel

安裝:pip install pytest-parallel

常用參數(shù)配置:

  • --workers=n:多進程運行需要加此參數(shù), n是進程數(shù)。默認為1
  • --tests-per-worker=n:多線程需要添加此參數(shù),n是線程數(shù)

如果兩個參數(shù)都配置了,就是進程并行,每個進程最多n個線程,總線程數(shù):進程數(shù)*線程數(shù)

注意:在windows上進程數(shù)永遠為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-xdist

安裝:pip install pytest-xdist

不支持多線程

常用參數(shù)配置:

  • -n=*:*代表進程數(shù)

多cpu并行執(zhí)行用例,直接加個-n參數(shù)即可,后面num參數(shù)就是并行數(shù)量,比如num設(shè)置為3

  • -n auto 自動偵測系統(tǒng)里的CPU數(shù)目
  • -n num 指定運行測試的處理器進程數(shù)

三、對比說明

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

pytst-xdist不支持多線程,而pytest-parallel支持python3.6及以上版本,如果想做多進程并發(fā)在linux或者mac上做,在Windows上不起作用(Workers=1),如果做多線程linux/mac/windows平臺都支持,進程數(shù)為workers的值。

pytest-parallel常用配置命令如下

  • –workers (optional) *:多進程運行需要加此參數(shù), *是進程數(shù)。默認為1。
  • –tests-per-worker (optional) *:多線程運行, *是每個worker運行的最大并發(fā)線程數(shù)。默認為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參數(shù)在windows系統(tǒng)下永遠是1,在linux和mac下可以取不同值。
2、pytest-parallel加了多線程處理后,最后執(zhí)行時間是運行時間最長的線程的時間。
3、在windows下想用多進程的選pytst-xdist; 想用多線程的選pytest-parallel

原文鏈接:https://blog.csdn.net/weixin_44275820/article/details/112169328

欄目分類
最近更新