摘要:Pytest 是 Python 中最流行、最强大的测试框架之一,广泛应用于单元测试、集成测试、功能测试等各类测试场景。相比 unittest,pytest 更加简洁优雅、易于编写和维护,支持丰富的插件生态和强大的参数化机制,是现代 Python 项目中的测试首
Pytest 是 Python 中最流行、最强大的测试框架之一,广泛应用于单元测试、集成测试、功能测试等各类测试场景。相比 unittest,pytest 更加简洁优雅、易于编写和维护,支持丰富的插件生态和强大的参数化机制,是现代 Python 项目中的测试首选。
安装 :
pip install pytest常见应用场景:
(1)编写单元测试、集成测试。
(2)自动发现和执行测试用例。
(3)支持测试函数、类、模块、文件夹。
(4)提供灵活的断言重写和丰富插件。
(5)与 CI/CD 流程集成(如 GitHub Actions、Jenkins)。
◆ ◆ ◆
核心概念
1、函数即测试
只需以 test_ 开头命名函数即可被自动识别为测试。
2、断言自动增强
内置的 assert 会输出清晰的失败信息。
3、参数化测试
用 @pytest.mark.parametrize 轻松编写多组测试数据。
4、测试夹具 fixture
通过 @pytest.fixture 管理测试前置与共享资源。
5、灵活的测试发现机制
自动查找以 test_ 命名的函数/方法/文件。
◆ ◆ ◆
基本用法
最简单的测试用例:
# test_sample.pydef func(x):return x + 1def test_answer:assert func(3) == 4运行:
pytest test_sample.py输出:
collected 1 itemtest_sample.py . [100%]◆ ◆ ◆
应用举例
例 1:参数化测试
import pytest@pytest.mark.parametrize("a,b,result", [(1, 2, 3), (3, 5, 8)])def test_add(a, b, result):assert a + b == result例 2:使用 fixture 管理资源
import pytest@pytest.fixturedef sample_data:return {"name": "Tom", "age": 25}def test_name(sample_data):assert sample_data["name"] == "Tom"例 3:组织测试用例类
class TestMath:def test_add(self):assert 1 + 2 == 3def test_mul(self):assert 2 * 5 == 10例 4:捕获异常
import pytestdef divide(x, y):return x / ydef test_zero_division:with pytest.raises(ZeroDivisionError):divide(1, 0)例 5:跳过与条件执行
import pytest@pytest.mark.skip(reason="暂时跳过此测试")def test_skip:assert 1 == 2@pytest.mark.skipif(2 > 1, reason="条件为真,跳过")def test_skip_if:assert 1 == 1◆ ◆ ◆
常用命令与选项
pytest
执行所有测试。
pytest test_mod.py::test_func
执行指定模块的某个函数。
pytest -k "keyword"
只运行函数名中包含关键字的测试。
pytest -v
显示详细信息(verbose)。
pytest -x
首个失败就终止测试。
pytest --maxfail=3
最多允许 3 个失败后终止。
pytest --tb=short
简洁显示 traceback。
pytest --disable-warnings
忽略警告信息。
插件推荐:
pytest-mock:集成 unittest.mock
pytest-xdist:并行执行测试
pytest-django / pytest-flask:Web 框架集成
安装示例:
pip install pytest-cov pytest-mock pytest-xdist◆ ◆ ◆
补充说明
1、pytest 兼容 unittest,可以运行已有的测试代码。
2、使用 conftest.py 可集中管理 fixture。
3、建议将测试代码放入 tests/ 目录中,并与源代码分离。
4、与 CI/CD 工具集成时,只需运行 pytest 即可完成自动化测试。
5、如需进一步学习 pytest,可参考:
官方文档:https://docs.pytest.org/
中文翻译:https://pytest-zh.readthedocs.io/
“点赞有美意,赞赏是鼓励”
来源:小象科技园地