NotAgain NotAgain - 28 days ago 17
Python Question

No active exception to reraise

A brief background first.
I have to run some unit tests. Only issue is that the client wants the failed tests to be reported in form of a word document with some additional information which I can add easily.
What I have done till now is this.

I have written a small function which will write stuff in a word document using python-docx.
The idea was that I will catch the exception thrown by assertEqual. In the catch block I will call my function to write stuff to word document and then raise the exception again so that old behaviour of a failing unit test is still happening.

class MyTestCase(unittest.TestCase):
def test_something(self):
try:
x = 1
y = 2
self.assertEqual(x, y)
except AssertionError:
writeToDocument(x, y, self.id().split('.')[-1], 'These values should be equal')
raise

if __name__ == '__main__':
unittest.main()


At least thats what I thought. I think I am missing something. I see this error when I run the test. This error is raised at the point where I raise the exception after calling my documentation method.

RuntimeError: No active exception to reraise


Any ideas where I am messing up on the exception handling stuff?

Answer Source

If it's losing the reference to the error somehow, try passing it explicitly using except AssertionError as err.

class MyTestCase(unittest.TestCase):
    def test_something(self):
        try:
            x = 1
            y = 2
            self.assertEqual(x, y)
        except AssertionError as err:
            writeToDocument(x, y, self.id().split('.')[-1], 'These values should be equal')
            raise err

if __name__ == '__main__':
    unittest.main()