Lambda Handler Configuration Validation Tests
Status: ✅ Implemented and Passing
Date: 2025-12-04
Test File: /tests/infrastructure/lambda-handler-config.test.ts
Coverage: 34 tests, 100% passing
Executive Summary
A comprehensive test suite has been implemented to validate that Lambda handler configurations in Terraform match the actual file structure in deployment packages. This test suite prevents a critical bug that caused 502 errors due to handler path misconfigurations.
Background: The Bug
Original Issue
The lessons_handler Lambda function had a misconfigured handler path in Terraform:
Incorrect Configuration (caused 502 error):
resource "aws_lambda_function" "lessons_handler" {
handler = "index.handler" # ❌ WRONG - Missing full path
# ...
}
Error Result:
Runtime.ImportModuleError: Error: Cannot find module 'index'
Root Cause
The handler configuration "index.handler" told AWS Lambda to look for a file named index.js at the root of the zip file. However, the actual file structure inside the zip was:
functions/lessons/src/index.js # ✅ Actual location
Fixed Configuration
Correct Configuration (lambda.tf line 184):
resource "aws_lambda_function" "lessons_handler" {
handler = "functions/lessons/src/index.handler" # ✅ CORRECT - Full path
# ...
}
Test Suite Implementation
Test Coverage
The test suite validates 5 Lambda functions with 34 comprehensive tests:
Lambda Functions Tested
courses_handlerlessons_handlerenrollments_handlerprogress_handleranalytics_handler
Test Categories
1. Terraform Configuration Parsing (3 tests)
- ✅ Successfully parses lambda.tf file
- ✅ Finds all expected Lambda functions
- ✅ Extracts handler configuration for each Lambda
2. Handler Path Format Validation (3 tests)
- ✅ Validates handler format (module.function)
- ✅ Verifies handler paths match expected structure
- ✅ Ensures no old incorrect handler format exists
3. Zip File Structure Validation (3 tests)
- ✅ Verifies zip files exist at specified paths
- ✅ Confirms handler files exist inside zip archives
- ✅ Matches handler module path to actual zip structure
4. Handler Configuration Consistency (2 tests)
- ✅ Ensures consistent handler paths for similar functions
- ✅ Validates zip paths align with handler paths
5. Specific Lambda Function Validations (20 tests)
- ✅ 4 tests per Lambda function:
- Defined in Terraform configuration
- Correct handler path
- Correct zip file path
- Handler file exists inside zip
6. Regression Test: Original Bug Prevention (3 tests)
- ✅ Never allows
handler = "index.handler" - ✅ Never allows handler path without directory structure
- ✅ Prevents mismatches between handler and zip contents
How the Tests Work
1. Terraform Parsing
The test parses infrastructure/terraform/lambda.tf line-by-line using a state machine approach:
// Extract Lambda configuration
{
resourceName: "courses_handler",
functionName: "courses",
handler: "functions/courses/src/index.handler",
zipPath: "backend/functions/courses/dist/index.zip"
}
2. Handler Validation
For each Lambda function:
// Parse handler
"functions/courses/src/index.handler"
↓
{ modulePath: "functions/courses/src/index", handlerName: "handler" }
↓
expectedFilePath: "functions/courses/src/index.js"
3. Zip File Verification
# Check if file exists in zip
unzip -l backend/functions/courses/dist/index.zip | grep "functions/courses/src/index.js"
4. Validation
- ✅ File found → Test passes
- ❌ File not found → Test fails with detailed error message
Expected Structure
All regular Lambda functions follow this pattern:
resource "aws_lambda_function" "{name}_handler" {
filename = "${path.module}/../../backend/functions/{name}/dist/index.zip"
handler = "functions/{name}/src/index.handler"
# ...
}
Inside the zip file:
functions/{name}/src/index.js # Handler file
functions/{name}/src/index.d.ts # TypeScript definitions
functions/{name}/src/index.js.map # Source map
shared/ # Shared utilities
node_modules/ # Dependencies
Test Results
Initial Test Run (2025-12-04)
PASS tests/infrastructure/lambda-handler-config.test.ts
Lambda Handler Configuration Validation
Terraform Configuration Parsing
✓ should successfully parse lambda.tf file (1 ms)
✓ should find all expected Lambda functions
✓ should extract handler configuration for each Lambda (1 ms)
Handler Path Format Validation
✓ should have valid handler format (module.function) (1 ms)
✓ should have handler paths that match the expected structure
✓ should not have the old incorrect handler format (1 ms)
Zip File Structure Validation
✓ should have zip files that exist at the specified paths
✓ should have handler files that exist inside the zip archives (127 ms)
✓ should match handler module path to actual zip structure (19 ms)
Handler Configuration Consistency
✓ should have consistent handler paths for similar functions
✓ should have zip paths that align with handler paths (1 ms)
Specific Lambda Function Validations
courses_handler
✓ should be defined in Terraform configuration
✓ should have the correct handler path
✓ should have the correct zip file path
✓ should have the handler file inside the zip (20 ms)
lessons_handler
✓ should be defined in Terraform configuration
✓ should have the correct handler path
✓ should have the correct zip file path
✓ should have the handler file inside the zip (20 ms)
enrollments_handler
✓ should be defined in Terraform configuration
✓ should have the correct handler path (1 ms)
✓ should have the correct zip file path
✓ should have the handler file inside the zip (32 ms)
progress_handler
✓ should be defined in Terraform configuration
✓ should have the correct handler path
✓ should have the correct zip file path
✓ should have the handler file inside the zip (32 ms)
analytics_handler
✓ should be defined in Terraform configuration
✓ should have the correct handler path
✓ should have the correct zip file path
✓ should have the handler file inside the zip (20 ms)
Regression Test: Original Bug Prevention
✓ should never have handler = "index.handler" for any Lambda function (1 ms)
✓ should never have a handler path without directory structure
✓ should prevent mismatches between handler and zip contents (123 ms)
Test Suites: 1 passed, 1 total
Tests: 34 passed, 34 total
Snapshots: 0 total
Time: 3.118 s
Result: ✅ All tests passing
Running the Tests
Command Line
# Run all infrastructure tests
npm run test:infrastructure
# Watch mode (auto-rerun on changes)
npm run test:infrastructure:watch
# With coverage report
npm run test:infrastructure:coverage
# Run as part of full test suite
npm test
CI/CD Integration
The tests are automatically run in GitHub Actions workflows:
Before Deployment:
# .github/workflows/deploy-infrastructure.yml
- name: Run Infrastructure Tests
run: npm run test:infrastructure
On Pull Requests:
# .github/workflows/test.yml
- name: Test Infrastructure
run: npm run test:infrastructure
Benefits
1. Prevents Production Errors
- ✅ Catches handler misconfigurations before deployment
- ✅ Prevents 502 errors from incorrect handler paths
- ✅ Validates changes during PR review
2. Regression Prevention
- ✅ Explicit tests for the original bug
- ✅ Prevents reintroduction of known issues
- ✅ Documents the correct configuration
3. Development Confidence
- ✅ Developers can verify configurations locally
- ✅ Automated validation in CI/CD pipeline
- ✅ Clear error messages for troubleshooting
4. Maintainability
- ✅ Self-documenting test descriptions
- ✅ Comprehensive README documentation
- ✅ Easy to extend for new Lambda functions
Common Test Failures and Solutions
“Handler file not found in zip”
Symptom:
✕ should have the handler file inside the zip
Expected: true
Received: false
Cause: Handler configuration doesn’t match zip file structure
Solution:
- Check handler in Terraform:
grep -A 5 "courses_handler" infrastructure/terraform/lambda.tf - Check zip contents:
unzip -l backend/functions/courses/dist/index.zip | grep index.js - Update Terraform handler to match actual structure
“No Lambda configurations found”
Symptom:
Error: No Lambda configurations found in lambda.tf
Cause: Terraform parsing failed
Solution:
- Verify lambda.tf exists:
ls infrastructure/terraform/lambda.tf - Check file syntax is valid:
terraform fmt infrastructure/terraform/lambda.tf - Ensure resource blocks follow expected format
“Zip file not found”
Symptom:
✕ should have zip files that exist at the specified paths
Cause: Lambda functions haven’t been built
Solution:
npm run build:lambda
Adding New Lambda Functions
When adding a new Lambda function:
1. Create the Function
mkdir -p backend/functions/new-function/src
cd backend/functions/new-function
npm init -y
# Create src/index.ts
2. Add to Terraform
# infrastructure/terraform/lambda.tf
resource "aws_lambda_function" "new_function_handler" {
filename = "${path.module}/../../backend/functions/new-function/dist/index.zip"
handler = "functions/new-function/src/index.handler"
# ... rest of configuration
}
3. Update Tests
// tests/infrastructure/lambda-handler-config.test.ts
// In "should find all expected Lambda functions" test:
const expectedFunctions = [
'courses_handler',
'lessons_handler',
'enrollments_handler',
'progress_handler',
'analytics_handler',
'new_function_handler', // ← Add here
];
// In "Specific Lambda Function Validations":
const specificTests = [
// ... existing tests
{
name: 'new-function',
expectedHandler: 'functions/new-function/src/index.handler',
expectedZipPath: 'backend/functions/new-function/dist/index.zip',
},
];
4. Verify
npm run build:lambda
npm run test:infrastructure
Future Enhancements
Potential Improvements
- AI Generation Handlers: Extend tests to validate AI generation Lambda functions
- Handler Exports: Verify the handler function is actually exported from the module
- Runtime Validation: Test that the handler has the correct signature
- Dependency Checks: Validate all required dependencies are included in the zip
- Size Validation: Check zip file sizes are within Lambda limits (50MB zipped, 250MB unzipped)
Test Coverage Goals
- Extend to AI generation Lambda functions
- Add tests for Lambda layers
- Validate environment variable configurations
- Test VPC configuration consistency
- Validate IAM role attachments
Related Documentation
- Test Implementation:
/tests/infrastructure/lambda-handler-config.test.ts - Test README:
/tests/infrastructure/README.md - Terraform Config:
/infrastructure/terraform/lambda.tf - Build Script:
/scripts/deployment/build-lambda.sh - Lambda Deployment Tests:
/tests/workflows/lambda-deployment.test.ts
Conclusion
This test suite provides comprehensive validation of Lambda handler configurations, preventing critical production errors and ensuring consistency across all Lambda functions. The tests are:
- ✅ Comprehensive: 34 tests covering all aspects of handler configuration
- ✅ Reliable: Automated validation in CI/CD pipeline
- ✅ Maintainable: Clear documentation and easy to extend
- ✅ Effective: Catches configuration errors before deployment
The implementation successfully prevents the recurrence of the original bug while providing a foundation for ongoing infrastructure validation.
Questions or Issues?
For questions about these tests:
- Review this documentation
- Check
/tests/infrastructure/README.md - Review test file comments
- Open a GitHub issue with
infrastructureandtestinglabels
Last Updated: 2025-12-04 Author: Test Engineer (Claude Code) Test Status: ✅ All 34 tests passing