user7236255
user7236255

Reputation:

How to raise an exception in pytest?

I have written a code in views.py

def fun():
    try:
         --Do some operation--
    except OSError:
         --Do something else-- 

And I have written a test case to cover total functionality of the code. To test the "except" part I have written the following code where it will raise "OSError",

with pytest.raises(OSError):
    response = client.post(reverse('my_views_funurl'), follow=True)

But, I am getting this error

response = client.post(reverse('my_views_funurl'), follow=True)
E           Failed: DID NOT RAISE

How to raise "OSError" to cover the except part in test cases. By the way I am using django-framework

Upvotes: 3

Views: 12565

Answers (2)

Juanmi Taboada
Juanmi Taboada

Reputation: 545

The right way to do this with "pytest" would be to provide the "side_effect" parameter to patch() with your expected Exception. Example:

def your_test_function(mocker):
    mocker.patch(
        "function.being.mocked",
        side_effect=OSError()
    )
    with pytest.raises(OSError):
        function.being.mocked()

Upvotes: 1

cegas
cegas

Reputation: 3091

Best thing would probably be to just mock the method to throw the exception you need, instead of going through all the trouble of actually creating conditions in which OSError would be thrown. A toy example:

from unittest.mock import Mock

def something():
    ...

something = Mock(side_effect=OSError('Your error text'))

>>> something()
>>> Traceback (most recent call first):
>>> ...
>>> OSError: Your error text

Now as I said, it's only a toy example, so for your own project with different structure and all you will most likely need a bit different setup (given the information you provided it's hard to know how exactly it will look). For example, if you're expecting that some call will throw an OSError exception inside your fun(), then you will need to mock the call in the module fun() is located in. Good places to start reading up on mocks:

  1. Docs quick guide
  2. Patch documentation (pay particularly close attention to 'where to patch' part)
  3. Useful in-depth example on stack-overflow. As it is a bit more sophisticated than my proof-of-concept example, it will probably resemble what you're trying to achieve.

Upvotes: 1

Related Questions