pytest常用命令行参数解析

简介:pytest作为一个成熟的测试框架,它提供了许多命令行参数来控制测试的运行方式,以配合适用于不同的测试场景。例如 -x 可以用于希望出现错误就停止,以便定位和分析问题。--reruns=num适用于希望进行失败重跑等个性化测试策略。

历史攻略:

Pytest+Yaml 数据驱动测试用例

常用命令行参数,案例解析:

python 复制代码
"-s": 输出调试信息,包括 print 打印的信息。这通常在调试时使用,因为它会显示测试用例中的所有 print 输出。

"-v": 显示更详细的信息,包括测试用例的名称、执行状态(通过、失败、错误、跳过等)、执行时间以及任何与测试用例相关的输出或日志信息。

"-n=num": 启用多线程或分布式运行测试用例。这需要安装 pytest-xdist 插件模块。它允许你指定并行运行的测试用例数量。

"-k=value": 只执行用例的 nodeid 包含指定值的用例。这可以用于根据表达式匹配并运行特定的测试用例。

"-m"=标签名: 执行被 @pytest.mark.标签名 标记的用例。这允许你根据定义的标签来过滤和运行测试用例。

"-x": 一旦有任何一个用例执行失败,就停止当前线程的测试执行。

"--maxfail=num": 与 -x 功能相似,但允许指定失败用例的最大数量后停止执行。

"--reruns=num": 失败用例重跑指定次数。这需要安装 pytest-rerunfailures 插件模块。

程序主入口代码:

python 复制代码
# -*- coding: utf-8 -*-
# time: 2024/5/12 17:46
# file: main.py
# 公众号: 玩转测试开发
import os
import pytest

if __name__ == "__main__":
    """
    "-s": 输出调试信息,包括 print 打印的信息。这通常在调试时使用,因为它会显示测试用例中的所有 print 输出。
    "-v": 显示更详细的信息.
    "-n=num": 启用多线程或分布式运行测试用例。这需要安装 pytest-xdist 插件模块。允许并行运行的测试用例数量。
    "-k=value": 只执行用例的 nodeid 包含指定值的用例。这可以用于根据表达式匹配并运行特定的测试用例。
    "-m"=标签名: 执行被 @pytest.mark.标签名 标记的用例。这允许你根据定义的标签来过滤和运行测试用例。
    "-x": 一旦有任何一个用例执行失败,就停止当前线程的测试执行。
    "--maxfail=num": 与 -x 功能相似,但允许指定失败用例的最大数量后停止执行。
    "--reruns=num": 失败用例重跑指定次数。这需要安装 pytest-rerunfailures 插件模块。
    """
    pytest.main(["-s", "./tests/test_demo.py", "--alluredir", "./report"])

    # 步骤2:将生成的测试报告json数据,打包生成allure-HTML报告格式
    os.system("allure serve report")

测试用例:

python 复制代码
# -*- coding: utf-8 -*-
# time: 2024/5/12 17:47
# file: test_demo.py
# 公众号: 玩转测试开发
import pytest
import random


class TestDemo(object):

    @pytest.mark.repeat(10)
    def test_01(self):
        res = random.randint(0, 10)
        pytest.assume(res > 2)
    
    @pytest.mark.repeat(10)
    def test_02(self):
        res = random.randint(0, 10)
        pytest.assume(res > 1)

-x: 一旦有任何一个用例执行失败,就停止当前线程的测试执行。

python 复制代码
pytest.main(["-s", "-x", "./tests/test_demo.py", "--alluredir", "./report"])

--maxfail=num: 与 -x 功能相似,但允许指定失败用例的最大数量后停止执行。

python 复制代码
pytest.main(["-s", "--maxfail=3", "./tests/test_demo.py", "--alluredir", "./report"])

"--reruns=num": 失败用例重跑指定次数。

python 复制代码
pytest.main(["-s", "--reruns=3", "./tests/test_demo.py", "--alluredir", "./report"])

"-n=num": 启用多线程或分布式运行测试用例。这需要安装 pytest-xdist 插件模块。允许并行运行的测试用例数量,当设置为auto时,设置为CPU核心数,效率最高。

python 复制代码
pytest.main(["-s", "-n=auto", "./tests/test_demo.py", "--alluredir", "./report"])
相关推荐
XXX-1718 小时前
1.pytest基础知识(默认的测试用例的规则以及基础应用)
软件测试·pytest
Mavis先生2 天前
PyTest装饰器
pytest
神即道 道法自然 如来4 天前
Python+Pytest框架,“main_run.py文件怎么编写“?
java·python·pytest
___Dream5 天前
【项目一】基于pytest的自动化测试框架———解读requests模块
python·计算机网络·pytest
ccy加油呀7 天前
pytest 接口测试
android·pytest
云泽野9 天前
一篇文章了解Pytest单元测试框架
服务器·单元测试·pytest
___Dream10 天前
【项目一】基于pytest的自动化测试框架day1
pytest
这不巧了10 天前
Faker在pytest中的应用
python·自动化·pytest
测试界的海飞丝11 天前
pytest运行方式及前置后置封装详解
开发语言·selenium·单元测试·pytest
什么时候才能变强11 天前
Pytest-@pytest.fixture夹具篇(一)
pytest