是否可以测试使用“os._exit()”的函数?

Is it possible to test a function which uses `os._exit()`?

我想测试函数在失败时执行 os._exit(2)。我已经看到许多 sys.exit() 使用 SystemExit 的解决方案。我已经阅读了 Python3 and the Python2 文档,似乎 os._exit() 没有使用 SystemExit

尽管如此,我已经尝试 this 以防我对文档的误解,但它只是退出 nosetest,甚至不是测试失败:

make: *** [test] Error 2

这可能是由于函数调用 os._exit(2)

os.system() return 值包含高 8 位的退出代码,因此您可以这样检查外部脚本的退出代码:

import os

assert os.system('python script.py') >> 8 == 2

你也可以用 sys.exit():

模拟 os._exit()
import os, sys
import script

os._exit = sys.exit
script.tested_method()  # raises SystemExit

unittest.mock.MagicMock 对象使得简单地检查函数是否被调用变得容易,而不需要它们执行它们的默认行为。

from unittest import mock
import os

def funcToTest():
    os.exit(2)

def test_func():
    os._exit = mock.MagicMock()
    funcToTest()
    assert os._exit.called