awsmock

package module
v0.0.0-...-e230160 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 16, 2026 License: Apache-2.0 Imports: 71 Imported by: 0

README

goto - AWS Mock Services for Go

CI Go Reference Go Report Card License

goto is a pure-Go library that mocks AWS services for testing. It starts an in-memory HTTP server that emulates real AWS API endpoints, so you can test code that uses the AWS SDK for Go v2 without making any real API calls.

Inspired by moto — the popular Python AWS mock library — goto brings the same idea to Go with idiomatic APIs and zero external service dependencies.

Features

  • Zero configurationawsmock.Start(t) is all you need
  • Automatic cleanup — the mock server stops when the test ends
  • Thread-safe — safe for parallel tests
  • Pure Go — no Python, no Docker, no external processes
  • AWS SDK v2 — works with github.com/aws/aws-sdk-go-v2
  • 62 services — broad coverage of the most commonly used AWS services

Supported Services

Service Operations
S3 CreateBucket, DeleteBucket, ListBuckets, HeadBucket, PutObject, GetObject, HeadObject, DeleteObject, ListObjectsV2, CopyObject
SQS CreateQueue, DeleteQueue, ListQueues, GetQueueUrl, GetQueueAttributes, SetQueueAttributes, SendMessage, ReceiveMessage, DeleteMessage, PurgeQueue
STS GetCallerIdentity, AssumeRole, GetSessionToken
DynamoDB CreateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, Query, Scan
SNS CreateTopic, DeleteTopic, ListTopics, Subscribe, Unsubscribe, ListSubscriptions, Publish
Secrets Manager CreateSecret, GetSecretValue, PutSecretValue, DeleteSecret, ListSecrets, DescribeSecret, UpdateSecret
Lambda CreateFunction, GetFunction, DeleteFunction, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration
CloudWatch Logs CreateLogGroup, DeleteLogGroup, DescribeLogGroups, CreateLogStream, DeleteLogStream, DescribeLogStreams, PutLogEvents, GetLogEvents, FilterLogEvents
IAM CreateUser, GetUser, DeleteUser, ListUsers, CreateRole, GetRole, DeleteRole, ListRoles, CreatePolicy, GetPolicy, DeletePolicy, ListPolicies, AttachRolePolicy, DetachRolePolicy
EC2 RunInstances, DescribeInstances, TerminateInstances, CreateVpc, DescribeVpcs, DeleteVpc, CreateSecurityGroup, DescribeSecurityGroups, DeleteSecurityGroup, CreateSubnet, DescribeSubnets, DeleteSubnet
Kinesis CreateStream, DeleteStream, DescribeStream, ListStreams, PutRecord, GetRecords, GetShardIterator
EventBridge CreateEventBus, DeleteEventBus, ListEventBuses, PutRule, DeleteRule, ListRules, PutTargets, RemoveTargets, ListTargetsByRule, PutEvents
SSM Parameter Store PutParameter, GetParameter, GetParameters, DeleteParameter, DescribeParameters, GetParametersByPath
KMS CreateKey, DescribeKey, ListKeys, Encrypt, Decrypt, GenerateDataKey, CreateAlias, ListAliases, DeleteAlias, ScheduleKeyDeletion
CloudFormation CreateStack, DeleteStack, DescribeStacks, ListStacks, UpdateStack
ECR CreateRepository, DeleteRepository, DescribeRepositories, ListImages, PutImage, BatchGetImage, GetAuthorizationToken
Route 53 CreateHostedZone, GetHostedZone, DeleteHostedZone, ListHostedZones, ChangeResourceRecordSets, ListResourceRecordSets
ECS CreateCluster, DeleteCluster, DescribeClusters, ListClusters, RegisterTaskDefinition, DeregisterTaskDefinition, ListTaskDefinitions, RunTask, StopTask, ListTasks, DescribeTasks, CreateService, DeleteService, UpdateService, ListServices, DescribeServices
ELBv2 CreateLoadBalancer, DeleteLoadBalancer, DescribeLoadBalancers, CreateTargetGroup, DeleteTargetGroup, DescribeTargetGroups, RegisterTargets, DeregisterTargets, DescribeTargetHealth, CreateListener, DeleteListener, DescribeListeners
RDS CreateDBInstance, DeleteDBInstance, DescribeDBInstances, ModifyDBInstance, CreateDBCluster, DeleteDBCluster, DescribeDBClusters
CloudWatch PutMetricData, GetMetricData, ListMetrics, PutMetricAlarm, DescribeAlarms, DeleteAlarms
Step Functions CreateStateMachine, DeleteStateMachine, DescribeStateMachine, ListStateMachines, StartExecution, DescribeExecution, ListExecutions, StopExecution
ACM RequestCertificate, DescribeCertificate, ListCertificates, DeleteCertificate
SES v2 CreateEmailIdentity, GetEmailIdentity, ListEmailIdentities, SendEmail, DeleteEmailIdentity
Cognito Identity Provider CreateUserPool, DescribeUserPool, DeleteUserPool, ListUserPools, CreateUserPoolClient, AdminCreateUser, AdminGetUser, AdminDeleteUser, ListUsers
API Gateway V2 CreateApi, GetApi, DeleteApi, GetApis, CreateStage, GetStages, DeleteStage, CreateRoute, GetRoutes, DeleteRoute
CloudFront CreateDistribution, GetDistribution, DeleteDistribution, ListDistributions, UpdateDistribution
EKS CreateCluster, DescribeCluster, DeleteCluster, ListClusters, CreateNodegroup, DescribeNodegroup, DeleteNodegroup, ListNodegroups
ElastiCache CreateCacheCluster, DeleteCacheCluster, DescribeCacheClusters, ModifyCacheCluster, CreateReplicationGroup, DeleteReplicationGroup, DescribeReplicationGroups
Firehose CreateDeliveryStream, DeleteDeliveryStream, DescribeDeliveryStream, ListDeliveryStreams, PutRecord
Athena StartQueryExecution, GetQueryExecution, GetQueryResults, ListQueryExecutions, CreateWorkGroup, GetWorkGroup, DeleteWorkGroup, ListWorkGroups
Glue CreateDatabase, GetDatabase, DeleteDatabase, GetDatabases, CreateTable, GetTable, DeleteTable, GetTables, CreateCrawler, GetCrawler, DeleteCrawler, StartCrawler, ListCrawlers
Auto Scaling CreateAutoScalingGroup, DescribeAutoScalingGroups, DeleteAutoScalingGroup, UpdateAutoScalingGroup, CreateLaunchConfiguration, DescribeLaunchConfigurations, DeleteLaunchConfiguration, SetDesiredCapacity
API Gateway CreateRestApi, GetRestApi, DeleteRestApi, GetRestApis, CreateResource, GetResources, PutMethod, PutIntegration
Cognito Identity CreateIdentityPool, DescribeIdentityPool, DeleteIdentityPool, ListIdentityPools, UpdateIdentityPool
Organizations CreateOrganization, DescribeOrganization, ListAccounts, CreateAccount, DescribeAccount, CreateOrganizationalUnit, ListOrganizationalUnitsForParent
DynamoDB Streams ListStreams, DescribeStream, GetShardIterator, GetRecords
EFS CreateFileSystem, DescribeFileSystems, DeleteFileSystem, CreateMountTarget, DescribeMountTargets, DeleteMountTarget
Batch CreateComputeEnvironment, DescribeComputeEnvironments, DeleteComputeEnvironment, CreateJobQueue, DescribeJobQueues, DeleteJobQueue, SubmitJob, DescribeJobs
CodeBuild CreateProject, BatchGetProjects, ListProjects, DeleteProject, StartBuild, BatchGetBuilds
CodePipeline CreatePipeline, GetPipeline, DeletePipeline, ListPipelines, UpdatePipeline
CloudTrail CreateTrail, GetTrail, DeleteTrail, DescribeTrails, StartLogging, StopLogging, GetTrailStatus, LookupEvents
Config PutConfigRule, DescribeConfigRules, DeleteConfigRule, PutConfigurationRecorder, DescribeConfigurationRecorders, PutDeliveryChannel
WAF v2 CreateWebACL, GetWebACL, DeleteWebACL, ListWebACLs, UpdateWebACL, CreateIPSet, GetIPSet, DeleteIPSet, ListIPSets
Redshift CreateCluster, DescribeClusters, DeleteCluster, ModifyCluster
EMR RunJobFlow, DescribeCluster, ListClusters, TerminateJobFlows, AddJobFlowSteps, ListSteps
Backup CreateBackupVault, DeleteBackupVault, ListBackupVaults, DescribeBackupVault, CreateBackupPlan, GetBackupPlan, DeleteBackupPlan
EventBridge Scheduler CreateSchedule, GetSchedule, DeleteSchedule, ListSchedules, UpdateSchedule
X-Ray PutTraceSegments, GetTraceSummaries, BatchGetTraces, CreateGroup, GetGroup, DeleteGroup, GetGroups
OpenSearch CreateDomain, DescribeDomain, DeleteDomain, ListDomainNames, UpdateDomainConfig
Service Discovery CreatePrivateDnsNamespace, CreateService, GetService, DeleteService, ListServices, RegisterInstance, DeregisterInstance, ListInstances
Transfer Family CreateServer, DescribeServer, DeleteServer, ListServers, CreateUser, DescribeUser, DeleteUser
Application Auto Scaling RegisterScalableTarget, DescribeScalableTargets, DeregisterScalableTarget, PutScalingPolicy, DescribeScalingPolicies, DeleteScalingPolicy
Resource Groups Tagging API TagResources, UntagResources, GetResources, GetTagKeys, GetTagValues
SSO Admin CreatePermissionSet, DescribePermissionSet, DeletePermissionSet, ListPermissionSets, CreateAccountAssignment, ListAccountAssignments
AppSync CreateGraphqlApi, GetGraphqlApi, DeleteGraphqlApi, ListGraphqlApis, CreateDataSource, GetDataSource, DeleteDataSource
MSK (Kafka) CreateCluster, DescribeCluster, DeleteCluster, ListClusters, UpdateBrokerCount
Neptune CreateDBCluster, DescribeDBClusters, DeleteDBCluster, ModifyDBCluster, CreateDBInstance, DescribeDBInstances, DeleteDBInstance
GuardDuty CreateDetector, GetDetector, DeleteDetector, ListDetectors, UpdateDetector
Amazon MQ CreateBroker, DescribeBroker, DeleteBroker, ListBrokers, UpdateBroker
DAX CreateCluster, DescribeClusters, DeleteCluster, ListTags, CreateSubnetGroup, DescribeSubnetGroups, DeleteSubnetGroup
FSx CreateFileSystem, DescribeFileSystems, DeleteFileSystem, UpdateFileSystem, TagResource

