实现Pytest测试用例按顺序循环执行多次

要实现测试用例按顺序循环执行多次,可以使用 pytest 的自定义装饰器或插件。这里有两种方法可以实现这个需求:

方法一:使用 pytest-repeat 插件

pytest-repeat 插件允许你重复执行测试用例。你可以使用 --count 参数来指定每个测试用例的执行次数。但为了实现指定顺序的循环执行,需要手动控制测试用例的执行顺序。

安装插件

首先,安装 pytest-repeat 插件:

bash 复制代码
pip install pytest-repeat
示例代码

假设有三个测试用例 test_case1, test_case2, 和 test_case3,你可以这样写:

python 复制代码
import pytest

@pytest.mark.repeat(2)
def test_case1():
    print("Executing test_case1")

@pytest.mark.repeat(2)
def test_case2():
    print("Executing test_case2")

@pytest.mark.repeat(2)
def test_case3():
    print("Executing test_case3")
执行命令

执行以下命令来运行测试用例:

bash 复制代码
pytest --count=2

这样,每个测试用例将依次执行两次。

方法二:自定义循环逻辑

如果你希望完全控制循环执行的逻辑,可以在一个测试用例中手动调用其他测试用例。

示例代码
python 复制代码
import pytest

def test_case1():
    print("Executing test_case1")

def test_case2():
    print("Executing test_case2")

def test_case3():
    print("Executing test_case3")

def test_repeat_cases():
    for _ in range(2):  # 控制循环次数
        test_case1()
        test_case2()
        test_case3()
执行命令

直接运行这个测试脚本:

bash 复制代码
pytest -s

-s 参数允许在控制台输出打印内容。

方法三:使用 pytest 的 pytest_generate_tests 动态生成测试用例

通过 pytest 的 pytest_generate_tests 钩子函数可以动态生成测试用例,按顺序执行,并且可以控制循环次数。

示例代码
python 复制代码
import pytest

def test_case(case_number):
    print(f"Executing test_case{case_number}")

def pytest_generate_tests(metafunc):
    if "case_number" in metafunc.fixturenames:
        for _ in range(2):  # 控制循环次数
            metafunc.parametrize("case_number", [1, 2, 3], indirect=False)
执行命令

直接运行这个测试脚本:

bash 复制代码
pytest -s

输出结果:

plaintext 复制代码
Executing test_case1
Executing test_case2
Executing test_case3
Executing test_case1
Executing test_case2
Executing test_case3

结论

这些方法可以根据需求来选择。如果你需要严格的顺序和循环控制,方法二和方法三更灵活;如果你需要简单的重复执行,pytest-repeat 插件会更方便。

相关推荐
五网5 天前
软件测试用例模板怎么写:从用例设计到执行记录的全套指南
软件测试·论文阅读·全文检索·测试用例·论文笔记·用例设计·用例模板
测试界的小码农8 天前
【让 AI 生成的测试用例变成 pytest API 自动化脚本】
人工智能·测试用例·pytest
Da Da 泓13 天前
五子棋 Web 端测试用例报告
前端·网络·websocket·网络协议·测试用例·项目
会开车的鸟哥13 天前
自动创建测试用例与组件测试向导
测试用例·simuinktest
螺丝钉tina14 天前
[Playwright][08] Upload 模块自动化:如何设计真实业务测试用例?
运维·自动化·测试用例
TomEval14 天前
【测AI】第22篇:Agent 系统测试方法 — AI 学会“动手“了
人工智能·python·prompt·aigc·测试用例
车软学堂15 天前
CANoe自动化:跑起第一个测试用例
运维·车载系统·自动化·汽车·测试用例
2601_9679873715 天前
Python在自动化测试中有哪些应用?
python自动化测试·selenium·appium·pytest·性能测试
jiangbqing16 天前
测试功能点,测试用例、测试报告全流程技能直接用
功能测试·测试用例·测试用例 测试报告
自动化测试行业观察16 天前
AI智能测试用例生成技术解析:多源融合+LLM混合生成方案与实践
自动化测试·人工智能·科技·测试用例·智能化测试·ai测试平台·ai智能遍历