import pytest
"""断言"""
def f():
return 3
# pytest允许您使用标准python assert来验证Python测试中的期望和值
def test_function():
assert f() == 4, "never see you again"
# 自行断言
# 断言可以指定一条消息,assert condition, message
# 消息将简单地显示在跟踪中AssertionError: message
# 关于预期异常的断言
def test_zero_division():
with pytest.raises(ZeroDivisionError):
result = 1/0
# excinfo是一个ExceptionInfo实例,是实际引发的异常的包装
# 感兴趣的主要属性是 .type,.value和.traceback
def test_recursion_depth():
with pytest.raises(RuntimeError) as excinfo:
def find_something():
find_something()
find_something()
# print(str(excinfo.type), str(excinfo.value),str(excinfo.traceback), end=' ')
assert "maximum recursion" in str(excinfo.value)
# 为了编写有关引发的异常的断言,可以将其 pytest.raises用作上下文管理器
# 将match关键字参数传递给上下文管理器,以测试正则表达式在异常的字符串表示形式上是否匹配
def myfunc():
raise ValueError("Exception 123 raised")
'''
myfunc引发的ValueError原因是否符合pytest.raises中match的匹配规则
'''
"""
pytest --trace-config 要找出环境中哪些插件处于活动状态
pytest -p no:NAME 阻止插件加载或注销它们
"""
def test_match():
with pytest.raises(ValueError, match=r".* 123 .*"):
myfunc()
# 为失败的断言定义自己的解释
# 通过实现该pytest_assertrepr_compare挂钩,可以添加您自己的详细说明
# pytest_assertrepr_compare(config,op,left,right )
# 返回失败断言表达式中的比较的说明
def pytest_assertrepr_compare(op, left, right):
if isinstance(left, Foo) and isinstance(right, Foo) and op == "==":
return [
"Comparing Foo instances:",
" vals: {} != {}".format(left.val, right.val),
]
class Foo:
def __init__(self, val):
self.val = val
def __eq__(self, other):
return self.val == other.val
def test_compare():
f1 = Foo(1)
f2 = Foo(2)
assert f1 == f2
pytest学习--断言
猜你喜欢
转载自blog.csdn.net/hide_in_darkness/article/details/108438774
今日推荐
周排行