How can I use pytest.raises with a few exceptions?

I am testing code in which one of two exceptions can occur: MachineError or NotImplementedError. I would like to use pytest.raises to make sure at least one of them is called when my test code runs, but it seems that it takes only one type of exception as an argument.

This is the signature for pytest.raises :

 raises(expected_exception, *args, **kwargs) 

I tried to use the or keyword inside the context manager:

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

but I assume that this only checks if the first pytest.raises None , and sets the second as a context manager, if any.

Passing a few exceptions as positional arguments does not work because pytest.raises treats its second argument as being called. Each subsequent positional argument is passed as an argument to this callee.

From the documentation :

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

List exception throwing also doesn't work:

 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'> 

Is there a workaround for this? He should not use the context manager.

+12
source share
1 answer

Pass exceptions as a tuple in raises :

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

In the pytest source, pytest.raises can:

In Python 3, except statements can take several exceptions. The issubclass function issubclass also take a tuple . Therefore, the use of a tuple should be acceptable in any situation.

+25
source

All Articles