Check error code or message from SystemExit in pytest

According to the pytest documentation, I can claim that SystemExit () takes place, but I want to do more: I also want to check the exit code and any messages. I tried the code below, but it doesnโ€™t print anything, and I'm not sure what I will need to claim in order to prove that I have the correct error code.

with pytest.raises(SystemExit): docopt_args = validate_args(docopt_args) out, err = pytest.capsys.readouterr() assert out == 'Foo' print out, err 

When I run my test, it passes, but thatโ€™s it. Nothing is printed, and I am not getting an approval error.

The code I expect to execute is:

  print '\n' + docopt_args['-d'] + ' is not a valid date\n' sys.exit(-3) 
+7
python
source share
2 answers

This works with the latest pytest :

All you have to do is run pytest with the option --capture=sys and depend on the statement outside the context of raises() (this bit is important for some reason!)

Example:

 #!/usr/bin/env python from __future__ import print_function import pytest def f(code=0): print("Foo") raise SystemExit(code) def test_f(capsys): with pytest.raises(SystemExit): f() out, err = capsys.readouterr() assert out == "Foo\n" print(out, err) 

Demo:

 $ py.test -v --capture=sys test_foo.py ======================================= test session starts ======================================== platform linux2 -- Python 2.7.9 -- py-1.4.27 -- pytest-2.7.0 -- /home/prologic/.virtualenvs/test/bin/python rootdir: /home/prologic/tmp, inifile: collected 1 items test_foo.py::test_f PASSED ===================================== 1 passed in 0.00 seconds ===================================== 

Changing print("Foo") to print("Bar") results in:

 $ py.test -v --capture=sys test_foo.py ======================================= test session starts ======================================== platform linux2 -- Python 2.7.9 -- py-1.4.27 -- pytest-2.7.0 -- /home/prologic/.virtualenvs/test/bin/python rootdir: /home/prologic/tmp, inifile: collected 1 items test_foo.py::test_f FAILED ============================================= FAILURES ============================================= ______________________________________________ test_f ______________________________________________ capsys = <_pytest.capture.CaptureFixture instance at 0x7f2729405518> def test_f(capsys): with pytest.raises(SystemExit): f() out, err = capsys.readouterr() > assert out == "Foo\n" E assert 'Bar\n' == 'Foo\n' E - Bar E + Foo test_foo.py:17: AssertionError ===================================== 1 failed in 0.01 seconds ===================================== 

What I think is exactly what you were after!

I did this in pure virtualenv :

 mkvirtualenv test pip install pytest 

The trick here is to read and understand setting capture methods or disabling capture

+9
source share
 import pytest def test_exit(): with pytest.raises(SystemExit): script_exit() 
0
source share

All Articles