pytest快速入门(2)

在测试中编写断言
Pytest支持显示最常用的子表达式的值,包括调用、属性、比较以及二进制和一元操作符。这允许您在不使用样板代码的情况下使用惯用的python构造,同时不丢失内省信息。
(一)pytest 允许您使用标准 Python 断言来验证 Python 测试中的期望和值,如

# test_001.py
import pytest

def testcases_01():
    assert 'h' in 'hello'

def add(x):
    return x + 1

def test_false():
    assert add(8) == 4


if __name__ == "__main__":
    pytest.main(['-s', 'test_001.py'])

断言函数或条件表达式,如果断言失败会返回详细错误信息(函数返回值等)

collected 2 items

test_001.py .F

================================== FAILURES ===================================
_________________________________ test_false __________________________________

    def test_false():
>       assert add(8) == 4
E       assert 9 == 4
E        +  where 9 = add(8)

test_001.py:16: AssertionError

(二)预期内的异常断言
对于某些异常如果是预期内的异常,可使用pytest.raises()

# test_001.py
import pytest
dict_calue = {'a': 1}
def test_except_error():
    print(dict_calue['b'])

如上述代码会返回KeyError,我们可以捕获其预期异常

# test_001.py
import pytest
dict_calue = {'a': 1}
def test_except_error():
    with pytest.raises(KeyError) as e:
        print(dict_calue['b'])
    assert e.type == KeyError
if __name__ == "__main__":
    pytest.main(['-s', 'test_001.py'])

pytest快速入门(2)_第1张图片
也可以自定义返回异常,对于不确定类型的异常,可以捕获后返回自定义类型异常

# test_001.py
import pytest
dict_calue = {'a': 1}
def error_info():
    try:
        print(dict_calue['b'])
    except:
        raise ValueError('not good')

def test_except_error():
    with pytest.raises(ValueError) as e:
        error_info()
    assert e.type == ValueError

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