0

I want to unittest some methods inside my aws_manager:

class aws_manager:

    def __init__(self) -> None:
        self.ec2 = boto3.client('ec2', region_name=REGION_NAME)
        self.running_instances = []

 def launchInstances(self, count: int):

            instances = self.ec2.run_instances(
                ImageId=IMAGE_ID,
                MinCount=count,
                MaxCount=count,
                InstanceType=INSTANCE_TYPE,
                KeyName=KEY_NAME,
                SecurityGroupIds=[SECURITY_GROUP_ID]
            )["Instances"][0]

my test looks like this:


import unittest
import boto3
from moto import mock_ec2
import aws_manager


@mock_ec2
class TestAwsManager(unittest.TestCase):
    def test_launchInstances(self):
        manager = aws_manager.aws_manager()
        manager.launchInstances(2)
        client = boto3.client('ec2',region_name='eu-central-1')
        instances = client.describe_instances()
        print(instances)

But the instances variable looks like this when printed:

{'Reservations': [], 'ResponseMetadata': {'RequestId': 'fdcdcab1-ae5c-489e-9c33-4637c5dda355', 'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'amazon.com'}, 'RetryAttempts': 0}}

I also get this error:

[ERROR][2022-07-02 22:30:42,452]: 'NoneType' object has no attribute 'id'

Have I overseen something? Shouldn't client contain the instances?

Thanks in advance

codedor
  • 73
  • 6

1 Answers1

0

This should be your code the mock ec2 and security group id.

def ec2():
"""
Returns a mock EC2 resource
"""

with mock_ec2():

    ec2_res = boto3.resource("ec2", region_name="us-west-1")

    ec2_res.create_key_pair(KeyName="your_key")

    yield ec2_res

@pytest.fixture
def security_group_id(ec2):
    """
    Returns a mock EC2 instance
    """
    security_group = ec2.create_security_group(
        GroupName="your_group_name",
        Description="test",
    )
    yield security_group.id