【Pytest】从配置到固件的使用指南

发布于:2025-07-23 ⋅ 阅读:(17) ⋅ 点赞:(0)

掌握高效测试的关键技巧,打造专业级自动化测试框架

一、Pytest框架的核心优势

Pytest作为Python最强大的测试框架之一,以其简洁灵活的语法和丰富的扩展能力深受开发者喜爱。相比unittest,Pytest提供了更直观的测试编写方式和更强大的功能集:

  • 零样板代码:无需继承特定类,函数即测试用例
  • 丰富的断言:自动展示断言失败时的差异信息
  • 插件生态系统:超过1000个插件扩展功能
  • 参数化测试:轻松实现数据驱动测试
  • 兼容性强:完美兼容unittest和nose测试套件

二、Pytest命令行参数化执行大全

1. 基础执行参数

# 显示详细测试信息
pytest.main(["-v"])

# 输出print语句内容
pytest.main(["-s"])

# 组合使用
pytest.main(["-vs"])

2. 测试筛选参数

# 指定标签执行(冒烟测试)
pytest.main(["-m", "smoke"])

# 按关键字筛选用例
pytest.main(["-k", "login"])

# 仅执行上次失败的用例
pytest.main(["--lf"])

# 指定测试文件
pytest.main(["test_login.py"])

3. 测试控制参数

# 遇到第一个失败用例时停止
pytest.main(["-x"])

# 最多允许2个失败
pytest.main(["--maxfail=2"])

# 仅收集测试项不执行
pytest.main(["--collect-only"])

4. 报告生成参数

# 生成JUnit格式报告
pytest.main(["--junit-xml=report.xml"])

# 生成HTML测试报告
pytest.main(["--html=report.html"])

# 生成带截图的报告(需配合插件)
pytest.main(["--html=report.html", "--self-contained-html"])

三、pytest.ini全局配置详解

1. 配置文件规范

[pytest]
# 默认命令行参数
addopts = -vs --tb=short

# 自定义标记注册
markers =
smoke: 冒烟测试用例
regression: 回归测试用例
performance: 性能测试用例

# 测试文件匹配规则
python_files = test_*.py

# 测试目录配置
testpaths = tests

# 测试类命名规则
python_classes = Test*

# 测试方法命名规则
python_functions = test_*

2. 配置效果说明表

配置项 功能说明 推荐值
addopts 默认命令行参数 -vs --tb=short
markers 自定义标记注册 按团队规范定义
python_files 测试文件匹配模式 test_*.py
testpaths 测试目录路径 tests
norecursedirs 排除目录 .venv node_modules
junit_suite_name JUnit报告名称 ${project} Tests

四、测试用例跳过策略详解

1. 无条件跳过

@pytest.mark.skip(reason="功能尚未实现")
def test_unimplemented_feature():
# 此测试暂不执行
assert False

2. 条件跳过

import sys

# 根据Python版本跳过
@pytest.mark.skipif(
sys.version_info < (3, 8),
reason="需要Python 3.8+的特性支持"
)
def test_walrus_operator():
assert (result := complex_calculation()) > 0

3. 运行时动态跳过

def test_environment_specific():
# 仅当环境变量PROFILE=production时执行
if os.environ.get("PROFILE") != "production":
pytest.skip("仅在生产环境执行")

# 生产环境专属测试逻辑
assert production_only_feature() is True

4. 跳过模块所有测试

import pytest

if not config.ENABLE_MODULE_A:
pytest.skip("模块A测试已禁用", allow_module_level=True)

五、测试固件(fixture)高级应用

1. 基础fixture使用

import pytest

@pytest.fixture
def database_connection():
# 前置操作:建立数据库连接
conn = create_db_connection()
yield conn# 测试用例在此处执行
# 后置操作:关闭连接
conn.close()

def test_query(database_connection):
result = database_connection.execute("SELECT 1")
assert result == 1

2. 作用域控制

@pytest.fixture(scope="module")
def shared_resource():
# 整个测试模块共享的资源
print("\n初始化资源")
resource = Resource()
yield resource
print("\n释放资源")
resource.release()

作用域选项对比:

作用域 生命周期 适用场景 执行次数(100测试用例)
function 每个测试函数 默认值,独立测试环境 100次
class 每个测试类 类内多测试共享 按类数量执行
module 每个模块 模块级资源共享 按模块数量执行
session 整个测试会话 全局资源共享 1次

3. 参数化fixture

@pytest.fixture(params=["mysql", "postgres", "sqlite"])
def database(request):
db = Database(request.param)
db.connect()
yield db
db.disconnect()

def test_db_compatibility(database):
assert database.version() >= "5.7"

4. 自动使用fixture

@pytest.fixture(autouse=True)
def global_setup_teardown():
# 1. 所有测试前执行
print("\n=== 全局测试开始 ===")

# 2. 测试执行
yield

# 3. 所有测试后执行
print("\n=== 全局测试结束 ===")

5. fixture重写机制

# conftest.py
@pytest.fixture(scope="session")
def config():
return load_config("default.json")

# test_prod.py
@pytest.fixture(scope="session")
def config():
return load_config("production.json")

Pytest最佳实践总结

配置集中化:通过pytest.ini统一管理配置
用例原子化:每个测试只验证一个功能点
命名规范化:test_前缀+描述性名称
固件轻量化:避免在fixture中放业务逻辑
报告可视化:结合Allure生成专业报告