pythonassertraises

How to use assertRaisesRegex in this situation?


I'm trying to use assertRaisesRegex (from the unittest module) to ensure that an exception (from our C++ backend) is raised when performing the following assignment:

a[:, 0] = b[:, 0]

a and b here are custom types defined in our backend.

In the cases I've seen assertRaisesRegex used, a function along with its arguments is passed into assertRaisesRegex, but in this case I need to test that the exception is raised during the above assignment. How can I best do that without having to write an additional function to do the assignment?


Solution

  • import unittest
    
    
    class SomeSpecificError(Exception):
        pass
    
    
    class OtherError(Exception):
        pass
    
    
    class FakeData:
        def __getitem__(self, key):
            raise SomeSpecificError(f"can't get slice {key!r}")
    
    
    class MyTestCase(unittest.TestCase):
        def test(self):
            a = FakeData()
            b = FakeData()
    
            with self.assertRaisesRegex(SomeSpecificError, "can't get slice"):
                a[:, 0] = b[:, 0]
            # passes
    
            with self.assertRaisesRegex(SomeSpecificError, "something something"):  #
                a[:, 0] = b[:, 0]
            # fails:
            # AssertionError: "something something" does not match "can't get slice (slice(None, None, None), 0)"
    
            with self.assertRaisesRegex(OtherError, "something something"):  #
                "no exception raised in this block"
            # fails:
            # AssertionError: OtherError not raised
    

    Obviously, substitute my FakeData with your own actual class, mine is for testing (like a mock).