pytest 框架常用的断言方法

在pytest框架中,断言是测试的核心部分。与传统的unittest不同,pytest直接使用Python的assert语句,并结合智能的错误信息提示,简化了断言的使用


1. 基本断言

直接用assert语句进行条件判断:

def test_basic():
    a = 5
    b = 3 + 2
    assert a == b          # 判断相等
    assert a != 6          # 判断不等
    assert "hello" in "hello world"   # 判断包含
    assert not False       # 判断布尔值
    assert hasattr([], "append")  # 判断对象是否有属性

当断言失败时,pytest会输出具体的值差异(如5 != 6)。


2. 异常断言

使用pytest.raises捕获并验证代码是否抛出预期异常:

import pytest

def test_exception():
    with pytest.raises(ZeroDivisionError):
        1 / 0  # 预期抛出ZeroDivisionError

    # 捕获异常并检查错误信息
    with pytest.raises(ValueError) as excinfo:
        int("invalid")
    assert "invalid literal" in str(excinfo.value)

3. 浮点数近似比较

使用pytest.approx处理浮点数精度问题:

def test_float():
    assert 0.1 + 0.2 == pytest.approx(0.3)          # 默认相对容差
    assert 1.001 == pytest.approx(1, abs=0.01)      # 指定绝对容差

4. 集合与容器断言

验证列表、字典等容器的内容:

def test_collections():
    my_list = [1, 2, 3]
    assert 2 in my_list             # 包含元素
    assert 4 not in my_list         # 不包含元素
    assert my_list == [1, 2, 3]     # 顺序严格匹配
    assert set(my_list) == {3, 2, 1}  # 忽略顺序(需转为集合)

    my_dict = {"name": "Alice", "age": 30}
    assert "name" in my_dict        # 检查键是否存在
    assert my_dict["age"] == 30     # 检查键对应的值

5. 类型与身份断言

验证对象类型或身份:

def test_type():
    obj = []
    assert isinstance(obj, list)   # 类型检查
    assert obj is not None         # 非空检查

6. 警告断言

使用pytest.warns检查代码是否触发警告:

import warnings
import pytest

def test_warning():
    with pytest.warns(UserWarning):
        warnings.warn("Deprecated feature", UserWarning)

7. 文件与目录断言

通过标准库验证文件系统:

import os

def test_file_exists(tmp_path):
    file_path = tmp_path / "test.txt"
    file_path.write_text("content")
    assert os.path.exists(file_path)  # 检查文件是否存在

8. 多重断言(需插件)

使用pytest-assume插件执行多个断言(即使部分失败):

pip install pytest-assume
def test_multiple_assertions():
    pytest.assume(1 == 1)
    pytest.assume(2 > 3)  # 即使失败,后续代码仍执行
    pytest.assume("a" in "abc")

优势说明

  • 智能错误提示:pytest会自动输出断言失败的详细上下文(如变量值、差异对比)。
  • 灵活性:普通assert语句覆盖大多数场景,无需记忆特定断言方法。
  • 扩展性:通过插件(如pytest-assume)可增强断言功能。
pytest是一个流行的Python测试框架,它提供了丰富的断言方法帮助开发者验证测试结果是否符合预期。以下是pytest常用的几种断言方法: 1. `assert`: 这是最基本的断言方法,用于检查两个表达式是否相等。如果它们不相等,则会引发AssertionError。 ```python assert value == expected_value ``` 2. `assert_equal` or `==`: 等价于上述的`assert`,用于比较数值、字符串或其他可比较的对象。 ```python assert a == b ``` 3. `assert_not_equal` 或 `-eq`: 检查两个值是否不相等。 ```python assert a != b ``` 4. `assert_in`: 验证某个值是否在一个序列或集合中。 ```python assert item in container ``` 5. `assert_not_in`: 反之,验证某个值不在指定序列或集合中。 ```python assert item not in container ``` 6. `pytest.raises(ExceptionType[, match])`: 验证特定异常是否在函数调用中被抛出。match参数可以用于检查异常消息。 ```python with pytest.raises(ZeroDivisionError): divide_by_zero() ``` 7. `assert_approx_equal(a, b, rel=1e-9, abs=0)`: 对近似值进行断言,允许一定的相对误差和绝对误差。 ```python import pytest pytest.approx(a, rel=1e-9) # 使用这个装饰器 ``` 使用这些断言方法时,通常会在测试用例中配合`def test_function_name()`函数,并将断言嵌套其中。如果所有断言都通过,那么该测试被认为是成功的;如果有断言失败,pytest会报告详细的错误信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值