Pytest

Exception assert

参考:

方法:

1
2
3
>>> import pytest
>>> with pytest.raises(ZeroDivisionError) as exe_info:
...    1/0

注意:

  1. 用于捕获单个 Exception

exception 文本匹配

解说:

  • 使用 match 关键字参数
  • 匹配对象

    • 文本
    • 正则
1
2
>>> with pytest.raises(ValueError, match=r'must be \d+$'):
...     raise ValueError("value must be 42")

直接传入函数和参数,不适用 with 语句

有参数

1
2
3
4
5
6
>>> def f(x): return 1/x
...
>>> raises(ZeroDivisionError, f, 0)
<ExceptionInfo ...>
>>> raises(ZeroDivisionError, f, x=0)
<ExceptionInfo ...>

无参数

1
2
>>> raises(ZeroDivisionError, lambda: 1/0)
<ExceptionInfo ...>

数据驱动

通过 csv 文件传入测试参数

参考: