Pytest 是一个简单、易用的 Python 测试框架。以下是一些关于如何使用 Pytest 的基本指南。
快速入门
安装 Pytest
使用 pip 安装 Pytest:pip install pytest
编写测试用例
测试用例通常以test_
开头,例如test_add.py
。运行测试
在命令行中,进入包含测试文件的目录,然后运行pytest
。
常用功能
断言
使用assert
语句来验证条件是否为真。def test_add(): assert 1 + 1 == 2
参数化测试
使用@pytest.mark.parametrize
装饰器来运行多个测试用例。@pytest.mark.parametrize("a,b", [(1, 2), (2, 3), (3, 4)]) def test_add(a, b): assert a + b == 3
** fixtures**
Fixtures 允许你定义可重用的测试代码。@pytest.fixture def adder(): return lambda x, y: x + y def test_add(adder): assert adder(1, 2) == 3
扩展阅读
想了解更多关于 Pytest 的信息?请访问我们的 Pytest 官方文档。