Pytest用例自定义 - 重复、并行、串行

简介: 面对快速迭代和持续交付的需求,提高测试效率变得至关重要。并行测试因其显著的时间节省优势而备受青睐。然而,并非所有测试都适合并行执行。在某些情况下,串行执行是必要的,以确保测试的正确性和稳定性。本文将探讨在自动化测试中部分串行、部分并行执行的必要性和实践方法,帮助测试开发者在提高测试效率的同时,确保测试结果的可靠性和准确性。

安装:

python 复制代码
pip install pytest-xdist

pip install pytest-repeat

使用案例:main.py

python 复制代码
import os

import pytest


if __name__ == "__main__":

# step-1:use pytest run test_case

pytest.main(["-s", "test_case", '-n', 'auto', "--alluredir", "./report"])


# step-2:auto report json data,zip to allure-html

os.system("allure serve report")

test_case/test_demo.py

python 复制代码
import time

import unittest



class TestDemo(unittest.TestCase):

def test_01(self):

time.sleep(5)

print('测试用例1执行')


def test_02(self):

time.sleep(5)

print('测试用例2执行')


def test_03(self):

time.sleep(5)

print('测试用例3执行')

test_case/test_parallel.py

python 复制代码
import time

import pytest



class TestParallel:

@pytest.mark.repeat(2)

def test_parallel_1(self):

time.sleep(5)

print("Parallel Test 1")


@pytest.mark.repeat(3)

def test_parallel_2(self):

time.sleep(5)

print("Parallel Test 2")


@pytest.mark.repeat(1)

def test_parallel_3(self):

time.sleep(5)

print("Parallel Test 3")


@pytest.mark.repeat(3)

def test_parallel_4(self):

time.sleep(5)

print("Parallel Test 4")

test_case/test_serial.py

python 复制代码
import time

import pytest



@pytest.mark.serial

class TestSerial:

def test_serial_1(self):

time.sleep(5)

print("Serial Test 1")


def test_serial_2(self):

time.sleep(5)

print("Serial Test 2")

配置文件:pytest.ini

python 复制代码
# pytest.ini

[pytest]

markers =

serial: mark test to run serially

运行结果:

注意事项:

1、同一文件中混合串行和并行测试,并且需要更精细的控制,可能需要编写更复杂的自定义逻辑或查找是否有现成的插件能满足这种特定的需求。

2、不关心执行顺序,简单地将 -n 参数设置为 auto,让 pytest-xdist 插件自动管理并行执行,通常是最简单也是最有效的方法。

**结论:**适当拆分错开并行和串行的测试类,通过pytest-xdist auto参数,可以便捷有效的大幅度提升运行测试用例的效率。

行动吧,在路上总比一直观望的要好,未来的你肯定会感 谢现在拼搏的自己!如果想学习提升找不到资料,没人答疑解惑时,请及时加入扣群: 320231853,里面有各种软件测试+开发资料和技术可以一起交流学习哦。

最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!

相关推荐
麦麦大数据18 小时前
F024 vue+flask电影知识图谱推荐系统vue+neo4j +python实现
vue.js·python·flask·知识图谱·推荐算法·电影推荐
say_fall18 小时前
精通C语言(4.四种动态内存有关函数)
c语言·开发语言
AI小云18 小时前
【Python与AI基础】Python编程基础:读写CSV文件
人工智能·python
暴力求解18 小时前
c++类和对象(下)
开发语言·c++·算法
Goboy18 小时前
Python修仙入门 - 踏入仙门的第一步
后端·python
应用市场18 小时前
Qt插件机制实现动态组件加载详解
开发语言·qt
小秋学嵌入式-不读研版18 小时前
C65-枚举类型
c语言·开发语言·笔记
程序员爱钓鱼18 小时前
Python编程实战 · 基础入门篇 | 什么是Python
后端·python
程序猿小D18 小时前
【完整源码+数据集+部署教程】遥感图像道路检测分割系统源码和数据集:改进yolo11-CARAFE
python·yolo·计算机视觉·目标跟踪·数据集·yolo11·遥感图像道路检测分割系统
zy_destiny19 小时前
【工业场景】用YOLOv8实现人员打电话识别
人工智能·python·深度学习·yolo·机器学习·计算机视觉·目标跟踪