Created
January 11, 2022 10:27
-
-
Save ricfeatherstone/dd5cee73520fff38607a36ffeb740d8f to your computer and use it in GitHub Desktop.
Go test S3 using testcontainers and localstack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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