pytest 助手
掌握 fixture 固件的核心用法
实现参数化测试与用例标记
熟悉常用的 pytest 插件与最佳实践
核心讲解
pytest 的强大之处在于灵活的扩展能力,固件、参数化、插件是提升自动化效率的核心。
(1)Fixture 固件用来实现测试的前置、后置操作,替代 unittest 的 setup/teardown,更灵活。
定义:
@pytest.fixture()装饰函数调用:用例参数里直接写固件名
作用域:
function(函数级,默认)、class(类级)、module(模块级)、session(会话级)后置:用
yield分隔前置和后置代码
用@pytest.mark.parametrize,把多组测试数据传入同一个用例,数据和代码分离。
给用例打标签,分组执行,比如@pytest.mark.smoke标记冒烟用例。
pytest-html:生成 HTML 测试报告pytest-rerunfailures:失败用例自动重跑pytest-xdist:多进程分布式执行,提速allure-pytest:生成专业美观的 Allure 报告pytest-ordering:控制用例执行顺序
代码示例
import pytest
# ===== fixture固件 =====
@pytest.fixture(scope="function")
def login():
print("\n=== 前置:登录系统 ===")
token = "abc123"
yield token # 返回给用例的值
print("\n=== 后置:退出登录 ===")
# 用例直接调用固件
def test_user_info(login):
print("测试用户信息,token:", login)
assert login != ""
# ===== 参数化 =====
@pytest.mark.parametrize("username, password, expected", [
("admin", "123456", True),
("user", "123456", True),
("admin", "123", False),
("", "", False)
])
def test_login(username, password, expected):
result = len(username) > 0 and len(password) >= 6
assert result == expected
# ===== 用例标记 =====
@pytest.mark.smoke
def test_smoke_case():
assert True
@pytest.mark.functional
def test_function_case():
assert True
# ===== 失败重跑配置示例 =====
# 命令行加 --reruns 2 --reruns-delay 1
# 失败自动重跑2次,每次间隔1秒
运行命令示例:
# 只运行冒烟用例
pytest -m smoke -v
# 失败重跑2次
pytest --reruns 2 test_demo.py
# 分布式并行执行
pytest -n 3 test_demo.py
常见误区
fixture 作用域理解错误:作用域越大,执行次数越少,session 级整个测试只执行一次
参数化参数名不匹配:装饰器里的参数名和函数参数名必须完全一致
插件安装后不生效:有些插件需要在 pytest.ini 里配置
滥用 fixture:不要什么都做成固件,只把公共的前后置抽出来
课后练习
用 fixture 实现测试前打开浏览器,测试后关闭浏览器
用参数化实现登录接口的 5 组不同测试数据
配置失败重跑 2 次,运行一个会失败的用例观察效果

