Reputation: 4511
I would like to test one failure scenario in one of my python file as follows:
source.py
def myfunc():
a()
associated test.py
def testMyFuncException():
a = Mock()
a.side_effect = MyError
with self.assertRaises(MyError) as _ : <--- THIS LINE I CANNOT USE self.assertRaises
..
But here I cannot use self as it's not associated with any class. So I am not getting any clue regarding how to do this.
EDIT
I have done it as follows now as per suggestions:
def testMyFuncException(TestCase):
a = Mock()
a.side_effect = MyError
with TestCase.assertRaises(MyError) as _ :
...
Now I am getting error as follows:
E fixture 'TestCase' not found
Upvotes: 6
Views: 2952
Reputation: 11522
You don't need pytest
. Although TestCase.assertRaises
does need to be run against a TestCase
instance, it doesn't use or need any context that varies from instance to instance. You can use any old TestCase
object.
Meaning you can just do this:
from unittest import TestCase
with TestCase().assertRaises(MyError):
raise_myerror()
Or, in the context of your example above:
from unittest import TestCase
def testMyFuncException():
a = Mock()
a.side_effect = MyError
with TestCase().assertRaises(MyError):
raise MyError
Upvotes: 0
Reputation: 16885
Another possibility is to use pytest instead of unittest. In this case you don't need a separate test class:
import pytest
from unittest.mock import Mock
def test_myfunc_exception():
a = Mock()
a.side_effect = MyError
with pytest.raises(MyError, match="my exception message"):
...
Upvotes: 8
Reputation: 4481
You need a TestCase
fixture in the unittest
testing framework. The normal way to do this is to create a class inheriting from unittest.TestCase
. You will then be able to use the self.assertRaises
method, along with the other asserts in the TestCase
class:
from unittest import TestCase
from unittest.mock import Mock
class TestMyFunc(TestCase):
def test_myfunc_exception(self):
a = Mock()
a.side_effect = MyError
with self.assertRaises(MyError) as _ :
...
Upvotes: 0