Skip to content

Instantly share code, notes, and snippets.

@ricfeatherstone
Created January 11, 2022 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricfeatherstone/dd5cee73520fff38607a36ffeb740d8f to your computer and use it in GitHub Desktop.
Save ricfeatherstone/dd5cee73520fff38607a36ffeb740d8f to your computer and use it in GitHub Desktop.
Go test S3 using testcontainers and localstack
package s3
import (
"context"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/magiconair/properties/assert"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
"testing"
)
func TestAccessS3(t *testing.T) {
awsEndpoint := "http://localhost:4566"
awsRegion := "us-east-1"
ctx := context.Background()
req := testcontainers.ContainerRequest{
Image: "localstack/localstack",
ExposedPorts: []string{"4566:4566/tcp"},
WaitingFor: wait.ForLog("Ready"),
}
c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
if err != nil {
t.Error(err)
}
defer func(c testcontainers.Container, ctx context.Context) {
if err := c.Terminate(ctx); err != nil {
fmt.Println(err)
}
}(c, ctx)
optsFunc := func(service, region string, options ...interface{}) (aws.Endpoint, error) {
return aws.Endpoint{
URL: awsEndpoint,
SigningRegion: region,
}, nil
}
customResolver := aws.EndpointResolverWithOptionsFunc(optsFunc)
cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(awsRegion), config.WithEndpointResolverWithOptions(customResolver))
if err != nil {
t.Error(err)
}
client := s3.NewFromConfig(cfg, func(o *s3.Options) {
o.UsePathStyle = true
})
bucketName := "test"
if _, err := client.CreateBucket(ctx, &s3.CreateBucketInput{
Bucket: &bucketName,
}); err != nil {
t.Error(err)
}
list, err := client.ListBuckets(ctx, &s3.ListBucketsInput{})
if err != nil {
t.Error(err)
}
assert.Equal(t, len(list.Buckets), 1)
assert.Equal(t, *list.Buckets[0].Name, bucketName)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment