Pytest进行单元测试的方法

Pytest 是一个功能强大且易于使用的 Python 测试框架,广泛用于单元测试和调试代码。它支持简单的断言语法、丰富的插件生态系统以及灵活的测试用例管理,非常适合调试和提高代码质量。

安装与环境配置

1
2
3
4
5
# 使用 pip 安装
pip install pytest

# 验证安装
pytest --version

编写测试用例

Pytest 遵循约定优于配置的原则,测试文件和函数需遵循以下命名规则:

  • 测试文件以 test_ 开头或 _test 结尾,例如 test_example.py。

  • 测试函数以 test_ 开头,例如 def test_add():。

  • 测试类以 Test 开头,且不包含 init 方法。

示例代码:

1
2
3
4
5
6
7
8
# 被测试函数
def add(a, b):
return a + b
# 测试用例
def test_add_positive_numbers():
assert add(2, 3) == 5
def test_add_negative_numbers():
assert add(-1, -1) == -2

执行测试与调试

运行测试时,可以通过命令行指定文件、目录或关键字:

1
2
3
4
5
6
# 运行当前目录下的所有测试
pytest
# 运行指定文件的测试
pytest test_example.py
# 运行包含特定关键字的测试
pytest -k "add"

断言与错误报告

Pytest 支持直接使用 Python 的 assert 语句,并在断言失败时提供详细的上下文信息。例如:

1
2
def test_example():
assert 2 + 2 == 5 # 输出详细的断言失败信息

参考链接

  1. 十分钟带你看懂——Python测试框架之pytest最全讲,by 程序员月下.