Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for a unit test to assert that a method calls sys.exit()?

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?

like image 370
Travis Bear Avatar asked Mar 28 '13 00:03

Travis Bear


People also ask

How do you handle system exit in JUnit?

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.

What is SYS exit in Python?

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.

What does a Unittest assert do?

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.


1 Answers

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.

like image 188
Pavel Anossov Avatar answered Sep 30 '22 16:09

Pavel Anossov