A comprehensive set of tests for the provided Lambda function! I'll guide you through the process.
Test Strategy
We'll write both unit tests and integration tests. Unit tests will focus on the function's logic, mocking external dependencies like http.client and logging. Integration tests will verify the function's behavior in an AWS environment, ensuring it correctly sends metrics to CloudWatch.
Identity Policy (for the test runner)
Create an IAM policy (LambdaTestRunnerPolicy) that allows the test runner to execute the Lambda function, invoke CloudWatch actions, and log to CloudWatch Logs:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowLambdaExecution",
"Effect": "Allow",
"Action": [
"lambda:InvokeFunction",
"lambda:GetFunctionConfiguration"
],
"Resource": "arn:aws:lambda:<REGION>:<ACCOUNT_ID>:function:<LAMBDA_FUNCTION_NAME>"
},
{
"Sid": "AllowCloudWatchActions",
"Effect": "Allow",
"Action": [
"cloudwatch:GetMetricStatistics",
"cloudwatch:ListMetrics",
"cloudwatch:PutMetricData"
],
"Resource": "*"
},
{
"Sid": "AllowLogging",
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:<REGION>:<ACCOUNT_ID>:log-group:/aws/lambda/<LAMBDA_FUNCTION_NAME>*"
}
]
}
Resource Policy (for the Lambda function)
Update the Lambda function's resource policy (LambdaFunctionPolicy) to allow the test runner to invoke the function:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowTestRunnerInvocation",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::<ACCOUNT_ID>:role/<TEST_RUNNER_ROLE_NAME>"
},
"Action": "lambda:InvokeFunction",
"Resource": "arn:aws:lambda:<REGION>:<ACCOUNT_ID>:function:<LAMBDA_FUNCTION_NAME>"
}
]
}
Unit Tests (using Pytest and Moto)
Create a test_lambda_function.py file:
import json
import logging
import pytest
from moto import mock_lambda, mock_cloudwatch
from unittest.mock import patch, MagicMock
from your_module import lambda_handler # Replace 'your_module' with the actual module name
@pytest.fixture
def event():
return {}
@pytest.fixture
def context():
return MagicMock(
function_name='test-lambda',
function_version='1',
aws_request_id='1234567890'
)
@mock_lambda
@mock_cloudwatch
def test_lambda_handler_invokes_cloudwatch(event, context):
with patch('http.client.HTTPSConnection') as mock_connection:
mock_response = MagicMock(status=200, reason='OK')
mock_response.read.return_value.decode.return_value = '{"key": "value"}'
mock_connection.return_value.getresponse.return_value = mock_response
lambda_handler(event, context)
# Verify CloudWatch metrics are sent
logs = logging.getLogger().handlers[0].stream.getvalue()
metrics = [json.loads(line) for line in logs.splitlines()]
assert len(metrics) > 0
assert metrics[0]['_aws']['CloudWatchMetrics'][0]['Namespace'] == 'Example/Namespace'
assert metrics[0]['Success'] == 1
assert metrics[0]['Error'] == 0
@mock_lambda
@mock_cloudwatch
def test_lambda_handler_handles_connection_error(event, context):
with patch('http.client.HTTPSConnection') as mock_connection:
mock_connection.side_effect = Exception('Connection error')
lambda_handler(event, context)
# Verify error metric is sent
logs = logging.getLogger().handlers[0].stream.getvalue()
metrics = [json.loads(line) for line in logs.splitlines()]
assert len(metrics) > 0
assert metrics[0]['Error'] == 1
assert metrics[0]['Success'] == 0
@mock_lambda
@mock_cloudwatch
def test_lambda_handler_handles_response_error(event, context):
with patch('http.client.HTTPSConnection') as mock_connection:
mock_response = MagicMock(status=500, reason='Internal Server Error')
mock_connection.return_value.getresponse.return_value = mock_response
lambda_handler(event, context)
# Verify error metric is sent
logs = logging.getLogger().handlers[0].stream.getvalue()
metrics = [json.loads(line) for line in logs.splitlines()]
assert len(metrics) > 0
assert metrics[0]['Error'] == 1
assert metrics[0]['Success'] == 0
def test_lambda_handler_generates_random_paths(event, context):
with patch('http.client.HTTPSConnection') as mock_connection:
mock_response = MagicMock(status=200, reason='OK')
mock_response.read.return_value.decode.return_value = '{"key": "value"}'
mock_connection.return_value.getresponse.return_value = mock_response
lambda_handler(event, context)
# Verify random paths are generated
logs = logging.getLogger().handlers[0].stream.getvalue()
metrics = [json.loads(line) for line in logs.splitlines()]
assert len(set(metric['FullPath'] for metric in metrics)) > 1
def test_lambda_handler_adds_data_to_metrics(event, context):
with patch('http.client.HTTPSConnection') as mock_connection:
mock_response = MagicMock(status=200, reason='OK')
mock_response.read.return_value.decode.return_value = '{"key": "value"}'
mock_connection.return_value.getresponse.return_value = mock_response
lambda_handler(event, context)
# Verify data is added to metrics
logs = logging.getLogger().handlers[0].stream.getvalue()
metrics = [json.loads(line) for line in logs.splitlines()]
assert 'Data' in metrics[0]
assert metrics[0]['Data'] == {'key': 'value'}