Installation

go get github.com/riyanimam/goto

Requires Go 1.22 or later.

Quick Start

package myapp_test

import (
    "context"
    "io"
    "strings"
    "testing"

    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/service/s3"

    awsmock "github.com/riyanimam/goto"
)

func TestUploadToS3(t *testing.T) {
    // Start a mock AWS server — automatically stops when the test ends.
    mock := awsmock.Start(t)

    // Get an AWS config that routes all requests to the mock server.
    cfg, err := mock.AWSConfig(context.Background())
    if err != nil {
        t.Fatal(err)
    }

    // Create an S3 client using path-style addressing.
    client := s3.NewFromConfig(cfg, func(o *s3.Options) {
        o.UsePathStyle = true
    })

    ctx := context.Background()

    // Create a bucket.
    _, err = client.CreateBucket(ctx, &s3.CreateBucketInput{
        Bucket: aws.String("my-bucket"),
    })
    if err != nil {
        t.Fatal(err)
    }

    // Upload an object.
    _, err = client.PutObject(ctx, &s3.PutObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String("hello.txt"),
        Body:   strings.NewReader("Hello, World!"),
    })
    if err != nil {
        t.Fatal(err)
    }

    // Read it back.
    resp, err := client.GetObject(ctx, &s3.GetObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String("hello.txt"),
    })
    if err != nil {
        t.Fatal(err)
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    if string(body) != "Hello, World!" {
        t.Errorf("got %q, want %q", body, "Hello, World!")
    }
}

