python 3.4 - How can I use pytest.raises with multiple exceptions? -
i'm testing code 1 of 2 exceptions can raised: machineerror or notimplementederror. use pytest.raises
make sure @ least 1 of them raised when run test code, seems accept 1 exception type argument.
this signature pytest.raises
:
raises(expected_exception, *args, **kwargs)
i tried using or
keyword inside context manager:
with pytest.raises(machineerror) or pytest.raises(notimplementederror): verb = verb("donner<ind><fut><rel><sg><1>") verb.conjugate()
but assume checks whether first pytest.raises
none
, sets second 1 context manager if is.
passing multiple exceptions positional arguments doesn't work, because pytest.raises
takes second argument callable. every subsequent positional argument passed argument callable.
from documentation:
>>> raises(zerodivisionerror, lambda: 1/0) <exceptioninfo ...> >>> def f(x): return 1/x ... >>> raises(zerodivisionerror, f, 0) <exceptioninfo ...> >>> raises(zerodivisionerror, f, x=0) <exceptioninfo ...>
passing exceptions list doesn't work either:
traceback (most recent call last): file "<pyshell#4>", line 1, in <module> 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 old-style classes or derived baseexception, not <class 'list'>
is there workaround this? doesn't have use context manager.
haven't tried myself, how this? pass exceptions tuple raises
:
with pytest.raises( (machineerror, notimplementederror) ): verb = ...
in source pytest
, pytest.raises
may:
- catch
expected_exception
; or - pass
expected_exception
raisescontext
instance, usesissubclass
check whether exception 1 wanted.
in python 3, except
statements can take tuple of exceptions. issubclass
function can take tuple. therefore, using tuple should acceptable in either situation.
Comments
Post a Comment