Henry
发布于 2025-02-25 / 9 阅读
0
0

Python - 使用pytest 进行单元测试

简介

pytest 是一个非常流行的 Python 测试框架,它易于上手,同时也支持复杂的功能测试。以下是 pytest 的基本使用方法:

安装 pytest

首先,需要安装 pytest。可以使用 pip 来安装:

pip install pytest pytest-html

编写测试用例

pytest 会自动发现以 test_ 开头或以 _test 结尾的函数作为测试用例。测试文件通常以 test_ 开头。下面是一个简单的测试用例示例:

# 文件名: test_example.py
def func(x):
    return x + 1
def test_answer():
    assert func(3) == 4

运行测试用例

在命令行中,导航到包含测试文件的目录,然后运行 pytestpytest 会自动查找并执行所有符合命名规则的测试用例。

pytest

测试报告

pytest 提供了许多插件来生成测试报告。例如,可以使用 pytest-html 插件来生成 HTML 报告:

pip install pytest-html

然后,使用 --html 选项运行 pytest

pytest --html=report.html

这将在当前目录下生成一个名为 report.html 的 HTML 报告文件。

参数化测试

pytest 支持参数化测试,可以使用不同的参数多次运行同一个测试用例。使用 @pytest.mark.parametrize 装饰器可以实现这一点:

import pytest
@pytest.mark.parametrize("test_input,expected", [
    ("3+5", 8),
    ("2+4", 6),
    ("6*9", 42),
])
def test_eval(test_input, expected):
    assert eval(test_input) == expected

Fixtures

pytest 的 fixtures 可以创建一个测试环境,可以在多个测试用例中使用。使用 @pytest.fixture 装饰器可以定义一个 fixture:

import pytest
@pytest.fixture
def supply_AA_BB_CC():
    aa = 25
    bb = 35
    cc = 45
    return [aa, bb, cc]
def test_compare_with_AA(supply_AA_BB_CC):
    zz = 35
    assert supply_AA_BB_CC[0] == zz, "aa and zz comparison failed"
def test_compare_with_BB(supply_AA_BB_CC):
    zz = 35
    assert supply_AA_BB_CC[1] == zz, "bb and zz comparison failed"

更多功能

pytest 还提供了许多其他功能,如测试覆盖率报告(使用 pytest-cov 插件)、并行测试、分布式测试等。可以通过阅读 pytest 的官方文档来了解更多高级功能和使用方法。 pytest 的官方文档:https://docs.pytest.org/en/stable/


以上便是本文的全部内容,感谢您的阅读。



评论