3.2.2 Integration Tests & Mock APIs

Write Integration Tests and Mock APIs

Mocking AWS Services

# Python — moto library
from moto import mock_aws
import boto3

@mock_aws
def test_dynamodb_put():
    client = boto3.client("dynamodb", region_name="us-east-1")
    client.create_table(
        TableName="test-table",
        KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
        AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
        BillingMode="PAY_PER_REQUEST"
    )
    client.put_item(TableName="test-table", Item={"id": {"S": "123"}})
    response = client.get_item(TableName="test-table", Key={"id": {"S": "123"}})
    assert "Item" in response

Mocking External APIs

from unittest.mock import patch, MagicMock

@patch('handler.requests.get')
def test_external_api(mock_get):
    mock_get.return_value = MagicMock(
        status_code=200,
        json=lambda: {"data": "mocked"}
    )
    result = handler.call_external_api()
    assert result["data"] == "mocked"

LocalStack

  • Local AWS cloud emulator
  • Supports: S3, DynamoDB, SQS, SNS, Lambda, etc.
  • Docker-based, free tier available

Testing Levels

LevelToolSpeed
Unitpytest + moto/mockFast
IntegrationSAM local, LocalStackMedium
E2EDeployed AWS resourcesSlow

Exam Tip: moto = mock AWS services in Python. SAM local = integration testing. Mock external APIs to avoid flaky tests.