0

Hi I have a following class/ function

class A:
  def __init__(aws_profile_name, aws_region, ec2_id):
      self.session = boto3.session.Session(profile_name=aws_profile_name, aws_region)

      self.ec2 = EC2(self.session, aws_region, id=ec2_id)

class EC2:
  def __init__(self, session, aws_region, id):
      self.session = session
      self.region = aws_region
      self.id = id
  
      self.ec2_resouce = self.session.resource("ec2", region_name=self.region)
      self.ec2_client = self.session.client("ec2", region_name=self.region)

      self.instance = self.filter_ec2_by_id()

  def filter_ec2_by_id(self):
      return self.filter(
            InstanceIds=[
               self.get_instance_id(),
            ]
        )

  def filter(self, kwargs):
    instances = self.ec2_resouce.instances.filter(**kwargs)
    instance_list = [instance for instance in instances]
    return instance_list

And here is my test test.py

from unittest import mock
import sys
from moto import mock_ec2
import boto3

@mock_ec2
def test_mock_session():
    mock_session_obj = mock.Mock()

    ec2 = boto3.resource("ec2", region_name="us-east-1")
    reservation = client.run_instances(ImageId="ami-1234", MinCount=2, MaxCount=2)
    instance1 = ec2.Instance(reservation["Instances"][0]["InstanceId"])

    ec2 = EC2(mock_session_obj, region="us-east-1", id=instance1)

test_mock_session()

With above test code, the test failed with following error

instance_list = [instance for instance in instances]
TypeError: 'Mock' object is not iterable

I think that is because ec2 filter return a collection, but I am not sure how should i mock the result. Any recommendation is welcomed.

TIA

spiderloop
  • 809
  • 1
  • 9
  • 10

1 Answers1

0

Moto will already mock boto3 for you, and intercept any calls to AWS, so there is no need to use mock_session_obj.

Just use EC2(boto3.session.Session(), region="us-east-1", id=instance1). When calling the filter-function, Moto will intercept it and return any created instances in the correct format.

Bert Blommers
  • 1,788
  • 2
  • 13
  • 19