smhk

Captured `SystemExit` with pytest and tox

I wanted to unit test some Python code that uses sys.exit(exit_code) to verify whether the exit_code was as expected. The first answer I came across suggests using the built in capsys fixture which is enabled with setting --capture=sys when running pytest. However for me this clashed with my tox.ini:

[testenv]
commands =
  pytest -vv {posargs}

I take advantage of the {posargs} feature by sometimes running tox with arguments for pytest, for example tox -e py27 -- --capture=no in order to stop pytest from capturing stdout. Using the --capture=sys method in my tox.ini as mentioned above did not seem to play well with optionally using --capture=no when invoking pytest through tox.

A better solution is to capture the exception rather than using capsys. This avoids the need to use the --capture=sys option at all:

def test_exit():
    with pytest.raises(SystemExit) as exc:
        # test goes here
    assert exc.value.code == 0