python-3.x - 如何在多个异常情况下使用 pytest.raises?

标签 python-3.x exception pytest contextmanager

我正在测试可以引发两个异常之一的代码:MachineError或未实现错误。我想使用 pytest.raises 来确保在运行测试代码时至少引发其中一个,但它似乎只接受一种异常类型作为参数。

这是pytest.raises的签名:

raises(expected_exception, *args, **kwargs)

我尝试在上下文管理器中使用 or 关键字:

with pytest.raises(MachineError) or pytest.raises(NotImplementedError):
    verb = Verb("donner<IND><FUT><REL><SG><1>")
    verb.conjugate()

但我假设这只检查第一个pytest.raises是否为None,如果是,则将第二个设置为上下文管理器。

将多个异常作为位置参数传递是行不通的,因为pytest.raises将其第二个参数作为可调用的。每个后续位置参数都作为参数传递给该可调用函数。

来自documentation :

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

>>> def f(x): return 1/x
...
>>> raises(ZeroDivisionError, f, 0)
<ExceptionInfo ...>
>>> raises(ZeroDivisionError, f, x=0)
<ExceptionInfo ...>

将异常作为列表传递也不起作用:

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    with pytest.raises([MachineError, NotImplementedError]):
  File "/usr/local/lib/python3.4/dist-packages/_pytest/python.py", line 1290, in raises
    raise TypeError(msg % type(expected_exception))
TypeError: exceptions must be old-style classes or derived from BaseException, not <class 'list'>

有解决办法吗?它不必使用上下文管理器。

最佳答案

将异常作为元组传递给raises:

with pytest.raises( (MachineError, NotImplementedError) ):
    verb = ...

pytest的源代码中,pytest.raises可能:

在 Python 3 中,except statements可以采用一组异常。 issubclass 函数 can also take a tuple 。因此,在任何一种情况下使用元组都是可以接受的。

关于python-3.x - 如何在多个异常情况下使用 pytest.raises?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38403710/

相关文章:

pytest -k 标志和语句

python - Pyautogui 屏幕截图。它去哪儿了?如何保存以后查找?

python - 显示字符串中小写字母的个数

python - 词典使用问题

python - 在 python 中使用 smtplib 时出错

python - Pytest:修补全局变量

python - TypeError : an integer is required (got type datetime. datetime) 尝试将字典中的日期时间对象转换为字符串时

c# - 为什么 finally 没有被执行?

python - 定义错误消息和错误代码列表

python - Pytest:捕获的 stderr 设置和捕获的日志设置重复