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

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

with self.assertRaises(SystemExit):
  myFunctionThatSometimesCallsSysExit()

import sys
sys.exit = lambda *x: None

Keep in mind that programs may reasonably expect not to continue after sys.exit(), so patching it out might not actually help...


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