Python中如何使用pytest进行测试实战

部门头头要求写单元测试,上网买了一本,花了一下午看了一遍,读起来很流畅,翻译的可以,没有读起来别扭的地方。基本上把 pytest 相关的知识都提到了,基础不好的人读起来也不会困难。对于要上手 pytest 或想浏览 pytest 框架功能的人来说很合适。写测试对提高代码质量很有帮助,推荐下。

这里有篇试读(需下载)
https://pan.baidu.com/s/1aFMy0_ybaXjJa09h0gHP0g
Python中如何使用pytest进行测试实战


12 回复

还是 unittest 简单。。


帖子回复:

pytest是Python最流行的测试框架之一,比unittest更简洁灵活。下面通过一个完整示例展示如何用pytest进行实际测试。

1. 安装pytest

pip install pytest

2. 创建待测试模块(calculator.py

class Calculator:
    def add(self, a, b):
        return a + b
    
    def subtract(self, a, b):
        return a - b
    
    def multiply(self, a, b):
        return a * b
    
    def divide(self, a, b):
        if b == 0:
            raise ValueError("除数不能为零")
        return a / b

3. 创建测试文件(test_calculator.py)

import pytest
from calculator import Calculator

class TestCalculator:
    @pytest.fixture
    def calc(self):
        """每个测试方法前都会创建新的Calculator实例"""
        return Calculator()
    
    def test_add(self, calc):
        assert calc.add(2, 3) == 5
        assert calc.add(-1, 1) == 0
    
    def test_subtract(self, calc):
        assert calc.subtract(5, 3) == 2
        assert calc.subtract(0, 5) == -5
    
    def test_multiply(self, calc):
        assert calc.multiply(3, 4) == 12
        assert calc.multiply(0, 5) == 0
    
    def test_divide(self, calc):
        assert calc.divide(6, 3) == 2
        assert calc.divide(5, 2) == 2.5
    
    def test_divide_by_zero(self, calc):
        with pytest.raises(ValueError, match="除数不能为零"):
            calc.divide(5, 0)

def test_parametrized():
    """参数化测试示例"""
    calc = Calculator()
    test_data = [
        (1, 2, 3),
        (-1, -1, -2),
        (100, 200, 300)
    ]
    
    for a, b, expected in test_data:
        assert calc.add(a, b) == expected

@pytest.mark.parametrize("a,b,expected", [
    (1, 2, 3),
    (-1, -1, -2),
    (100, 200, 300)
])
def test_add_parametrized(a, b, expected):
    """使用pytest参数化装饰器"""
    calc = Calculator()
    assert calc.add(a, b) == expected

4. 运行测试

# 运行所有测试
pytest

# 运行特定测试文件
pytest test_calculator.py

# 运行特定测试类
pytest test_calculator.py::TestCalculator

# 显示详细输出
pytest -v

# 运行包含特定字符串的测试
pytest -k "add"

5. 关键特性说明

  • 自动发现测试:pytest会自动查找以test_开头的文件和函数
  • 断言简单:直接使用Python的assert语句
  • 夹具系统:使用@pytest.fixture管理测试资源
  • 参数化测试:用@pytest.mark.parametrize减少重复代码
  • 丰富的插件:可通过插件扩展功能

总结建议: 从简单的assert开始,逐步掌握fixture和参数化等高级特性。

感谢,已下单

pytest 的文档写的也很棒

头他会写吗

不客气。

没敢问:)

=,=所有不提供个完整电子版下载吗?

不过网上没电子版出售啊(官方电子书

pytest 比 unittest 简单

好像只有纸书卖。

我只有纸书。

回到顶部