【问题标题】:Can I work around UnitTest's SystemExit handler?我可以解决 UnitTest 的 SystemExit 处理程序吗?
【发布时间】:2017-05-27 14:33:12
【问题描述】:

我正在将 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(),但它使程序在两个进程中都死掉了。

【问题讨论】:

    标签: python unix exit python-unittest low-level


    【解决方案1】:

    事实证明 os._exit 确实有效,但在我的单元测试中我需要模拟它,因为我模拟了 os.fork。愚蠢的错误。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 谢谢。问题是我不想抓住它,我真的想让分叉的进程在退出代码 = 42 的情况下死掉。
      猜你喜欢
      • 2014-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多