Pytest是Python中最流行的测试框架之一,相比Python自带的unittest框架,Pytest具有以下优势:
特性 | unittest | pytest |
---|---|---|
安装方式 | 无需安装 | 手动安装 |
版本管理 | 无法改变版本 | 可以指定版本 |
代码风格 | Java语言 | Python语言 |
插件生态 | 几个插件 | 1400+插件 |
维护 | Python官方 | 完全兼容unittest |
bash
pip install pytest # 安装 pip install pytest -U # 升级到最新版
命令行:pytest
代码中:pytest.main()
通过PyCharm运行(不推荐)
Pytest测试结果使用简洁的符号表示:
缩写 | 含义 |
---|---|
. | 通过(passed) |
F | 失败(failed) |
E | 出错(error) |
s | 跳过(skipped) |
X | 预期外的通过(xpassed) |
x | 预期内的失败(xfailed) |
遍历目录(排除venv和.开头的目录)
查找test_
开头或_test
结尾的Python文件
查找Test
开头的类
收集test_
开头的函数或方法
必须是可调用的(函数、方法、类、对象)
名称以test_
开头
没有参数(参数有特殊含义)
没有返回值(默认为None)
python
def add(a, b): return a + b class TestAdd: def test_int(self): res = add(1, 3) assert res == 4 def test_str(self): res = add("1", "3") assert res == "13" def test_list(self): res = add([1], [2, 3, 4]) assert res == [1, 2, 3, 4]
-v
:增加详细程度
-s
:允许用例中的输入输出
-x
:遇到失败用例时停止执行
-m
:用例筛选
创建pytest.ini
文件进行配置:
ini
[pytest] addopts = -v -s
python
@pytest.mark.api def test_int(self): res = add(1, 3) assert res == 4
注册标记(在pytest.ini中):
ini
[pytest] markers = api: API测试 ui: UI测试 pay: 支付测试
@pytest.mark.skip
:无条件跳过
@pytest.mark.skipif
:有条件跳过
@pytest.mark.xfail
:预期失败
@pytest.mark.parametrize
:参数化
@pytest.mark.usefixtures
:使用fixtures
使用参数化实现数据驱动测试:
python
@pytest.mark.ddt @pytest.mark.parametrize("a,b,c", [ (1, 1, 2), (2, 3, 5), (3, 3, 6), (4, 4, 8) ]) def test_ddt(self, a, b, c): res = add(a, b) assert res == c
也可以从外部文件读取测试数据:
python
import csv def read_csv(file_path): with open(file_path) as f: return list(csv.reader(f)) @pytest.mark.parametrize("a,b,c", read_csv("data.csv")) def test_csv_data(a, b, c): res = add(int(a), int(b)) assert res == int(c)
Pytest作为Python生态中最强大的测试框架,通过简洁的语法和丰富的插件系统,可以满足从单元测试到复杂集成测试的各种需求。本文介绍了Pytest的基本使用方法,包括安装配置、用例编写、标记系统和数据驱动测试等核心功能。掌握这些内容后,可以大大提高Python项目的测试效率和代码质量。