【pytest学习笔记】03-断言

本文介绍了pytest中断言的使用,包括简单的断言、自定义错误信息以及异常断言的三种方式,详细展示了如何通过assert关键字进行测试,以及如何在断言失败时提供丰富的错误信息和处理异常。

pytest 使用的是 python 的 assert 关键字,所以不需要像 unitest 使用 self.assert*那样,仅需要记住一个assert就行。

assert 后面是跟着一个表达式或方法调用,如果assert 后 语句执行后为True,则断言错误,否则断言失败,则作为 failure 返回错误。

简单的断言

def test_assert():
    a = 3
    assert  a % 2 == 0

运行,结果:

============================================================================= FAILURES ============================================================================== ____________________________________________________________________________ test_assert ____________________________________________________________________________

    def test_assert():
        a = 3
>       assert  a % 2 == 0
E       assert (3 % 2) == 0

test_assert_01.py:9: AssertionError
1 failed in 0.07 seconds

可以看出,pytest的错误输出是比较详细的

  1. 将失败测试函数打印出来
  2. 将错误函数显示出来
  3. 将变量中间值打印出来

自定义错误信息

可以通过以下方式自定义错误输出

def test_assert():
    a = 3
    assert  a % 2 == 0, "%s is a odd number"%a

运行结果为:

============================================================================= FAILURES ============================================================================== ____________________________________________________________________________ test_assert ____________________________________________________________________________

    def test_assert():
        a = 3
>       assert  a % 2 == 0, "%s is a odd number"%a
E       AssertionError: 3 is a odd number
E       assert (3 % 2) == 0

test_assert_01.py:4: AssertionError
1 failed in 0.09 seconds

异常的断言

pytest 支持 断言异常

import pytest

def f():
    raise SystemExit(1)

def test_f():
    with pytest.raises(SystemExit):
        f()

如果需要处理异常信息,如断言信息中的关键字等,pytest也是支持的

import pytest

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

excinfoExceptionInfo的一个实例,其主要的属性,有value,type,traceback

raises也可以传入match参数,用于匹配错误信息中的字符串,如果不匹配,则认为是失败。如

import pytest

def test_recursion_depth():
    with pytest.raises(RuntimeError, match=r"min") as excinfo:
        def f():
            f()
        f()
    print(excinfo.value)
    assert 'maximum recursion' in str(excinfo.value)

除了使用with语句, pytest 还提供了另外一种异常断言方式,如下,会将参数传给func并执行,并判断是否有指定的异常抛出。

pytest.raises(ExpectedException, func, *args, **kwargs)

import pytest

def f():
    f()

def test_f():
    pytest.raises(RuntimeError, f)

还有一种方式是使用装饰器的方式,如

import pytest

def f():
    f()

@pytest.mark.xfail(raises=RuntimeError)
def test_f():
    f()

装饰器是对整个函数进行异常断言

三种方式按需使用,更多异常使用查看官方文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值