使用 PyTest 测试 Python 程序

PyTest 是一个流行的 Python 测试框架,简单易用且功能强大,适用于单元测试和功能测试。

安装

pip install pytest

编写测试代码

PyTest 会自动发现以 test_ 开头的函数或以 Test 开头的类方法。所以,你需要按照这种命名约定来编写测试。

示例:

目录布局:

root
├── pyproject.toml
├── src
│   ├── my_math.py
└── tests
    └── test_my_math.py

pyproject.toml:

[tool.pytest.ini_options]
addopts = ["--import-mode=importlib"]
pythonpath = ["src", "tests"]

参考:Choosing a test layout | pytest documentation

源代码 src/my_math.py

def add(a, b):
    return a + b

测试代码 tests/test_my_math.py

from my_math import add

def test_add():
    assert add(1, 2) == 3
    assert add(-1, 1) == 0
    assert add(0, 0) == 0

运行测试

在命令行中运行以下命令来执行测试:

pytest

PyTest 会自动查找当前目录及子目录中的测试文件,并执行其中的测试函数。

测试运行后,PyTest 会在终端中输出测试结果。通过结果可以看到哪些测试通过,哪些失败,以及失败的原因。

在 Visual Studio Code 中,可以使用 Test Runner for Java 插件管理测试。

其他功能

PyTest 提供了许多强大的功能,比如:

  • 参数化测试:可以使用 @pytest.mark.parametrize 装饰器来对同一个测试函数进行多组数据测试。

    @pytest.mark.parametrize("a, b, expected", [
        (1, 2, 3),
        (-1, 1, 0),
        (0, 0, 0),
    ])
    def test_add(a, b, expected):
        assert add(a, b) == expected
    
  • 设置和清理测试环境:使用 setupteardown 方法,或者使用 fixture

    import pytest
    
    @pytest.fixture
    def setup_data():
        # Setup code
        data = {"key": "value"}
        yield data
        # Teardown code
    
    def test_with_fixture(setup_data):
        assert setup_data["key"] == "value"
    
  • 查看详细输出:使用 -v 选项可以看到更详细的输出。

    pytest -v
    
  • 只运行失败的测试:可以使用 --lf 选项快速重新运行上一次失败的测试。

    pytest --lf
    
  • 生成测试报告:使用 --junitxml=report.xml 生成 JUnit XML 格式的测试报告。

    pytest --junitxml=report.xml
    

参见:

posted @ 2025-03-09 17:43  Undefined443  阅读(50)  评论(0)    收藏  举报