如何使用pytest.raises多个例外?

fen*_*eop 13 exception contextmanager pytest python-3.x

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

这是签名pytest.raises:

raises(expected_exception, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

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

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

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

将多个异常作为位置参数传递不起作用,因为pytest.raises它的第二个参数是可调用的.每个后续位置参数都作为参数传递给该可调用对象.

文档:

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

>>> def f(x): return 1/x
...
>>> raises(ZeroDivisionError, f, 0)
<ExceptionInfo ...>
>>> raises(ZeroDivisionError, f, x=0)
<ExceptionInfo ...>
Run Code Online (Sandbox Code Playgroud)

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

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'>
Run Code Online (Sandbox Code Playgroud)

这有解决方法吗?它不必使用上下文管理器.

cxw*_*cxw 27

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

with pytest.raises( (MachineError, NotImplementedError) ):
    verb = ...
Run Code Online (Sandbox Code Playgroud)

在源中pytest,pytest.raises可能:

在Python 3中,except语句可以采用一组异常.该issubclass函数也可以采用元组.因此,在任何一种情况下都应该接受使用元组.

  • @fenceop http://stackoverflow.com/questions/35851782/why-does-handling-multiple-exceptions-require-a-tuple-and-not-a-list (2认同)