Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get around "sys.exit()" in python nosetest?

It seems that python nosetest will quit when encountered "sys.exit()", and mocking of this built-in doesn't work. Thanks for suggestions.

like image 412
Hailiang Zhang Avatar asked Nov 30 '11 19:11

Hailiang Zhang


People also ask

How do you handle a sys exit exception?

Wrap your main code in a try / except block, catch SystemExit , and call os. _exit() there, and only there! This way you may call sys. exit normally anywhere in the code, let it bubble out to the top level, gracefully closing all files and running all cleanups, and then calling os.

Do you need SYS exit Python?

exit() function allows the developer to exit from Python. The exit function takes an optional argument, typically an integer, that gives an exit status. Zero is considered a “successful termination”.

How do I exit python without traceback?

exit() stops execution without printing a backtrace, raising an Exception does... your question describes exactly what the default behavior is, so don't change anything. @Luper It is very easy to check that sys.


2 Answers

You can try catching the SystemExit exception. It is raised when someone calls sys.exit().

with self.assertRaises(SystemExit):
  myFunctionThatSometimesCallsSysExit()
like image 175
kichik Avatar answered Sep 28 '22 16:09

kichik


If you're using mock to patch sys.exit, you may be patching it incorrectly.

This small test works fine for me:

import sys
from mock import patch

def myfunction():
    sys.exit(1)

def test_myfunction():
    with patch('foo.sys.exit') as exit_mock:
        myfunction()
        assert exit_mock.called

invoked with:

nosetests foo.py

outputs:

.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
like image 30
Adam Wagner Avatar answered Sep 28 '22 16:09

Adam Wagner