How It Works

  1. awsmock.Start(t) starts an httptest.Server that accepts all AWS SDK requests.
  2. mock.AWSConfig(ctx) returns an aws.Config with:
    • BaseEndpoint pointing to the mock server
    • Static test credentials (AKIAIOSFODNN7EXAMPLE)
    • Region set to us-east-1
  3. You pass this config to any AWS SDK v2 client (s3.NewFromConfig(cfg), etc.).
  4. The mock server routes each request to the correct service handler based on the Authorization header credential scope or the X-Amz-Target header.
  5. Each service stores state in memory (maps, slices) with mutex-based thread safety.
  6. When your test finishes, t.Cleanup automatically shuts down the server.

Usage Examples

DynamoDB
func TestDynamoDB(t *testing.T) {
    mock := awsmock.Start(t)
    cfg, _ := mock.AWSConfig(context.Background())
    client := dynamodb.NewFromConfig(cfg)
    ctx := context.Background()

    // Create table.
    client.CreateTable(ctx, &dynamodb.CreateTableInput{
        TableName: aws.String("users"),
        KeySchema: []types.KeySchemaElement{
            {AttributeName: aws.String("id"), KeyType: types.KeyTypeHash},
        },
        AttributeDefinitions: []types.AttributeDefinition{
            {AttributeName: aws.String("id"), AttributeType: types.ScalarAttributeTypeS},
        },
        BillingMode: types.BillingModePayPerRequest,
    })

    // Put and get items.
    client.PutItem(ctx, &dynamodb.PutItemInput{
        TableName: aws.String("users"),
        Item: map[string]types.AttributeValue{
            "id":   &types.AttributeValueMemberS{Value: "1"},
            "name": &types.AttributeValueMemberS{Value: "Alice"},
        },
    })
}
Lambda
func TestLambda(t *testing.T) {
    mock := awsmock.Start(t)
    cfg, _ := mock.AWSConfig(context.Background())
    client := lambda.NewFromConfig(cfg)
    ctx := context.Background()

    // Create function.
    client.CreateFunction(ctx, &lambda.CreateFunctionInput{
        FunctionName: aws.String("my-handler"),
        Runtime:      types.RuntimePython312,
        Role:         aws.String("arn:aws:iam::123456789012:role/lambda-role"),
        Handler:      aws.String("index.handler"),
        Code:         &types.FunctionCode{ZipFile: []byte("fake")},
    })

    // Invoke returns the payload you send (echo behavior).
    resp, _ := client.Invoke(ctx, &lambda.InvokeInput{
        FunctionName: aws.String("my-handler"),
        Payload:      []byte(`{"key":"value"}`),
    })
    // resp.Payload == []byte(`{"key":"value"}`)
}
IAM
func TestIAM(t *testing.T) {
    mock := awsmock.Start(t)
    cfg, _ := mock.AWSConfig(context.Background())
    client := iam.NewFromConfig(cfg)
    ctx := context.Background()

    // Create role.
    client.CreateRole(ctx, &iam.CreateRoleInput{
        RoleName:                 aws.String("my-role"),
        AssumeRolePolicyDocument: aws.String(`{"Version":"2012-10-17","Statement":[]}`),
    })

    // Create and attach policy.
    policyResp, _ := client.CreatePolicy(ctx, &iam.CreatePolicyInput{
        PolicyName:     aws.String("my-policy"),
        PolicyDocument: aws.String(`{"Version":"2012-10-17","Statement":[]}`),
    })
    client.AttachRolePolicy(ctx, &iam.AttachRolePolicyInput{
        RoleName:  aws.String("my-role"),
        PolicyArn: policyResp.Policy.Arn,
    })
}
EC2
func TestEC2(t *testing.T) {
    mock := awsmock.Start(t)
    cfg, _ := mock.AWSConfig(context.Background())
    client := ec2.NewFromConfig(cfg)
    ctx := context.Background()

    // Create VPC + run instances.
    vpcResp, _ := client.CreateVpc(ctx, &ec2.CreateVpcInput{
        CidrBlock: aws.String("10.0.0.0/16"),
    })
    runResp, _ := client.RunInstances(ctx, &ec2.RunInstancesInput{
        ImageId:      aws.String("ami-12345678"),
        InstanceType: "t2.micro",
        MinCount:     aws.Int32(1),
        MaxCount:     aws.Int32(1),
    })

    // Terminate when done.
    client.TerminateInstances(ctx, &ec2.TerminateInstancesInput{
        InstanceIds: []string{*runResp.Instances[0].InstanceId},
    })
    client.DeleteVpc(ctx, &ec2.DeleteVpcInput{VpcId: vpcResp.Vpc.VpcId})
}
SSM Parameter Store
func TestSSM(t *testing.T) {
    mock := awsmock.Start(t)
    cfg, _ := mock.AWSConfig(context.Background())
    client := ssm.NewFromConfig(cfg)
    ctx := context.Background()

    // Store and retrieve configuration.
    client.PutParameter(ctx, &ssm.PutParameterInput{
        Name:  aws.String("/app/db/host"),
        Value: aws.String("localhost"),
        Type:  types.ParameterTypeString,
    })

    resp, _ := client.GetParameter(ctx, &ssm.GetParameterInput{
        Name: aws.String("/app/db/host"),
    })
    // *resp.Parameter.Value == "localhost"
}
KMS
func TestKMS(t *testing.T) {
    mock := awsmock.Start(t)
    cfg, _ := mock.AWSConfig(context.Background())
    client := kms.NewFromConfig(cfg)
    ctx := context.Background()

    // Create a key and encrypt/decrypt.
    keyResp, _ := client.CreateKey(ctx, &kms.CreateKeyInput{
        Description: aws.String("test key"),
    })

    encResp, _ := client.Encrypt(ctx, &kms.EncryptInput{
        KeyId:     keyResp.KeyMetadata.KeyId,
        Plaintext: []byte("secret"),
    })

    decResp, _ := client.Decrypt(ctx, &kms.DecryptInput{
        CiphertextBlob: encResp.CiphertextBlob,
    })
    // string(decResp.Plaintext) == "secret"
}
SQS
func TestSendAndReceive(t *testing.T) {
    mock := awsmock.Start(t)

    cfg, err := mock.AWSConfig(context.Background())
    if err != nil {
        t.Fatal(err)
    }

    client := sqs.NewFromConfig(cfg)
    ctx := context.Background()

    // Create a queue.
    createResp, _ := client.CreateQueue(ctx, &sqs.CreateQueueInput{
        QueueName: aws.String("my-queue"),
    })

    // Send a message.
    client.SendMessage(ctx, &sqs.SendMessageInput{
        QueueUrl:    createResp.QueueUrl,
        MessageBody: aws.String(`{"event": "order.created"}`),
    })

    // Receive the message.
    recvResp, _ := client.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{
        QueueUrl: createResp.QueueUrl,
    })

    if len(recvResp.Messages) != 1 {
        t.Fatalf("expected 1 message, got %d", len(recvResp.Messages))
    }
}
STS
func TestCallerIdentity(t *testing.T) {
    mock := awsmock.Start(t)

    cfg, err := mock.AWSConfig(context.Background())
    if err != nil {
        t.Fatal(err)
    }

    client := sts.NewFromConfig(cfg)
    resp, err := client.GetCallerIdentity(context.Background(), &sts.GetCallerIdentityInput{})
    if err != nil {
        t.Fatal(err)
    }

    // Mock account ID is always "123456789012".
    if *resp.Account != "123456789012" {
        t.Errorf("unexpected account: %s", *resp.Account)
    }
}

How to Use This Package in Your Project

Step 1: Add the dependency
go get github.com/riyanimam/goto
Step 2: Import and start in your test
import awsmock "github.com/riyanimam/goto"

func TestMyFunction(t *testing.T) {
    mock := awsmock.Start(t)
    cfg, _ := mock.AWSConfig(context.Background())
    // Pass cfg to your code that creates AWS clients
}
Step 3: Refactor your production code to accept aws.Config

The key design pattern is dependency injection of the AWS config. Instead of creating AWS clients with hardcoded configs, pass aws.Config as a parameter:

// ❌ Hard to test
func ProcessOrders() {
    cfg, _ := config.LoadDefaultConfig(context.Background())
    client := sqs.NewFromConfig(cfg)
    // ...
}

// ✅ Testable — inject the config
func ProcessOrders(cfg aws.Config) {
    client := sqs.NewFromConfig(cfg)
    // ...
}

// In tests:
func TestProcessOrders(t *testing.T) {
    mock := awsmock.Start(t)
    cfg, _ := mock.AWSConfig(context.Background())
    ProcessOrders(cfg) // Uses mock server
}

// In production:
func main() {
    cfg, _ := config.LoadDefaultConfig(context.Background())
    ProcessOrders(cfg) // Uses real AWS
}
Step 4: Reset state between subtests if needed
func TestMultipleScenarios(t *testing.T) {
    mock := awsmock.Start(t)

    t.Run("scenario1", func(t *testing.T) {
        // ... create resources ...
    })

    mock.Reset() // Clear all service state

    t.Run("scenario2", func(t *testing.T) {
        // Fresh state, no leftover resources
    })
}

Adding Custom Services

You can implement the Service interface to add support for additional AWS services:

type Service interface {
    Name() string           // AWS service name (e.g., "dynamodb")
    Handler() http.Handler  // HTTP handler for the service
    Reset()                 // Clears all in-memory state
}

Register your service when starting the mock:

mock := awsmock.Start(t, awsmock.WithService(myCustomService))

Architecture

┌──────────────────────────────────┐
│         Your Test Code           │
│   client := s3.NewFromConfig()   │
└──────────────┬───────────────────┘
               │ HTTP request
┌──────────────▼───────────────────┐
│         MockServer               │
│   net/http/httptest.Server       │
│   Routes by Authorization header │
│   or X-Amz-Target header        │
└──────────────┬───────────────────┘
               │
┌──────────────▼───────────────────┐
│       Service Handlers           │
│   S3, SQS, STS, DynamoDB, SNS,  │
│   Secrets Manager, Lambda, IAM,  │
│   CloudWatch Logs, EC2, Kinesis, │
│   EventBridge, SSM, KMS, ECR,    │
│   CloudFormation, Route 53, ECS, │
│   ELBv2, RDS, CloudWatch, ACM,   │
│   Step Functions, SES, Cognito,  │
│   API Gateway, CloudFront, EKS,  │
│   ElastiCache, Firehose, Athena, │
│   Glue, Auto Scaling, Batch,     │
│   CodeBuild, CodePipeline, EMR,  │
│   CloudTrail, Config, WAF v2,    │
│   Redshift, Backup, Scheduler,   │
│   X-Ray, OpenSearch, EFS,        │
│   Organizations, DynamoDB Streams,│
│   Service Discovery, Transfer    │
│   (in-memory, thread-safe)       │
└──────────────────────────────────┘

Best Practices & Recommendations

1. Use t.Parallel() for Independent Tests

Each call to awsmock.Start(t) creates an isolated mock server. Tests using separate instances can safely run in parallel:

func TestFeatureA(t *testing.T) {
    t.Parallel()
    mock := awsmock.Start(t)
    // ...
}
2. Use Dependency Injection

Design your production code to accept an aws.Config so the mock can be injected:

// Production code
func NewService(cfg aws.Config) *MyService {
    return &MyService{s3: s3.NewFromConfig(cfg)}
}

// Test code
func TestMyService(t *testing.T) {
    mock := awsmock.Start(t)
    cfg, _ := mock.AWSConfig(context.Background())
    svc := NewService(cfg) // Uses mock instead of real AWS
}
3. Test Error Paths

Mock services return realistic AWS errors. Test that your code handles them:

// Attempt to get a non-existent resource
_, err := client.GetFunction(ctx, &lambda.GetFunctionInput{
    FunctionName: aws.String("does-not-exist"),
})
// err will be a ResourceNotFoundException — test your error handling!
4. Reset State Between Subtests

Use mock.Reset() to clear all service state without restarting the server:

func TestCRUD(t *testing.T) {
    mock := awsmock.Start(t)
    // ... create resources ...

    mock.Reset() // Clears all data
    // ... verify clean state ...
}
5. Keep Mock Tests Fast
  • Avoid time.Sleep — mock responses are immediate
  • Use -race flag in CI to catch concurrency issues
  • Run with -count=1 to avoid test caching
6. Extend with Custom Services

For services not yet supported, implement the awsmock.Service interface:

type Service interface {
    Name() string
    Handler() http.Handler
    Reset()
}

And register it with awsmock.WithService(myService).

Development

# Run tests
make test

# Run tests with race detection
make test-race

# Run linter
make lint

# Run all checks
make ci

Contributing

See CONTRIBUTING.md for guidelines.

License

Apache License 2.0 — see LICENSE for details.

Documentation

Overview

Package awsmock provides an in-memory mock of AWS services for testing.

awsmock starts a local HTTP server that emulates AWS service APIs, allowing you to test code that uses the AWS SDK for Go v2 without making real API calls.

Quick Start

func TestMyFunction(t *testing.T) {
    mock := awsmock.Start(t)

    cfg := mock.AWSConfig(context.Background())
    client := s3.NewFromConfig(cfg)

    _, err := client.CreateBucket(ctx, &s3.CreateBucketInput{
        Bucket: aws.String("my-bucket"),
    })
    if err != nil {
        t.Fatal(err)
    }
}

Supported Services

awsmock currently supports the following AWS services:

  • S3 (Simple Storage Service)
  • SQS (Simple Queue Service)
  • STS (Security Token Service)
  • DynamoDB
  • SNS (Simple Notification Service)
  • Secrets Manager
  • Lambda
  • CloudWatch Logs
  • IAM (Identity and Access Management)
  • EC2 (Elastic Compute Cloud)
  • Kinesis Data Streams
  • EventBridge
  • SSM Parameter Store
  • KMS (Key Management Service)
  • CloudFormation
  • ECR (Elastic Container Registry)
  • Route 53 (DNS)
  • ECS (Elastic Container Service)
  • ELBv2 (Elastic Load Balancing v2)
  • RDS (Relational Database Service)
  • CloudWatch (Metrics and Alarms)
  • Step Functions
  • ACM (Certificate Manager)
  • SES v2 (Simple Email Service)
  • Cognito Identity Provider
  • API Gateway V2 (HTTP/WebSocket APIs)
  • CloudFront (CDN)
  • EKS (Elastic Kubernetes Service)
  • ElastiCache (Redis/Memcached)
  • Firehose (Kinesis Data Firehose)
  • Athena (SQL Query Service)
  • Glue (ETL/Data Catalog)
  • Auto Scaling
  • API Gateway (REST APIs)
  • Cognito Identity (Federated Identities)
  • Organizations
  • DynamoDB Streams
  • EFS (Elastic File System)
  • Batch
  • CodeBuild
  • CodePipeline
  • CloudTrail
  • Config
  • WAF v2 (Web Application Firewall)
  • Redshift
  • EMR (Elastic MapReduce)
  • Backup
  • EventBridge Scheduler
  • X-Ray
  • OpenSearch
  • Service Discovery (Cloud Map)
  • Transfer Family (SFTP/FTPS/FTP)
  • Application Auto Scaling
  • Resource Groups Tagging API
  • SSO Admin (IAM Identity Center)
  • AppSync (GraphQL)
  • MSK (Managed Streaming for Kafka)
  • Neptune (Graph Database)
  • GuardDuty (Threat Detection)
  • Amazon MQ (Message Broker)
  • DAX (DynamoDB Accelerator)
  • FSx (Managed File Systems)

Additional services can be added by implementing the Service interface.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type MockServer

type MockServer struct {
	// contains filtered or unexported fields
}

MockServer is a mock AWS server that routes requests to service handlers.

func Start

func Start(t testing.TB, opts ...Option) *MockServer

Start creates and starts a new mock AWS server with all built-in services. The server is automatically stopped when the test completes.

func (*MockServer) AWSConfig

func (m *MockServer) AWSConfig(ctx context.Context) (aws.Config, error)

AWSConfig returns an aws.Config pre-configured to route all requests to the mock server with static test credentials.

func (*MockServer) Register

func (m *MockServer) Register(svc Service)

Register adds a service to the mock server. If a service with the same name already exists, it is replaced.

func (*MockServer) Reset

func (m *MockServer) Reset()

Reset clears all in-memory state across all registered services.

func (*MockServer) ServeHTTP

func (m *MockServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP routes incoming requests to the appropriate service handler. It determines the target service by inspecting the Authorization header's credential scope (e.g., ".../s3/aws4_request").

func (*MockServer) Stop

func (m *MockServer) Stop()

Stop shuts down the mock server and resets all services.

func (*MockServer) URL

func (m *MockServer) URL() string

URL returns the base URL of the mock server.

type Option

type Option func(*serverConfig)

Option configures a MockServer.

func WithService

func WithService(svc Service) Option

WithService registers an additional Service with the mock server. Use this to add custom service implementations or override built-in ones.

type Service

type Service interface {
	// Name returns the AWS service identifier (e.g., "s3", "sqs", "sts").
	Name() string

	// Handler returns the HTTP handler for this service.
	Handler() http.Handler

	// Reset clears all in-memory state for the service.
	Reset()
}

Service represents an AWS service mock that can handle HTTP requests.

Directories

Path Synopsis
internal
mockhelpers
Package mockhelpers provides shared helper functions for mock AWS services.
Package mockhelpers provides shared helper functions for mock AWS services.
services
acm
Package acm provides a mock implementation of AWS Certificate Manager.
Package acm provides a mock implementation of AWS Certificate Manager.
apigateway
Package apigateway provides a mock implementation of AWS API Gateway v1 (REST APIs).
Package apigateway provides a mock implementation of AWS API Gateway v1 (REST APIs).
apigatewayv2
Package apigatewayv2 provides a mock implementation of AWS API Gateway V2 (HTTP/WebSocket APIs).
Package apigatewayv2 provides a mock implementation of AWS API Gateway V2 (HTTP/WebSocket APIs).
applicationautoscaling
Package applicationautoscaling provides a mock implementation of AWS Application Auto Scaling.
Package applicationautoscaling provides a mock implementation of AWS Application Auto Scaling.
appsync
Package appsync provides a mock implementation of AWS AppSync.
Package appsync provides a mock implementation of AWS AppSync.
athena
Package athena provides a mock implementation of AWS Athena.
Package athena provides a mock implementation of AWS Athena.
autoscaling
Package autoscaling provides a mock implementation of AWS Auto Scaling.
Package autoscaling provides a mock implementation of AWS Auto Scaling.
backup
Package backup provides a mock implementation of AWS Backup.
Package backup provides a mock implementation of AWS Backup.
batch
Package batch provides a mock implementation of AWS Batch.
Package batch provides a mock implementation of AWS Batch.
cloudformation
Package cloudformation provides a mock implementation of AWS CloudFormation.
Package cloudformation provides a mock implementation of AWS CloudFormation.
cloudfront
Package cloudfront provides a mock implementation of AWS CloudFront.
Package cloudfront provides a mock implementation of AWS CloudFront.
cloudtrail
Package cloudtrail provides a mock implementation of AWS CloudTrail.
Package cloudtrail provides a mock implementation of AWS CloudTrail.
cloudwatch
Package cloudwatch provides a mock implementation of AWS CloudWatch (metrics).
Package cloudwatch provides a mock implementation of AWS CloudWatch (metrics).
cloudwatchlogs
Package cloudwatchlogs provides a mock implementation of AWS CloudWatch Logs.
Package cloudwatchlogs provides a mock implementation of AWS CloudWatch Logs.
codebuild
Package codebuild provides a mock implementation of AWS CodeBuild.
Package codebuild provides a mock implementation of AWS CodeBuild.
codepipeline
Package codepipeline provides a mock implementation of AWS CodePipeline.
Package codepipeline provides a mock implementation of AWS CodePipeline.
cognitoidentity
Package cognitoidentity provides a mock implementation of AWS Cognito Identity.
Package cognitoidentity provides a mock implementation of AWS Cognito Identity.
cognitoidp
Package cognitoidp provides a mock implementation of AWS Cognito Identity Provider.
Package cognitoidp provides a mock implementation of AWS Cognito Identity Provider.
configservice
Package configservice provides a mock implementation of AWS Config.
Package configservice provides a mock implementation of AWS Config.
dax
Package dax provides a mock implementation of Amazon DAX.
Package dax provides a mock implementation of Amazon DAX.
dynamodb
Package dynamodb provides a mock implementation of AWS DynamoDB.
Package dynamodb provides a mock implementation of AWS DynamoDB.
dynamodbstreams
Package dynamodbstreams provides a mock implementation of AWS DynamoDB Streams.
Package dynamodbstreams provides a mock implementation of AWS DynamoDB Streams.
ec2
Package ec2 provides a mock implementation of AWS Elastic Compute Cloud.
Package ec2 provides a mock implementation of AWS Elastic Compute Cloud.
ecr
Package ecr provides a mock implementation of AWS Elastic Container Registry.
Package ecr provides a mock implementation of AWS Elastic Container Registry.
ecs
Package ecs provides a mock implementation of AWS Elastic Container Service.
Package ecs provides a mock implementation of AWS Elastic Container Service.
efs
Package efs provides a mock implementation of AWS Elastic File System.
Package efs provides a mock implementation of AWS Elastic File System.
eks
Package eks provides a mock implementation of AWS Elastic Kubernetes Service.
Package eks provides a mock implementation of AWS Elastic Kubernetes Service.
elasticache
Package elasticache provides a mock implementation of AWS ElastiCache.
Package elasticache provides a mock implementation of AWS ElastiCache.
elbv2
Package elbv2 provides a mock implementation of AWS Elastic Load Balancing v2.
Package elbv2 provides a mock implementation of AWS Elastic Load Balancing v2.
emr
Package emr provides a mock implementation of AWS EMR (Elastic MapReduce).
Package emr provides a mock implementation of AWS EMR (Elastic MapReduce).
eventbridge
Package eventbridge provides a mock implementation of AWS EventBridge.
Package eventbridge provides a mock implementation of AWS EventBridge.
firehose
Package firehose provides a mock implementation of AWS Kinesis Data Firehose.
Package firehose provides a mock implementation of AWS Kinesis Data Firehose.
fsx
Package fsx provides a mock implementation of AWS FSx.
Package fsx provides a mock implementation of AWS FSx.
glue
Package glue provides a mock implementation of AWS Glue.
Package glue provides a mock implementation of AWS Glue.
guardduty
Package guardduty provides a mock implementation of AWS GuardDuty.
Package guardduty provides a mock implementation of AWS GuardDuty.
iam
Package iam provides a mock implementation of AWS Identity and Access Management.
Package iam provides a mock implementation of AWS Identity and Access Management.
kafka
Package kafka provides a mock implementation of Amazon Managed Streaming for Apache Kafka (MSK).
Package kafka provides a mock implementation of Amazon Managed Streaming for Apache Kafka (MSK).
kinesis
Package kinesis provides a mock implementation of AWS Kinesis Data Streams.
Package kinesis provides a mock implementation of AWS Kinesis Data Streams.
kms
Package kms provides a mock implementation of AWS Key Management Service.
Package kms provides a mock implementation of AWS Key Management Service.
lambda
Package lambda provides a mock implementation of AWS Lambda.
Package lambda provides a mock implementation of AWS Lambda.
mq
Package mq provides a mock implementation of Amazon MQ.
Package mq provides a mock implementation of Amazon MQ.
neptune
Package neptune provides a mock implementation of AWS Neptune.
Package neptune provides a mock implementation of AWS Neptune.
opensearch
Package opensearch provides a mock implementation of Amazon OpenSearch Service.
Package opensearch provides a mock implementation of Amazon OpenSearch Service.
organizations
Package organizations provides a mock implementation of AWS Organizations.
Package organizations provides a mock implementation of AWS Organizations.
rds
Package rds provides a mock implementation of AWS Relational Database Service.
Package rds provides a mock implementation of AWS Relational Database Service.
redshift
Package redshift provides a mock implementation of AWS Redshift.
Package redshift provides a mock implementation of AWS Redshift.
resourcegroupstaggingapi
Package resourcegroupstaggingapi provides a mock implementation of AWS Resource Groups Tagging API.
Package resourcegroupstaggingapi provides a mock implementation of AWS Resource Groups Tagging API.
route53
Package route53 provides a mock implementation of AWS Route 53.
Package route53 provides a mock implementation of AWS Route 53.
s3
Package s3 provides a mock implementation of AWS Simple Storage Service.
Package s3 provides a mock implementation of AWS Simple Storage Service.
scheduler
Package scheduler provides a mock implementation of Amazon EventBridge Scheduler.
Package scheduler provides a mock implementation of Amazon EventBridge Scheduler.
secretsmanager
Package secretsmanager provides a mock implementation of AWS Secrets Manager.
Package secretsmanager provides a mock implementation of AWS Secrets Manager.
servicediscovery
Package servicediscovery provides a mock implementation of AWS Cloud Map (Service Discovery).
Package servicediscovery provides a mock implementation of AWS Cloud Map (Service Discovery).
ses
Package ses provides a mock implementation of AWS Simple Email Service (SES v2).
Package ses provides a mock implementation of AWS Simple Email Service (SES v2).
sns
Package sns provides a mock implementation of AWS Simple Notification Service.
Package sns provides a mock implementation of AWS Simple Notification Service.
sqs
Package sqs provides a mock implementation of AWS Simple Queue Service.
Package sqs provides a mock implementation of AWS Simple Queue Service.
ssm
Package ssm provides a mock implementation of AWS Systems Manager Parameter Store.
Package ssm provides a mock implementation of AWS Systems Manager Parameter Store.
ssoadmin
Package ssoadmin provides a mock implementation of AWS SSO Admin.
Package ssoadmin provides a mock implementation of AWS SSO Admin.
stepfunctions
Package stepfunctions provides a mock implementation of AWS Step Functions.
Package stepfunctions provides a mock implementation of AWS Step Functions.
sts
Package sts provides a mock implementation of AWS Security Token Service.
Package sts provides a mock implementation of AWS Security Token Service.
transfer
Package transfer provides a mock implementation of AWS Transfer Family.
Package transfer provides a mock implementation of AWS Transfer Family.
wafv2
Package wafv2 provides a mock implementation of AWS WAF v2.
Package wafv2 provides a mock implementation of AWS WAF v2.
xray
Package xray provides a mock implementation of AWS X-Ray.
Package xray provides a mock implementation of AWS X-Ray.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL