博客
关于我
pytest单元测试框架
阅读量:797 次
发布时间:2023-03-05

本文共 2033 字,大约阅读时间需要 6 分钟。

Python 单元测试框架 pytest 实用指南

一、单元测试框架概述

单元测试是软件开发中对功能的最小单元进行验证和测试的过程。Pytest 是一个成熟的 Python 单元测试框架,相较于 unittest,更灵活且易于上手。

二、Pytest 常用功能

1. 安装

通过 pip 安装 pytest:

pip install pytest

安装插件(如 HTML 报告、分布式执行等):

pip install -r requirements.txt

2. 测试用例结构

  • 模块命名:以 test__test 结尾。
  • 测试类:命名为 TestXxx,不含 __init__ 方法。
  • 测试方法:以 test_ 开头。

3. 测试运行方式

  • 单独文件运行
    pytest test_print.py
  • 目录运行
    pytest ./tests
  • 特定用例运行
    pytest ./tests/test_print.py::TestPrint::test_01_demo

4. 核心参数解析

  • -s:输出 debug 信息。
  • -v:详细日志。
  • -n:多线程执行(如 -n 2)。
  • --reruns:失败后重试(如 --reruns=2)。

5. 测试顺序

Pytest 默认按文件顺序运行,可以通过 @pytest.mark.run(order=1) 更改顺序。

6. 测试分组

用于冒烟测试或模块分组执行:

@pytest.mark.smokedef test_01_baili(self):    print("测试百里")

使用命令运行指定分组:

pytest -m "smoke or usermanage"

三、Pytest 实用技巧

1. 跳过用例

  • 无条件跳过
    @pytest.mark.skipdef test_03():    print("测试3")
  • 有条件跳过
    @pytest.mark.skipif(condition, reason="原因")

2. 接口自动化

结合 requests 库实现接口测试:

  • 请求方法
    import requestsresponse = requests.post(url, json=data)response.status_code # 获取状态码response.json()     # 解析 JSON
  • ** yaml 文件管理**:
    import yamldef read_yaml(key):    with open('extract.yml', 'r') as f:        data = yaml.load(f)    return data[key]

3. 测试报告

集成 allure 生成美观报告:

allure generate ./temp -o ./report

默认生成 HTML 格式报告。

四、Pytest 高级功能

1. 固件(Fixture)

  • 作用域控制
    @pytest.fixture(scope="function")def exec_database_sql():    print("前置操作-===数据库查询")    yield    print("后置操作=====数据校验")
  • 数据驱动测试
    @pytest.fixture(params=["测试1", "测试2"])def param_info(self):    yield param_info

2. 会话管理

通过 conftest.py 文件管理固件会话:

@pytest.fixture(scope="session", autouse=True)def exec_database_sql():    clear_yaml()    print("前置操作-===所有请求前执行一次")    yield    print("后置操作=====所有请求之后执行一次")

五、Pytest 常见问题解答

1. 如何跳过测试?

使用 @pytest.mark.skip@pytest.mark.skipif 注解。

2. 如何实现分布式测试?

使用 pytest-xdist 插件,通过 -n 参数指定线程数。

3. 如何生成测试报告?

使用 allure 插件,通过命令生成 HTML 报告。

4. 如何管理多个测试用例?

通过 @pytest.mark.parametrize 参数化测试用例:

@pytest.mark.parametrize("param_info,[['测试1'], ['测试2']]")def test_01(self, param_info):    print(param_info)

六、结语

Pytest 是 Python 开发者必须掌握的工具,通过上述实用技巧,您可以高效地编写、执行和分析单元测试。希望这篇指南能为您的测试工作带来帮助!

转载地址:http://ajafk.baihongyu.com/

你可能感兴趣的文章
Protobuf - 语法、字段使用规则、注意事项
查看>>
protobuf —— 快速上手
查看>>
protobuf —— 认识和安装
查看>>
Protobuf 三个关键字required、optional、repeated的理解
查看>>
ProtoBuf 原理详解
查看>>
Protobuf 实例(java)
查看>>
ProtoBuf 实际应用(java)
查看>>
Protobuf 属性解释
查看>>
Protobuf 编译工具转换 Java 类
查看>>
protobuf使用详解
查看>>
ProtoBuf在使用protoc进行编译时提示: Required fields are not allowed in proto3
查看>>
Protobuf学习 - 入门
查看>>
protobuf对象与JSON相互转换
查看>>
ProtoBuf的介绍以及在Java中使用protobuf将对象进行序列化与反序列化
查看>>
protocol学习笔记001---RPC和HTTP协议之间的区别_与各自优势
查看>>
protostuff简单应用
查看>>
PRover 开源项目教程
查看>>
PyTorch-Tutorials【pytorch官方教程中英文详解】- 4 Transforms
查看>>
Proxy server 緩存 jsp html
查看>>
Proxy 和 Reflect 结合实现代理和拦截( 代码示例 )
查看>>