Search code examples
pythonamazon-web-servicesdockeraws-lambdamoto

Mocking AWS lambda with Moto


I am trying to mock an AWS lambda function, below is my sample code

def get_lambda_resp(arn: str, input: str) -> str:
    lambda_client = boto3.client("lambda")
    response = lambda_client.invoke(
        FunctionName=arn, LogType="None",
        Payload=json.dumps({"param": input}).encode("utf-8")
    )
    output = json.loads(response["Payload"].read().decode("utf-8"))
    return output["value"]

and below is my test case

import io
import zipfile

import boto3
from moto import mock_lambda

@mock_lambda
def test():
    conn = boto3.client('lambda', 'us-east-1')

    def get_test_zip_file():
        pfunc = '''
        import json
        def lambda_handler(event, context):
            resp = {"value":"input_str"}
            return json.dumps(resp)
        '''
        zip_output = io.BytesIO()
        zip_file = zipfile.ZipFile(zip_output, 'w', zipfile.ZIP_DEFLATED)
        zip_file.writestr('lambda_function.py', pfunc)
        zip_file.close()
        zip_output.seek(0)
        return zip_output.read()

    conn.create_function(
        FunctionName='lambda-function-name',
        Runtime='python3.8',
        Role='test-iam-role',
        Handler='lambda_function.lambda_handler',
        Code={
            'ZipFile': get_test_zip_file(),
        },
        Description='test lambda function',
        Timeout=3,
        MemorySize=128,
        Publish=True
    )

    resp = get_auth("arn", "input_str")
    assert resp is not None

While running the test case, I am getting below error

E   ModuleNotFoundError: No module named 'docker'

I already have my Docker running, What else should I do to run it?


Solution

  • That message refers to the pip-module called docker. Assuming you use Moto >=2.x, make sure you install it correctly to get all required dependencies:

    pip install moto[awslambda,s3,service1,etc]

    Or if you use many services, install all dependencies without having to list all services:

    pip install moto[all]

    This will install all required Pip modules, including Docker.

    Source: https://github.com/spulec/moto/issues/3722