【问题标题】:Is there a way to make py.test ignore SystemExit raised on a child process?有没有办法让 py.test 忽略子进程引发的 SystemExit?
【发布时间】:2014-03-09 11:10:42
【问题描述】:

我正在测试一个 Python 模块,其中包含以下 sn-p 代码。

        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

谢谢:)

【问题讨论】:

    标签: python multiprocessing pytest systemexit


    【解决方案1】:
    def test_mytest():
    
        try:
            # code goes here
            # like
            # import my_packaage.__main__
            # which can raise
            # a SystemExit 
        except SystemExit:
            pass
    
        assert(True)
    

    我找到了here

    【讨论】:

      【解决方案2】:

      这就是我用 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
      

      【讨论】:

        【解决方案3】:

        (回答我自己的问题)

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

        例子:

        import os
        os._exit(0)
        

        学分: Is there a way to prevent a SystemExit exception raised from sys.exit() from being caught?

        【讨论】:

          猜你喜欢
          • 2015-01-20
          • 1970-01-01
          • 2010-11-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-15
          • 2021-01-06
          • 1970-01-01
          相关资源
          最近更新 更多