Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading