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:
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.