Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


2 Answers

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.
like image 83
cegas Avatar answered Dec 13 '25 16:12

cegas


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()
like image 40
Juanmi Taboada Avatar answered Dec 13 '25 14:12

Juanmi Taboada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!