xqqlyx

pytest 5 种核心测试场景的 极简示例

pytest 5 种核心测试场景的 极简示例(含代码+执行命令):

1. 全量测试(默认)

核心逻辑:执行所有符合命名规则的用例(test_*.py/test_* 函数)

示例代码(test_all.py)

def test_add():
    assert 1 + 2 == 3

def test_multiply():
    assert 3 * 4 == 12

执行命令

pytest test_all.py -v  # -v 显示详细结果

2. 冒烟测试(核心功能验证)

核心逻辑:用 @pytest.mark.smoke 标记核心用例,仅执行标记用例

步骤1:注册标记(项目根目录创建 pytest.ini)

[pytest]
markers =
    smoke: 冒烟测试(核心功能)

步骤2:测试代码(test_smoke.py)

import pytest

@pytest.mark.smoke  # 标记核心用例
def test_login():  # 核心功能:登录
    assert "success" == login("user1", "pass1")  # 假设 login 是业务函数

def test_logout():  # 非核心功能,不标记
    assert "success" == logout()

执行命令

pytest -m smoke -v  # 仅执行 smoke 标记的用例

3. 回归测试(验证代码修改不影响旧功能)

核心逻辑:代码修改后,重新执行历史用例(通常结合全量/选择性测试)

示例代码(test_regression.py,修改前已存在的用例)

def test_old_func1():  # 旧功能1
    assert len("hello") == 5

def test_old_func2():  # 旧功能2
    assert "a" in ["a", "b", "c"]

执行命令(生成报告更清晰)

pytest test_regression.py --html=report.html -v  # 执行旧用例并生成HTML报告

4. 参数化测试(一套逻辑测多场景)

核心逻辑:用 @pytest.mark.parametrize 传多组参数,批量验证

示例代码(test_param.py)

import pytest

# 多组参数:(输入1, 输入2, 预期结果)
@pytest.mark.parametrize("a, b, expected", [
    (1, 2, 3),    # 正常场景
    (-1, -2, -3), # 负数场景
    (0, 5, 5)     # 含0场景
])
def test_add_param(a, b, expected):
    assert a + b == expected

执行命令

pytest test_param.py -v  # 自动执行3组参数,分别验证

5. 并发测试(多进程加速执行)

核心逻辑:用 pytest-xdist 插件多进程并行执行,缩短大规模用例时间

步骤1:安装插件

pip install pytest-xdist

步骤2:测试代码(test_concurrent.py,假设用例较多)

def test_case1():
    assert 1 == 1

def test_case2():
    assert 2 == 2

# 可添加更多用例(比如100个,并发效果更明显)

执行命令

pytest test_concurrent.py -n 4 -v  # 4个进程并行执行(根据CPU核数调整)
# 或 pytest -n auto -v  # 自动适配CPU核数

posted on 2025-11-26 15:21  烫烫烫烫热  阅读(0)  评论(0)    收藏  举报