# How to catch exceptions in test code?(Python 3.8) [closed]

I have a script that includes some independent tests that run together (not parallelly). The tests include calls for some libraries that might raise exceptions (which indicate of a failure in the test). Instead of wrapping each call with "try - except" mechanism I thought about wrapping the each test with "try - except" using decorator of this kind:

def log_exceptions(func):
def inner(*args, **kwargs):
try:
return func(*args, *kwargs)
except Exception as e: # Can be more specific here, I know
logging.error("Python Exception raised from {} - {}".format(func.__name__, e))
ERROR_MSG.append("Python Exception raised from {} - {}".format(func.__name__, e))
return False

return inner

@log_exceptions
def test1():
some_funciton_call()


Where ERROR_MSG is a list of the errors that occurred during the tests.

Do you think managing the exceptions and errors this way is a good practice? Can you suggest a different way of capturing exceptions?

Thanks! :)

• Why do you need to catch and log the exceptions there in first place? afaik uncaught exceptions dont fail tests (at least not when using pytest), so if there's an exception affecting the functionality, then it should be reflected via failing assert – yedpodtrzitko Oct 12 at 14:40
• What test framework are you using? There are several, and each one I've seen includes exception handling, including failing a test if an expected exception is not raised. Catching (and logging) an unexpected exception is the simplest case that all of those test frameworks already handle. Include your real code, and real test code, not pseudo code (some_funciton_call()) and hypothetically code (# Can be more specific), and you might get real help. Otherwise, this is vote-to-close/missing review context. – AJNeufeld Oct 12 at 16:45