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的错误输出是比较详细的
- 将失败测试函数打印出来
- 将错误函数显示出来
- 将变量中间值打印出来
自定义错误信息
可以通过以下方式自定义错误输出
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)
excinfo
是ExceptionInfo
的一个实例,其主要的属性,有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()
装饰器是对整个函数进行异常断言
三种方式按需使用,更多异常使用查看官方文档