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 cli.py
:
from argparse import ArgumentParser
def create_parser():
parser = ArgumentParser()
parser.add_argument('list', help='List something')
...
return parser
The tests:
import pytest
from parser import cli
@pytest.fixture
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
Top comments (0)