Question

I'm testing a Python module which contains the following snippet of code.

        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

All tests pass, but there's s difficulty in regards to sys.exit(0). When sys.exit(0) executes, it raises SystemExit, which is intercepted by py.test and reported as an error in the console.

I don't understand in detail what py.test does internally, but looks like it goes ahead and ends up ignoring such event raised by the child process. In the end, all tests pass, which is good.

But I'd like to have a clean output in the console.

Is there a way to make py.test produce a clean output?

For your information:

  • Debian Jessie, kernel 3.12.6
  • Python 2.7.6
  • pytest 2.5.2

Thanks :)

Was it helpful?

Solution

( answering my own question )

You can terminate execution without provoking signals associated to these events. So, instead of sys.exit(n), use os._exit(n), where n is the status code desired.

Example:

import os
os._exit(0)

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

OTHER TIPS

def test_mytest():

    try:
        # code goes here
        # like
        # import my_packaage.__main__
        # which can raise
        # a SystemExit 
    except SystemExit:
        pass

    assert(True)

I found it here.

This is how I solve the problem with mock - with this approach, you can take advantage of all the cleanup sys.exit will do for us

@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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top