Search code examples
pythonpython-unittest

Using assertRaises without self in Python 3.6


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

Solution

  • 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"):
            ...