温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python pytest如何做断言

发布时间:2026-10-14 19:36:22 来源:亿速云 阅读:90 作者:小樊 栏目:编程语言

在 Python 中使用 pytest 做断言,本质上就是使用 Python 的 assert 语句,pytest 对其做了增强,使失败信息更清晰。下面从基础到进阶系统地说明。


一、最基础的断言

pytest 中不需要像 unittest 那样用 self.assertEqual,直接用 assert:

def test_add():
    assert 1 + 1 == 2

如果断言失败,pytest 会显示详细的对比信息。


二、常用断言示例

1. 相等 / 不等

assert a == b
assert a != b

2. 包含关系

assert "hello" in "hello world"
assert 3 not in [1, 2]

3. 布尔值

assert True
assert not False

4. 异常断言(非常重要)

使用 pytest.raises:

import pytest

def test_zero_division():
    with pytest.raises(ZeroDivisionError):
        1 / 0

带异常信息校验:

with pytest.raises(ValueError) as exc_info:
    int("abc")

assert "invalid literal" in str(exc_info.value)

三、断言异常 & 警告

警告断言

import pytest

def test_warning():
    with pytest.warns(UserWarning):
        import warnings
        warnings.warn("hello", UserWarning)

四、断言失败时的友好提示

可以加自定义消息:

def test_age():
    age = 15
    assert age >= 18, "用户年龄必须大于等于18岁"

五、结合 fixture 做断言

import pytest

@pytest.fixture
def user():
    return {"name": "Tom", "age": 20}

def test_user(user):
    assert user["name"] == "Tom"
    assert user["age"] > 18

六、断言近似相等(浮点数)

assert abs(0.1 + 0.2 - 0.3) < 1e-9

或使用 pytest.approx:

from pytest import approx

assert 0.1 + 0.2 == approx(0.3)

七、断言对象属性

class Student:
    def __init__(self, name):
        self.name = name

def test_student():
    s = Student("Alice")
    assert s.name == "Alice"

八、断言调用次数(结合 mock)

from unittest import mock

def test_mock():
    m = mock.Mock()
    m(1, 2)
    m.assert_called_once_with(1, 2)

总结

✅ pytest 断言特点:

  • 使用原生 assert
  • 失败信息清晰
  • 支持异常、警告、近似比较
  • 不需要继承 TestCase

如果你有具体业务场景(如 API 测试、数据库、异步函数),我可以给你更贴合的示例。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手