'TypeError: 'ec2.instancesCollectionManager' object is not iterable when mocking with Moto?

The following code got error of "TypeError: 'ec2.instancesCollectionManager' object is not iterable" when casting to list(instances) using Moto.

@pytest.fixture(scope='function')
def aws_credentials():
    os.environ['AWS_ACCESS_KEY_ID'] = 'testing'
    os.environ['AWS_SECRET_ACCESS_KEY'] = 'testing'
    os.environ['AWS_SECURITY_TOKEN'] = 'testing'
    os.environ['AWS_SESSION_TOKEN'] = 'testing'
    os.environ["MOTO_ALLOW_NONEXISTENT_REGION"] = 'True'
    os.environ['AWS_DEFAULT_REGION'] = 'us-east-1'

@pytest.fixture
def session(aws_credentials):
    return boto3.session.Session()

@mock_ec2
def test_get_nodes(session):
    #session = boto3.session.Session(region_name='us-east-1')
    filters = None
    Node.get_nodes(session, filters)
    instances = session.resource('ec2').instances
    print(list(instances))  # ERR
    assert any(instances)  # ERR

The instance in Node class can be casted to list() if not using Moto.

class Node(NodeBase):
    @classmethod
    def get_nodes(cls, session, filters):
        instances = session.resource('ec2').instances.filter(Filters=filters)
        return instances

print(type(instances)) got <class 'boto3.resources.collection.ec2.instancesCollection'> whenever using Moto or not.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source