I am trying to make a Python unit test that will pass if no exceptions are raised and fail if any are (even if they are handled).
My code is basically like this:
def do_something():
try:
# Do some code
pass
except:
print("An exception was raised")
class TestDoSomething(unittest.TestCase):
def test_do_something(self):
do_something()
But this test will pass regardless of any exceptions raised in the try block.
How do I get this test to fail if an exception is raised?
I have already tried the various answers along the lines of
def test_do_something(self):
try:
do_something()
except:
self.fail("An exception was raised")
These answers result in the exception being swallowed by the code being tested.
I guess that is one example, why a bare except statement is a problematic solution.
If you decide to go this path anyway, you could probably mock the print function to return the string and test, if this return value is your print string.