Sam Hooke

These are rough notes from whatever I was working on, interested in or thinking about at the time. They vary greatly in quality and length, but prove useful to me, and hopefully to you too!

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
<< Previous: Tastypie "TypeError of type 'NoneType' is not iterable"
Next: Automatic image thumbnails in Hugo from static directory >>