`pytest` 是一个流行的 Python 测试框架,它简单、灵活且易于扩展。使用 `pytest`,你可以编写各种类型的测试,包括单元测试、集成测试和功能测试。以下是 `pytest` 的一些基本用法:
安装
首先,你需要安装 `pytest`。可以通过 pip(Python 包管理工具)进行安装:
pip install pytest
编写测试
`pytest` 的测试文件通常以 `test_` 开头,或者以 `_test` 结尾,测试函数通常以 `test_` 开头。例如,你可以创建一个名为 `test_example.py` 的文件,并在其中编写测试函数:
# test_example.py
def add(x, y):
return x + y
def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0
运行测试
在命令行中,你可以使用 `pytest` 命令来运行测试:
pytest
这将会查找当前目录及其子目录下的所有测试文件,并执行它们。上面的例子中,`test_add` 函数将会被运行,如果 `add` 函数正确实现,测试将会通过。
参数化测试
`pytest` 支持参数化测试,允许你为测试函数提供多组输入和期望的输出。例如:
import pytest
def add(x, y):
return x + y
@pytest.mark.parametrize("x, y, expected", [(1, 2, 3), (-1, 1, 0), (0, 0, 0)])
def test_add(x, y, expected):
assert add(x, y) == expected
断言
在测试函数中,你可以使用 Python 的 `assert` 语句来验证代码的行为是否符合预期。如果 `assert` 语句失败(即条件为 `False`),测试将被标记为失败。
跳过测试
有时你可能想要跳过某些测试。可以使用 `pytest.mark.skip` 装饰器来跳过整个测试函数,或者使用 `pytest.skip()` 函数在测试函数内部跳过:
import pytest
def test_skipped_function():
pytest.skip("Skipping this test")
设置和拆卸
使用 `setup` 和 `teardown` 方法或者 `@pytest.fixture` 可以进行测试前的设置工作和测试后的清理工作。
import pytest
def setup_module():
print("Setup for the whole module")
def teardown_module():
print("Teardown for the whole module")
def test_one():
assert 1 == 1
def test_two():
assert 2 == 2
插件和扩展
`pytest` 的强大之处在于其插件系统,它允许你扩展 `pytest` 的功能。例如,`pytest-cov` 插件可以用于测试覆盖率报告,`pytest-xdist` 插件可以并行运行测试。
这只是 `pytest` 的一些基本用法。要更深入地了解 `pytest` 的高级特性和配置,建议查阅官方文档:<https://docs.pytest.org/en/stable/>
通过不断地实践,你可以熟练掌握 `pytest`,并在项目中有效地实施测试驱动开发(TDD)或其他测试策略。