在 Python 中使用 pytest 做断言,本质上就是使用 Python 的 assert 语句,pytest 对其做了增强,使失败信息更清晰。下面从基础到进阶系统地说明。
pytest 中不需要像 unittest 那样用 self.assertEqual,直接用 assert:
def test_add():
assert 1 + 1 == 2
如果断言失败,pytest 会显示详细的对比信息。
assert a == b
assert a != b
assert "hello" in "hello world"
assert 3 not in [1, 2]
assert True
assert not False
使用 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岁"
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"
from unittest import mock
def test_mock():
m = mock.Mock()
m(1, 2)
m.assert_called_once_with(1, 2)
✅ pytest 断言特点:
assert如果你有具体业务场景(如 API 测试、数据库、异步函数),我可以给你更贴合的示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。