Search code examples
pythonpytestexit-code

how to make pytest fail on shellcommand invocation failure


For a python pytest file with contents of:

import os
def test_that():
    print("step 1: should work")
    os.system("echo hello")
    
    print("step 2: should fail")
    os.system("asdf_failing_non_existing_command")

and an invocation of pytest like:

 pytest -s testing.py

The output is:

1 passed

I would expect the test to fail. How can I get the exit code from os system call to influence the test failure and actually fail the test?


Solution

  • How can I get the exit code from os system call to influence the test failure and actually fail the test?

    Don't use os.system. (You almost never need it, and the docs are pretty strong on using subprocess instead).

    With subprocess:

    import subprocess
    
    subprocess.run(["echo", "hi"], check=True)
    subprocess.run(["asdfasdfasdfdas"], check=True)
    

    Or you can use os.system and check yourself, but why reinvent the wheel?