[Python] How to unit test nested exception in python?

Discussão em 'Python' iniciado por Stack, Junho 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have the scenario as follows,

    class SomeException(Exception):
    pass

    class SomeOtherException(Exception):
    pass

    def first_fn():
    raise SomeException

    def second_fn():
    try:
    first_fn()
    except Exception as e:
    raise SomeOtherException from e


    I want to check that, somewhere in the chain whether "SomeException" was raised. I have written the unittest as follows,

    import unittest

    class MyTestCase(unittest.TestCase):

    def test_case(self):
    self.assertRaises(SomeException, second_fn)

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


    But the unit test fails. But if I do the following,

    class MyTestCase(unittest.TestCase):

    def test_case(self):
    self.assertRaises(SomeOtherException, second_fn)



    then it is passing.

    Is there a way to check whether a particular nested exception was raised in the exception stack trace?

    Continue reading...

Compartilhe esta Página