开发者

PyUnit with child processes

In some Python code, I fork and do some processing in a child process while the parent waits for it to exit. It doesn't exec after the fork.

I'm having a problem testing this code in PyUnit, because when the child process exits explicitly with sys.exit, it creates a PyUnit error.

This code below produces the problem

class TestClass(TestCase):
    def test(se开发者_运维百科lf):
        pid = os.fork()
        if pid == 0:
            sys.exit(0)
        else:
            os.waitpid(pid,0)

This is the error

Traceback (most recent call last):
  File "test.py", line 15, in test
    sys.exit(0)
SystemExit: 0
----------------------------------------------------------------------
Ran 1 test in 0.007s

FAILED (errors=1)

Is there some way to avoid PyUnit failing the test if a child process exits explicitly?


All that sys.exit does is throw a SystemExit exception, that bubbles up as normal. However os._exit(0) will exit immediately and does not give any cleanup code a chance to run. This prevents PyUnit from doing anything, including failing the test. So in your test code you can trap SystemExit and call os._exit instead.

If the child process expects some explicit cleanup to happen on exit, you'll have to arrange to do that in your test case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