Search code examples
pythonunit-testingpython-unittestnose

Is it possible to test a function which uses `os._exit()`?


I want to test that a function executes os._exit(2) on fail. I have seen many solutions with sys.exit() using SystemExit. I have read both the Python3 and the Python2 documentation and it seems that os._exit() doesn't use SystemExit

Nevertheless, I have tried this in case it was a misunderstanding of the documentation on my side, but it just exits nosetest, it's not even a test failure :

make: *** [test] Error 2

This is probably due to the function calling os._exit(2)


Solution

  • os.system() return value contains exit code in higher 8 bits, so you could check exit code of external script this way:

    import os
    
    assert os.system('python script.py') >> 8 == 2
    

    You could also mock os._exit() with sys.exit():

    import os, sys
    import script
    
    os._exit = sys.exit
    script.tested_method()  # raises SystemExit