5. pytest的断言

2023-05-06,,

一、pytest 支持Python自带的标准断言

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

pytest 的断言报告,也很丰富,和详情,比如:

import pytest

def test_set_comparison():
set1 = set("1308")
set2 = set("8035")
assert set1 == set2

运行一下:

二、对于一些异常的断言

有时候,我们需要对一些异常抛出作断言,可以用pytest.raises

比如:测试除法运算,0不可以被除,这里就可以写一个异常的断言,ZeroDivisionError

import pytest

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

运行测试

不做异常断言,运行测试,就会抛错,ZeroDivisionError

有的时候,我们可能需要在测试中用到产生的异常中的某些信息,比如异常的类型type,异常的值value等等

比如

import pytest

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

5. pytest的断言的相关教程结束。

《5. pytest的断言.doc》

下载本文的Word格式文档,以方便收藏与打印。