DEV Community

Boris Quiroz
Boris Quiroz

Posted on

 

🐍 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

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.