pytest-assert断言

断言

pytest使用python自带的assert关键字来进行断言

在python中,断言语句assert后面跟任何合法的表达式,assert语句做出一个判断,如果结果为true,则该语句不做任何事情,如果结果为false,assert语句会抛出异常AssertionError,在assert语句后加上解释性语句,用来解释某种异常发生的原因,当出现某种异常时,解释性语句作为异常抛出。

例如:

def test_one():
        x = "hello"
        assert "m"in x,"判断x中是否包含m"

运行结果

Launching pytest with arguments test_01.py::test_one --no-header --no-summary -q in C:\Users\zhangman11\PycharmProjects\pythonProject3

============================= test session starts =============================
collecting ... collected 1 item

test_01.py::test_one FAILED                                              [100%]
test_01.py:2 (test_one)
def test_one():
            x = "hello"
>           assert "m"in x,"判断x中是否包含m"
E           AssertionError: 判断x中是否包含m
E           assert 'm' in 'hello'

test_01.py:5: AssertionError


============================== 1 failed in 0.14s ==============================

Process finished with exit code 1

上面的程序中,在测试函数中使用assert判断x中是否包含字母m,因m不包含在x中,所以会报AssertionError错误,导致用例执行失败

常用断言

1.assert 表达式 :判断条件为真

2.assert not 表达式 :判断表达式不为真

3.assert a in b :判断包含a

4.assert a == b:判断a等于b

5.assert a != b :判断a不等于b

异常断言

可以使用pytest.raise作为上下文管理器,当抛出异常是可以获取到对应的异常实例

例如

import pytest

def test_one():
        with pytest.raises(NameError) as f:
                a = b
        assert f.type == NameError
        assert "name 'b' is not defined"in str(f.value)

执行结果

Launching pytest with arguments test_01.py::test_one --no-header --no-summary -q in C:\Users\zhangman11\PycharmProjects\pythonProject3

============================= test session starts =============================
collecting ... collected 1 item

test_01.py::test_one PASSED                                              [100%]

============================== 1 passed in 0.02s ==============================

Process finished with exit code 0

断言场景:判断执行a = b的结果是不是预期的NameError,执行a = b后抛出NameError异常,与预期一致,所以用例测试通过

断言时通常断言异常的type和value,此例中,由于b未定义,所以会引发NameError,该异常的type为NameError,值的类型为 name 'b' is not defined

f是一个异常类的实例,主要熟悉包括type,value,traceback

断言type时,异常类型不需要加引号,断言value值时需要转为str

你可能感兴趣的:(pytest,python,开发语言)