2025-03-05
编程
00
请注意,本文编写于 54 天前,最后修改于 54 天前,其中某些信息可能已经过时。

目录

安装
基本概念
基本使用示例
1. 简单测试函数
2. 使用参数化测试
3. 测试异常
4. 使用 Fixtures
5. 使用多个 Fixtures
6. 自动发现测试
7. 标记测试
8. 运行特定测试
9. 插件系统

Pytest 是一个功能强大且易于使用的 Python 测试框架,适用于各种规模的项目。

它使得编写简单而可读的测试变得容易,同时支持复杂的功能测试和单元测试。以下是关于 Pytest 的详细介绍和使用指南。

安装

首先,你需要安装 pytest 包。可以通过 pip 来安装:

bash
pip install pytest

基本概念

  • 测试函数:以 test_ 开头的函数名。
  • 测试文件:文件名以 test_ 开头或结尾。
  • 断言:使用标准的 assert 语句进行断言,无需导入额外的模块。

基本使用示例

以下是一些具体的示例,展示了如何使用 pytest 编写和运行测试。

1. 简单测试函数

创建一个名为 test_sample.py 的文件,并添加以下内容:

python
def add_numbers(a, b): return a + b def test_add_numbers(): assert add_numbers(2, 3) == 5 assert add_numbers(-1, 1) == 0

然后在命令行中运行:

bash
pytest test_sample.py

2. 使用参数化测试

@pytest.mark.parametrize 装饰器允许你对同一测试函数执行多次,每次使用不同的参数。

python
import 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

3. 测试异常

你可以测试代码是否抛出了预期的异常。

python
def 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)

4. 使用 Fixtures

Fixtures 是 pytest 提供的一种机制,用于设置和清理测试环境。它们可以用来共享测试数据、配置等。

python
import pytest @pytest.fixture def sample_data(): return {'key': 'value'} def test_sample_data(sample_data): assert sample_data['key'] == 'value'

5. 使用多个 Fixtures

你可以在同一个测试函数中使用多个 fixtures。

python
import 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"

6. 自动发现测试

pytest 自动查找并运行当前目录及其子目录下的所有符合条件的测试文件(文件名以 test_ 开头或结尾)和测试函数(函数名以 test_ 开头)。

只需在项目的根目录下运行:

bash
pytest

7. 标记测试

通过标记(marking)测试,可以将测试分组或过滤特定类型的测试。

python
import pytest @pytest.mark.slow def test_slow_operation(): # 模拟一个耗时的操作 pass def test_fast_operation(): # 快速操作 pass

你可以只运行标记为 slow 的测试:

bash
pytest -m slow

或者跳过这些测试:

bash
pytest -m "not slow"

8. 运行特定测试

你可以通过指定测试函数名来运行特定的测试:

bash
pytest test_sample.py::test_add_numbers

9. 插件系统

pytest 支持插件系统,允许扩展其功能。例如,pytest-cov 可以用来生成代码覆盖率报告。

安装 pytest-cov

bash
pip install pytest-cov

运行测试并生成覆盖率报告:

bash
pytest --cov=your_module_name