ChinnaR
ChinnaR

Reputation: 837

how to mock lambda cache ssm getattr

I am using lambda_cache library in python to implement caching for coupld of parameters stored in ssm. The following code is working as expected.

from lambda_cache import ssm

@ssm.cache(parameter=['applicationId', 'sharedSecret'], entry_name='parameters', max_age_in_seconds=300)
def lambda_handler(event, context):  
        applicationId = getattr(context,'parameters').get('applicationId')
        sharedSecret = getattr(context,'parameters').get('sharedSecret')  
        #rest of code

I want to implement a unit test where I need to assign some values to applicationId and sharedSecret. I started as follows

@mock_ssm
def test_lambda_handler1(self):
ssm = boto3.client('ssm', region_name=REGION_NAME)
    response = ssm.put_parameter (
        Name = 'parameters',
        Value = 'applicationIdValue',
        KeyId='applicationId',
        Type = 'String',
        Overwrite = True
    )

    response = ssm.put_parameter (
        Name = 'parameters',
        Value = 'sharedSecretValue',
        KeyId = 'sharedSecret',
        Type = 'String',
        Overwrite = True
    )

lambda_handler(event, None)

this has thrown the error 'NoneType' object has no attribute 'parameters'.

So I then created a context as

    context = {
        'parameters':'parameters'
    }

and then called the lambda as

 lambda_handler(event, context)

it then thrown the error 'dict' object has no attribute 'parameters'

I have then tried creating a class

class context:
    parameters = {"applicationId":"testapplicationId", "sharedSecret":"testsharedSecret"}

and in the unit test

s1 = context()
lambda_handler(event,s1)

But this is returning None for both applicationId and sharedSecret as getattr(context, 'parameters') itself show the len() as 0.

Parameters set in the context class in TestCase are not passed to the lamdba_handler. I think it only allows the attributes defined in the link https://docs.aws.amazon.com/lambda/latest/dg/python-context.html like aws_request_id,memory_limit_in_mb , etc. How can I mock ssm cache to get the parameter values?

Upvotes: 1

Views: 256

Answers (1)

Anthone Silva
Anthone Silva

Reputation: 1

That's how I achieved that, declaring a class as you did, but with some changes:

class LambdaContext:

def __init__(self):
    self.__setattr__('parameters', 'values')
    self.function_name: str = "test"
    self.memory_limit_in_mb: int = 128

Then, you just have to import this class overloading where you want to use the context, as in:

from setup import LambdaContext

def test_case():
    lambda_function.lambda_handler(event, LambdaContext())

I hope it helps!

Upvotes: 0

Related Questions