Pytest
是一个功能强大且易于使用的 Python 测试框架,适用于各种规模的项目。
它使得编写简单而可读的测试变得容易,同时支持复杂的功能测试和单元测试。以下是关于 Pytest
的详细介绍和使用指南。
首先,你需要安装 pytest
包。可以通过 pip 来安装:
bashpip install pytest
test_
开头的函数名。test_
开头或结尾。assert
语句进行断言,无需导入额外的模块。以下是一些具体的示例,展示了如何使用 pytest
编写和运行测试。
创建一个名为 test_sample.py
的文件,并添加以下内容:
pythondef add_numbers(a, b):
return a + b
def test_add_numbers():
assert add_numbers(2, 3) == 5
assert add_numbers(-1, 1) == 0
然后在命令行中运行:
bashpytest test_sample.py
@pytest.mark.parametrize
装饰器允许你对同一测试函数执行多次,每次使用不同的参数。
pythonimport pytest
@pytest.mark.parametrize("a,b,expected", [
(2, 3, 5),
(-1, 1, 0),
(5, 7, 12)
])
def test_add_numbers_param(a, b, expected):
assert add_numbers(a, b) == expected
你可以测试代码是否抛出了预期的异常。
pythondef divide_numbers(a, b):
if b == 0:
raise ValueError("Cannot divide by zero!")
return a / b
def test_divide_by_zero():
with pytest.raises(ValueError):
divide_numbers(1, 0)
Fixtures 是 pytest
提供的一种机制,用于设置和清理测试环境。它们可以用来共享测试数据、配置等。
pythonimport pytest
@pytest.fixture
def sample_data():
return {'key': 'value'}
def test_sample_data(sample_data):
assert sample_data['key'] == 'value'
你可以在同一个测试函数中使用多个 fixtures。
pythonimport pytest
@pytest.fixture
def first_fixture():
return "first"
@pytest.fixture
def second_fixture():
return "second"
def test_multiple_fixtures(first_fixture, second_fixture):
assert first_fixture == "first"
assert second_fixture == "second"
pytest
自动查找并运行当前目录及其子目录下的所有符合条件的测试文件(文件名以 test_
开头或结尾)和测试函数(函数名以 test_
开头)。
只需在项目的根目录下运行:
bashpytest
通过标记(marking)测试,可以将测试分组或过滤特定类型的测试。
pythonimport pytest
@pytest.mark.slow
def test_slow_operation():
# 模拟一个耗时的操作
pass
def test_fast_operation():
# 快速操作
pass
你可以只运行标记为 slow
的测试:
bashpytest -m slow
或者跳过这些测试:
bashpytest -m "not slow"
你可以通过指定测试函数名来运行特定的测试:
bashpytest test_sample.py::test_add_numbers
pytest
支持插件系统,允许扩展其功能。例如,pytest-cov
可以用来生成代码覆盖率报告。
安装 pytest-cov
:
bashpip install pytest-cov
运行测试并生成覆盖率报告:
bashpytest --cov=your_module_name