Skip to content
Advertisement

Check for system exit and for error logs with unittest in Python

Is it possible to check if a program stopped with sys.exit() and check for the messages that were logged using the logging module?

For example, let’s say I have the following function in a file called func.py:

JavaScript

Now, I have created a couple of tests to check my function’s performance. I know that, to test the messages logged–provided that the program completed its function–I can do something like this:

JavaScript

And if I want to check if the program is stopping when expected, I’m doing something similar to this:

JavaScript

My question is: is it possible to test for a system exit and the messages logged at the same time? In other words, I would like to modify the test_exit() test to check (a) that the program stopped with a SystemExit and (b) that the message

Something went wrong with apple.

was logged. In particular, I want to check both of these conditions because in my real script, I have several conditions that will prompt sys.exit(), and I want to test that when the program stops, it is stopping for the reason that I expect.

Advertisement

Answer

Just put the two context managers together:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement