pytest学习教程--assert(3)

Assert就是断言,每个测试用例都需要断言。

与unittest不同,pytest使用的是python自带的assert关键字来进行断言,大大降低了学习成本。

assert关键字后面可以接一个表达式,只要表达式的最终结果为True,那么断言通过,用例执行成功,否则用例执行失败。

详尽的用例失败描述

pytest的用例失败描述非常详尽,一目了人。考虑下面的例子

#content of test_assert1.py
def f():
    return 3

def test_function():
    assert f() == 4

执行上面的用例

$ pytest test_assert1.py
======= test session starts ========
platform linux – Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y rootdir: $REGENDOC_TMPDIR,
inifile: collected 1 item

test_assert1.py F

======= FAILURES ========
_______ test_function ________

def test_function():
assert f() == 4
E assert 3 == 4
E + where 3 = f()

test_assert1.py:5: AssertionError
======= 1 failed in 0.12 seconds ========

可以很明显的看出,pytest给出的错误提示是:f()的值是3,也就是实际结果是3,而预期结果是4,3不等于4,因此断言未通过,用例失败。

断言异常抛出

pytest有自己的异常抛出断言套路,下面是最简单的形式

import pytest

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

上面代码的意思是: 1/0的时候应该抛出ZeroDivisionError,否则用例失败,断言不通过。

另外pytest还允许我们访问异常的具体信息,如下面的例子

def test_recursion_depth():
    with pytest.raises(RuntimeError) as excinfo:
        def f():
            f()
        f()
    assert 'maximum recursion' in str(excinfo.value)

我们还可以定制断言异常的错误信息,比如

with raises(ZeroDivisionError, message=“Expecting ZeroDivisionError”):
… pass … Failed: Expecting ZeroDivisionError

总结

更多断言异常以及定制assert中比较方式的例子,请参阅官方文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值