Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 有没有办法使py.test忽略子进程上引发的SystemExit?_Python_Multiprocessing_Pytest_Systemexit - Fatal编程技术网

Python 有没有办法使py.test忽略子进程上引发的SystemExit?

Python 有没有办法使py.test忽略子进程上引发的SystemExit?,python,multiprocessing,pytest,systemexit,Python,Multiprocessing,Pytest,Systemexit,我正在测试一个Python模块,其中包含以下代码片段 r, w = os.pipe() pid = os.fork() if pid: os.close(w) # use os.close() to close a file descriptor r = os.fdopen(r) # turn r into a file object # read seria

我正在测试一个Python模块,其中包含以下代码片段

        r, w = os.pipe()
        pid = os.fork()
        if pid:
            os.close(w)        # use os.close() to close a file descriptor
            r = os.fdopen(r)   # turn r into a file object
            # read serialized object from ``r`` and persists onto storage medium
            self.ofs.put_stream(bucket, label, r, metadata)
            os.waitpid(pid, 0) # make sure the child process gets cleaned up
        else:
            os.close(r)
            w = os.fdopen(w, 'w')
            # serialize object onto ``w``
            pickle.dump(obj, w)
            w.close()
            sys.exit(0)
        return result
所有测试都通过了,但是在
sys.exit(0)
方面存在困难。 当执行
sys.exit(0)
时,它会引发
SystemExit
,被
py.test
截取并在控制台中报告为错误

我不太清楚py.test在内部做了什么,但看起来它继续进行,最终忽略了子进程引发的此类事件。最后,所有测试都通过了,这很好

但是我希望在控制台中有一个干净的输出

有没有办法使
py.test
产生干净的输出

供您参考:

  • Debian Jessie,内核3.12.6
  • Python 2.7.6
  • pytest 2.5.2
谢谢:)

(回答我自己的问题)

您可以在不触发与这些事件关联的信号的情况下终止执行。 因此,不要使用
sys.exit(n)
,而是使用
os.\u exit(n)
,其中
n
是所需的状态代码

例如:

import os
os._exit(0)
学分:
这就是我用mock解决问题的方法-通过这种方法,您可以利用所有清理
sys.exit
将为我们做的事情

@mock.patch('your.module.sys.exit')
def test_func(mock_sys_exit):
    mock_sys_exit.side_effect = SystemExit("system is exiting")
    with pytest.raises(SystemExit):
        # run function that supposed to trigger SystemExit
我找到了

def test_mytest():

    try:
        # code goes here
        # like
        # import my_packaage.__main__
        # which can raise
        # a SystemExit 
    except SystemExit:
        pass

    assert(True)