微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【pytest】五 pytest中的断言

一、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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