pytest学习--断言

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值