DEV Community


🐍 Testing exit codes with Pytest

boris profile image Boris Quiroz ・1 min read

As almost every other sysadmin I know, python is the language of choice to do some scripting. And, as we all know, testing is an important part of any development.

My code is a simple parser that interacts with some Linux commands using subprocess, which instead of raising an exception it returns something != 0. In fact, the exit code is 2. How to test that with pytest? This is what I did (which might not be the best way to do it):

The parser is pretty simple, this is the

from argparse import ArgumentParser

def create_parser():
    parser = ArgumentParser()
    parser.add_argument('list', help='List something')
    return parser
Enter fullscreen mode Exit fullscreen mode

The tests:

import pytest
from parser import cli

def parser():
    return cli.create_parser()

def test_something_to_test(parser):
    with pytest.raises(SystemExit) as e:
        # The command to test
        parser.parse_args(['some', 'commands'])
    # Here's the trick
    assert e.type == SystemExit
    assert e.value.code == 2
Enter fullscreen mode Exit fullscreen mode


Editor guide