Python 有没有办法使py.test忽略子进程上引发的SystemExit?
我正在测试一个Python模块,其中包含以下代码片段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
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)