In Python 3, using Pytest, how do we test for exit code : exit(1) and exit(0) for a python program?

Viewed 7279

I am new to Pytest in python .

I am facing a tricky scenario where I need to test for exit codes - exit(1) and exit(0) , using Pytest module. Below is the python program :

 def sample_script():
     count_file  = 0
     if count_file == 0:
        print("The count of files is zero")
     exit(1)
     else:
         print("File are present")
     exit(0)

Now I want to test the above program for exit codes, exit(1) and exit(0) . Using Pytest how we can frame the test code so that we can test or asset the exit code of the function sample_script ?

Please help me.

1 Answers

Once you put the exit(1) inside the if block as suggested, you can test for SystemExit exception:

from some_package import sample_script


def test_exit():
    with pytest.raises(SystemExit) as pytest_wrapped_e:
        sample_script()
    assert pytest_wrapped_e.type == SystemExit
    assert pytest_wrapped_e.value.code == 42

The example is taken from here: https://medium.com/python-pandemonium/testing-sys-exit-with-pytest-10c6e5f7726f

UPDATE:

Here's a complete working example you can copy/paste to test:

import pytest

def sample_func():
    exit(1)

def test_exit():
    with pytest.raises(SystemExit) as e:
        sample_func()
    assert e.type == SystemExit
    assert e.value.code == 1

if __name__ == '__main__':
    test_exit()
Related