Hailiang Zhang
Hailiang Zhang

Reputation: 18950

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

It seems that python nosetest will quit when encountered sys.exit(), and mocking of this builtin doesn't work.

Upvotes: 21

Views: 16223

Answers (5)

aless80
aless80

Reputation: 3342

From this article on medium:

def test_exit(mymodule):
    with pytest.raises(SystemExit) as pytest_wrapped_e:
            mymodule.will_exit_somewhere_down_the_stack()
    assert pytest_wrapped_e.type == SystemExit
    assert pytest_wrapped_e.value.code == 42

Upvotes: 0

kichik
kichik

Reputation: 34744

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

with self.assertRaises(SystemExit):
  myFunctionThatSometimesCallsSysExit()

Upvotes: 43

Tarrasch
Tarrasch

Reputation: 10567

This is an example in the unittest framework.

with self.assertRaises(SystemExit) as cm:
    my_function_that_uses_sys_exit()
self.assertEqual(cm.exception.code, expected_return_code)

Upvotes: 7

Adam Wagner
Adam Wagner

Reputation: 16127

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

Upvotes: 9

kindall
kindall

Reputation: 184455

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...

Upvotes: 7

Related Questions