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

北战南征 提交于 2021-02-07 11:22:49

问题


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


回答1:


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

with self.assertRaises(SystemExit):
  myFunctionThatSometimesCallsSysExit()



回答2:


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




回答3:


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



回答4:


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)


来源:https://stackoverflow.com/questions/8332090/how-to-get-around-sys-exit-in-python-nosetest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!