How can we mock test a Lamdba that references a Secret Manager

0

I am trying to run a unit test for a lambda function where I am using SECRET_ARN for incident creation using Secret Manager

I am fetching SECRET_ARN from the environment variable SECRET_ARN = os.environ.get("SECRET_ARN")

But when I am trying to run the test case to check for event status as "ABORTED" I get an error as ParamValidationError(report=report.generate_report()) botocore.exceptions.ParamValidationError: Parameter validation failed: Invalid type for parameter SecretId, value: None, type: <class 'NoneType'>, valid types: <class 'str'>

Below is my LambdaTest Code for reference :

import os
import boto3
import unittest
from unittest.mock import MagicMock, patch
from moto import mock_aws
import sys
from lambda.my_lambda_function import lambda_handler

class TestLambdaFunction(unittest.TestCase):
@mock_aws
    def test_lambda_handler_aborted_execution(self):
    # Mock event data for aborted execution
        event = {
            'status': 'ABORTED',
            'stateMachineArn': 'arn:aws:states:region:<Account_ID>:stateMachine:myStateMachineARN',
            'input': '{}'
        }

    # Create a mock SNS topic
        sns_client = boto3.client("sns", region_name="my_region")

    # Set snsARN as an environment variable
        os.environ['snsARN'] = sns_client.create_topic(Name="MySNSTopic")['TopicArn']

        context = MagicMock()
    # Call lambda_handler function
        result = lambda_handler(event, context)

    # Assert that the result is as expected
        self.assertEqual(result['statusCode'], 200)
        self.assertEqual(result['body'], 'Function execution complete.')


if __name__ == "__main__":
    unittest.main()

  • Hi, you have to give more details about the code of lambda.my_lambda_function to get useful help: we need to see how you use SecretsManager (directly or indirectly)

  • Hi, below is the generated standard code used to retrieve the Secrets from the secrets manager:

    import boto3
    from botocore.exceptions import ClientError
     
     
    def get_secret():
     
        secret_name = "mySecrets"
        region_name = "us-east-1"
     
        # Create a Secrets Manager client
        session = boto3.session.Session()
        client = session.client(
            service_name='secretsmanager',
            region_name=region_name
        )
     
        try:
            get_secret_value_response = client.get_secret_value(
                SecretId=secret_name
            )
        except ClientError as e:
            raise e
     
        secret = get_secret_value_response['SecretString']
    
    

    I am using get_secret_from_secret_manager(SECRET_ARN) to fetch the credentials.

Vivek P
asked 2 months ago40 views
No Answers

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions