Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pytest throws exception while using ClickArguments SystemExit: 0

I am trying to run a test case for a python script. Test case is successful when I don’t use Click decorator and argument in python script method.

But when I am using it, it gives SystemExit: 0.

cleanup.py:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import boto3
import sys
import click

ec2=boto3.client("ec2")

@click.command()
@click.argument('ami_info',nargs=-1)
def get_all_amis(ami_info):
    print("amis_to_retain --> {}".format(ami_info[1]))
    print("amis_name_prefix --> {}".format(ami_info[0]))
    amis=ec2.describe_images(Owners=["self"])
    return amis

test_cleanup.py:

import boto3
import sys
import botocore.session
from botocore.stub import Stubber
import pytest
import cleanup

@pytest.fixture(autouse=False)
def stub_ec2():
    ec2_stubber = boto3.client("ec2")
    stubber = Stubber(ec2_stubber)
    cleanup.ec2=ec2_stubber
    yield stubber
    try:
        stubber.deactivate()
    except:
        print("ec2 Stubber already deactivated")

def test_ami_list(stub_ec2):
    stub_ec2.add_response(
        'describe_images',
        expected_params={'Owners':['self']},
        service_response={"Images": [{"ImageId": "DummyVal"}]}
    )
    stub_ec2.activate()
    response = cleanup.get_all_amis(["ctm","10"])
    print("response is --> {}".format(response))

I am running test case per below

pytest -rA tests

where tests is the directory where both above files are kept.

Test fails with SystemExit: 0

>Solution :

Don’t run click commands directly; they will use sys.exit(0) when done.

Instead, follow the Testing Click Applications chapter and use CliRunner() object to run your commands:

from click.testing import CliRunner
# ...


def test_ami_list(stub_ec2):
    stub_ec2.add_response(
        'describe_images',
        expected_params={'Owners':['self']},
        service_response = {"DummyKey":"DummyVal"}
    )
    stub_ec2.activate()

    runner = CliRunner()
    result = runner.invoke(cleanup.get_all_amis, ["ctm", "10"])
    response = result.return_value

Note that I passed in a list of string arguments; click will parse those into the correct structure.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading