DEV Community

Boris Quiroz
Boris Quiroz

Posted on

3

🐍 Testing exit codes with Pytest

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay