I have a Python 2.7 method that sometimes calls
sys.exit(1)
Is it possible to make a unit test that verifies this line of code is called when the right conditions are met?
You actually can mock or stub out the System. exit method, in a JUnit test. Vote down reason: The problem with this solution is that if System. exit is not the last line in the code (i.e. inside if condition), the code will continue to run.
sys.exit([arg]) exit() is considered good to be used in production code for the sys module is always available. The optional argument arg can be an integer giving the exit or another type of object. If it is an integer, zero is considered “successful termination”. Note: A string can also be passed to the sys.
Python testing framework uses Python's built-in assert() function which tests a particular condition. If the assertion fails, an AssertionError will be raised. The testing framework will then identify the test as Failure.
Yes. sys.exit
raises SystemExit
, so you can check it with assertRaises
:
with self.assertRaises(SystemExit): your_method()
Instances of SystemExit
have an attribute code
which is set to the proposed exit status, and the context manager returned by assertRaises
has the caught exception instance as exception
, so checking the exit status is easy:
with self.assertRaises(SystemExit) as cm: your_method() self.assertEqual(cm.exception.code, 1)
sys.exit Documentation:
Exit from Python. This is implemented by raising the
SystemExit
exception ... it is possible to intercept the exit attempt at an outer level.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With