我正在将一个afl-fuzz (一个C应用程序)重写为Python。由于我对它的内部工作原理没有足够的了解,我想尽可能地复制它的功能。
我正在尝试运行一个例程的功能测试,该例程派生Python解释器,运行execve,如果失败,则通过返回42向调用者报告失败。这个测试在unittest之外运行得很好,但是在放进去的时候失败了:
#!/usr/bin/env python
import os
import sys
import unittest
def run_test():
x = os.fork()
if not x:
sys.exit(42)
waitpid_result, status = os.waitpid(x, os.WUNTRACED)
print(os.WEXITSTATUS(status))
class ForkFunctionalTest(unittest.TestCase):
def test_exercise_fork(self):
run_test()
if __name__ == '__main__':
print('Expecting "42" as output:')
run_test()
print('\nAnd here goes unexpected SystemExit error:')
unittest.main()下面是它失败的原因:
Expecting "42" as output:
42
And here goes unexpected SystemExit error:
E
======================================================================
ERROR: test_exercise_fork (__main__.ForkFunctionalTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "afl-fuzz2.py", line 23, in test_exercise_fork
run_test()
File "afl-fuzz2.py", line 15, in run_test
sys.exit(42)
SystemExit: 42
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
1
.
----------------------------------------------------------------------
Ran 1 test in 0.014s
OK有没有一种方法可以让unittest在不改变run_test的情况下使用这个函数?我尝试了os._exit而不是sys.exit(),但它使程序在两个进程中都死了。
发布于 2017-05-27 22:47:08
事实证明,os._exit实际上是有效的,但在我的单元测试中,我需要模拟它,因为我模拟了os.fork。愚蠢的错误。
发布于 2017-05-27 22:42:03
sys.exit()会引发SystemExit类异常,如果未捕获到该异常,则会退出程序。您可以尝试捕获异常:
def text_exercise_fork(self):
try:
run_test()
except SystemExit as e:
print(e.args[0])https://stackoverflow.com/questions/44218092
复制相似问题