2017-05-27 78 views
0

我正在为Python重写一个afl-fuzz(一个C应用程序)。由于我对其内部工作没有足够的了解,因此我想尽可能地复制其功能。我可以使用UnitTest的SystemExit处理程序吗?

我试图运行一个例程的功能测试,它运行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 

有没有办法让这个功能单元测试工作,而无需改变RUN_TEST?我尝试了os._exit而不是sys.exit(),但它使程序在两个进程中都死亡。

回答

1

sys.exit()引发SystemExit类异常,如果未捕获,则会退出该程序。你可以尝试捕捉异常:

def text_exercise_fork(self): 
    try: 
     run_test() 
    except SystemExit as e: 
     print(e.args[0]) 
+0

谢谢。问题是我不想捕获它,我想实际上分叉的进程死于退出代码= 42。 – d33tah

0

原来,os._exit实际工作,但在我的单元测试,我需要嘲笑它因为我嘲笑了os.fork。愚蠢的错误。

相关问题