func ExampleCloudFormation_EstimateTemplateCost() { svc := cloudformation.New(nil) params := &cloudformation.EstimateTemplateCostInput{ Parameters: []*cloudformation.Parameter{ { // Required ParameterKey: aws.String("ParameterKey"), ParameterValue: aws.String("ParameterValue"), UsePreviousValue: aws.Boolean(true), }, // More values... }, TemplateBody: aws.String("TemplateBody"), TemplateURL: aws.String("TemplateURL"), } resp, err := svc.EstimateTemplateCost(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { // Generic AWS Error with Code, Message, and original error (if any) fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { // A service error occurred fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } } // Pretty-print the response data. fmt.Println(awsutil.StringValue(resp)) }
func TestInputService9ProtocolTestRecursiveShapesCase6(t *testing.T) { svc := NewInputService9ProtocolTest(nil) svc.Endpoint = "https://test" input := &InputService9TestShapeInputShape{ RecursiveStruct: &InputService9TestShapeRecursiveStructType{ RecursiveMap: map[string]*InputService9TestShapeRecursiveStructType{ "bar": { NoRecurse: aws.String("bar"), }, "foo": { NoRecurse: aws.String("foo"), }, }, }, } req, _ := svc.InputService9TestCaseOperation6Request(input) r := req.HTTPRequest // build request query.Build(req) assert.NoError(t, req.Error) // assert body assert.NotNil(t, r.Body) body, _ := ioutil.ReadAll(r.Body) assert.Equal(t, util.Trim(`Action=OperationName&RecursiveStruct.RecursiveMap.entry.1.key=bar&RecursiveStruct.RecursiveMap.entry.1.value.NoRecurse=bar&RecursiveStruct.RecursiveMap.entry.2.key=foo&RecursiveStruct.RecursiveMap.entry.2.value.NoRecurse=foo&Version=2014-01-01`), util.Trim(string(body))) // assert URL assert.Equal(t, "https://test/", r.URL.String()) // assert headers }
func TestUploadOrderMultiFailureLeaveParts(t *testing.T) { s, ops, _ := loggingSvc() s.Handlers.Send.PushBack(func(r *aws.Request) { switch data := r.Data.(type) { case *s3.UploadPartOutput: if *data.ETag == "ETAG2" { r.HTTPResponse.StatusCode = 400 } } }) mgr := s3manager.NewUploader(&s3manager.UploadOptions{ S3: s, Concurrency: 1, LeavePartsOnError: true, }) _, err := mgr.Upload(&s3manager.UploadInput{ Bucket: aws.String("Bucket"), Key: aws.String("Key"), Body: bytes.NewReader(make([]byte, 1024*1024*12)), }) assert.Error(t, err) assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart"}, *ops) }
func TestInputService3ProtocolTestListTypesCase1(t *testing.T) { svc := NewInputService3ProtocolTest(nil) svc.Endpoint = "https://test" input := &InputService3TestShapeInputShape{ ListArg: []*string{ aws.String("foo"), aws.String("bar"), aws.String("baz"), }, } req, _ := svc.InputService3TestCaseOperation1Request(input) r := req.HTTPRequest // build request query.Build(req) assert.NoError(t, req.Error) // assert body assert.NotNil(t, r.Body) body, _ := ioutil.ReadAll(r.Body) assert.Equal(t, util.Trim(`Action=OperationName&ListArg.member.1=foo&ListArg.member.2=bar&ListArg.member.3=baz&Version=2014-01-01`), util.Trim(string(body))) // assert URL assert.Equal(t, "https://test/", r.URL.String()) // assert headers }
func TestInputService4ProtocolTestFlattenedListCase1(t *testing.T) { svc := NewInputService4ProtocolTest(nil) svc.Endpoint = "https://test" input := &InputService4TestShapeInputShape{ ListArg: []*string{ aws.String("a"), aws.String("b"), aws.String("c"), }, ScalarArg: aws.String("foo"), } req, _ := svc.InputService4TestCaseOperation1Request(input) r := req.HTTPRequest // build request query.Build(req) assert.NoError(t, req.Error) // assert body assert.NotNil(t, r.Body) body, _ := ioutil.ReadAll(r.Body) assert.Equal(t, util.Trim(`Action=OperationName&ListArg.1=a&ListArg.2=b&ListArg.3=c&ScalarArg=foo&Version=2014-01-01`), util.Trim(string(body))) // assert URL assert.Equal(t, "https://test/", r.URL.String()) // assert headers }
func TestInputService6ProtocolTestSerializeMapTypeWithLocationNameCase1(t *testing.T) { svc := NewInputService6ProtocolTest(nil) svc.Endpoint = "https://test" input := &InputService6TestShapeInputShape{ MapArg: map[string]*string{ "key1": aws.String("val1"), "key2": aws.String("val2"), }, } req, _ := svc.InputService6TestCaseOperation1Request(input) r := req.HTTPRequest // build request query.Build(req) assert.NoError(t, req.Error) // assert body assert.NotNil(t, r.Body) body, _ := ioutil.ReadAll(r.Body) assert.Equal(t, util.Trim(`Action=OperationName&MapArg.entry.1.TheKey=key1&MapArg.entry.1.TheValue=val1&MapArg.entry.2.TheKey=key2&MapArg.entry.2.TheValue=val2&Version=2014-01-01`), util.Trim(string(body))) // assert URL assert.Equal(t, "https://test/", r.URL.String()) // assert headers }
func loggingSvc() (*s3.S3, *[]string, *[]interface{}) { var m sync.Mutex partNum := 0 names := []string{} params := []interface{}{} svc := s3.New(nil) svc.Handlers.Unmarshal.Clear() svc.Handlers.UnmarshalMeta.Clear() svc.Handlers.UnmarshalError.Clear() svc.Handlers.Send.Clear() svc.Handlers.Send.PushBack(func(r *aws.Request) { m.Lock() defer m.Unlock() names = append(names, r.Operation.Name) params = append(params, r.Params) r.HTTPResponse = &http.Response{ StatusCode: 200, Body: ioutil.NopCloser(bytes.NewReader([]byte{})), } switch data := r.Data.(type) { case *s3.CreateMultipartUploadOutput: data.UploadID = aws.String("UPLOAD-ID") case *s3.UploadPartOutput: partNum++ data.ETag = aws.String(fmt.Sprintf("ETAG%d", partNum)) case *s3.CompleteMultipartUploadOutput: data.Location = aws.String("https://location") } }) return svc, &names, ¶ms }
func TestInputService1ProtocolTestScalarMembersCase1(t *testing.T) { svc := NewInputService1ProtocolTest(nil) svc.Endpoint = "https://test" input := &InputService1TestShapeInputShape{ Bar: aws.String("val2"), Foo: aws.String("val1"), } req, _ := svc.InputService1TestCaseOperation1Request(input) r := req.HTTPRequest // build request query.Build(req) assert.NoError(t, req.Error) // assert body assert.NotNil(t, r.Body) body, _ := ioutil.ReadAll(r.Body) assert.Equal(t, util.Trim(`Action=OperationName&Bar=val2&Foo=val1&Version=2014-01-01`), util.Trim(string(body))) // assert URL assert.Equal(t, "https://test/", r.URL.String()) // assert headers }
func ExampleCloudFormation_ListStacks() { svc := cloudformation.New(nil) params := &cloudformation.ListStacksInput{ NextToken: aws.String("NextToken"), StackStatusFilter: []*string{ aws.String("StackStatus"), // Required // More values... }, } resp, err := svc.ListStacks(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { // Generic AWS Error with Code, Message, and original error (if any) fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { // A service error occurred fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } } // Pretty-print the response data. fmt.Println(awsutil.StringValue(resp)) }
func ExampleCloudFormation_ValidateTemplate() { svc := cloudformation.New(nil) params := &cloudformation.ValidateTemplateInput{ TemplateBody: aws.String("TemplateBody"), TemplateURL: aws.String("TemplateURL"), } resp, err := svc.ValidateTemplate(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { // Generic AWS Error with Code, Message, and original error (if any) fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { // A service error occurred fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } } // Pretty-print the response data. fmt.Println(awsutil.StringValue(resp)) }
func TestPresignHandler(t *testing.T) { svc := s3.New(nil) req, _ := svc.PutObjectRequest(&s3.PutObjectInput{ Bucket: aws.String("bucket"), Key: aws.String("key"), ContentDisposition: aws.String("a+b c$d"), ACL: aws.String("public-read"), }) req.Time = time.Unix(0, 0) urlstr, err := req.Presign(5 * time.Minute) assert.NoError(t, err) expectedDate := "19700101T000000Z" expectedHeaders := "host;x-amz-acl" expectedSig := "7edcb4e3a1bf12f4989018d75acbe3a7f03df24bd6f3112602d59fc551f0e4e2" expectedCred := "AKID/19700101/mock-region/s3/aws4_request" u, _ := url.Parse(urlstr) urlQ := u.Query() assert.Equal(t, expectedSig, urlQ.Get("X-Amz-Signature")) assert.Equal(t, expectedCred, urlQ.Get("X-Amz-Credential")) assert.Equal(t, expectedHeaders, urlQ.Get("X-Amz-SignedHeaders")) assert.Equal(t, expectedDate, urlQ.Get("X-Amz-Date")) assert.Equal(t, "300", urlQ.Get("X-Amz-Expires")) assert.NotContains(t, urlstr, "+") // + encoded as %20 }
func ExampleCloudFormation_SignalResource() { svc := cloudformation.New(nil) params := &cloudformation.SignalResourceInput{ LogicalResourceID: aws.String("LogicalResourceId"), // Required StackName: aws.String("StackNameOrId"), // Required Status: aws.String("ResourceSignalStatus"), // Required UniqueID: aws.String("ResourceSignalUniqueId"), // Required } resp, err := svc.SignalResource(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { // Generic AWS Error with Code, Message, and original error (if any) fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { // A service error occurred fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } } // Pretty-print the response data. fmt.Println(awsutil.StringValue(resp)) }
func TestDownloadError(t *testing.T) { s, names, _ := dlLoggingSvc([]byte{1, 2, 3}) opts := &s3manager.DownloadOptions{S3: s, PartSize: 1, Concurrency: 1} num := 0 s.Handlers.Send.PushBack(func(r *aws.Request) { num++ if num > 1 { r.HTTPResponse.StatusCode = 400 r.HTTPResponse.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) } }) d := s3manager.NewDownloader(opts) w := newDLWriter(3) n, err := d.Download(w, &s3.GetObjectInput{ Bucket: aws.String("bucket"), Key: aws.String("key"), }) assert.NotNil(t, err) assert.Equal(t, int64(1), n) assert.Equal(t, []string{"GetObject", "GetObject"}, *names) assert.Equal(t, []byte{1, 0, 0}, w.buf) }
func TestMD5InPutBucketPolicy(t *testing.T) { svc := s3.New(nil) req, _ := svc.PutBucketPolicyRequest(&s3.PutBucketPolicyInput{ Bucket: aws.String("bucketname"), Policy: aws.String("{}"), }) assertMD5(t, req) }
func TestMD5InPutBucketCORS(t *testing.T) { svc := s3.New(nil) req, _ := svc.PutBucketCORSRequest(&s3.PutBucketCORSInput{ Bucket: aws.String("bucketname"), CORSConfiguration: &s3.CORSConfiguration{ CORSRules: []*s3.CORSRule{ {AllowedMethods: []*string{aws.String("GET")}}, }, }, }) assertMD5(t, req) }
func TestMD5InPutBucketTagging(t *testing.T) { svc := s3.New(nil) req, _ := svc.PutBucketTaggingRequest(&s3.PutBucketTaggingInput{ Bucket: aws.String("bucketname"), Tagging: &s3.Tagging{ TagSet: []*s3.Tag{ {Key: aws.String("KEY"), Value: aws.String("VALUE")}, }, }, }) assertMD5(t, req) }
func TestMD5InDeleteObjects(t *testing.T) { svc := s3.New(nil) req, _ := svc.DeleteObjectsRequest(&s3.DeleteObjectsInput{ Bucket: aws.String("bucketname"), Delete: &s3.Delete{ Objects: []*s3.ObjectIdentifier{ {Key: aws.String("key")}, }, }, }) assertMD5(t, req) }
func TestUploadOrderReadFail2(t *testing.T) { s, ops, _ := loggingSvc() mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) _, err := mgr.Upload(&s3manager.UploadInput{ Bucket: aws.String("Bucket"), Key: aws.String("Key"), Body: &failreader{times: 2}, }) assert.Equal(t, "ReadRequestBody", err.(awserr.Error).Code()) assert.EqualError(t, err.(awserr.Error).OrigErr(), "random failure") assert.Equal(t, []string{"CreateMultipartUpload", "AbortMultipartUpload"}, *ops) }
// Use DynamoDB methods for simplicity func TestPaginationEachPage(t *testing.T) { db := dynamodb.New(nil) tokens, pages, numPages, gotToEnd := []string{}, []string{}, 0, false reqNum := 0 resps := []*dynamodb.ListTablesOutput{ {TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")}, {TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")}, {TableNames: []*string{aws.String("Table5")}}, } db.Handlers.Send.Clear() // mock sending db.Handlers.Unmarshal.Clear() db.Handlers.UnmarshalMeta.Clear() db.Handlers.ValidateResponse.Clear() db.Handlers.Build.PushBack(func(r *aws.Request) { in := r.Params.(*dynamodb.ListTablesInput) if in == nil { tokens = append(tokens, "") } else if in.ExclusiveStartTableName != nil { tokens = append(tokens, *in.ExclusiveStartTableName) } }) db.Handlers.Unmarshal.PushBack(func(r *aws.Request) { r.Data = resps[reqNum] reqNum++ }) params := &dynamodb.ListTablesInput{Limit: aws.Long(2)} req, _ := db.ListTablesRequest(params) err := req.EachPage(func(p interface{}, last bool) bool { numPages++ for _, t := range p.(*dynamodb.ListTablesOutput).TableNames { pages = append(pages, *t) } if last { if gotToEnd { assert.Fail(t, "last=true happened twice") } gotToEnd = true } return true }) assert.Equal(t, []string{"Table2", "Table4"}, tokens) assert.Equal(t, []string{"Table1", "Table2", "Table3", "Table4", "Table5"}, pages) assert.Equal(t, 3, numPages) assert.True(t, gotToEnd) assert.Nil(t, err) }
func TestUploadOrderSingleBufferedReader(t *testing.T) { s, ops, _ := loggingSvc() mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) resp, err := mgr.Upload(&s3manager.UploadInput{ Bucket: aws.String("Bucket"), Key: aws.String("Key"), Body: &sizedReader{size: 1024 * 1024 * 2}, }) assert.NoError(t, err) assert.Equal(t, []string{"PutObject"}, *ops) assert.NotEqual(t, "", resp.Location) assert.Equal(t, "", resp.UploadID) }
func TestCopySourceSSECustomerKeyOverHTTPError(t *testing.T) { s := s3.New(&aws.Config{DisableSSL: true}) req, _ := s.CopyObjectRequest(&s3.CopyObjectInput{ Bucket: aws.String("bucket"), CopySource: aws.String("bucket/source"), Key: aws.String("dest"), CopySourceSSECustomerKey: aws.String("key"), }) err := req.Build() assert.Error(t, err) assert.Equal(t, "ConfigError", err.(awserr.Error).Code()) assert.Contains(t, err.(awserr.Error).Message(), "cannot send SSE keys over HTTP") }
func TestUploadOrderZero(t *testing.T) { s, ops, args := loggingSvc() mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) resp, err := mgr.Upload(&s3manager.UploadInput{ Bucket: aws.String("Bucket"), Key: aws.String("Key"), Body: bytes.NewReader(make([]byte, 0)), }) assert.NoError(t, err) assert.Equal(t, []string{"PutObject"}, *ops) assert.NotEqual(t, "", resp.Location) assert.Equal(t, "", resp.UploadID) assert.Equal(t, 0, buflen(val((*args)[0], "Body"))) }
func TestNoErrors(t *testing.T) { input := &StructShape{ RequiredList: []*ConditionalStructShape{}, RequiredMap: map[string]*ConditionalStructShape{ "key1": {Name: aws.String("Name")}, "key2": {Name: aws.String("Name")}, }, RequiredBool: aws.Boolean(true), OptionalStruct: &ConditionalStructShape{Name: aws.String("Name")}, } req := aws.NewRequest(service, &aws.Operation{}, input, nil) aws.ValidateParameters(req) assert.NoError(t, req.Error) }
func TestDownloadZero(t *testing.T) { s, names, ranges := dlLoggingSvc([]byte{}) opts := &s3manager.DownloadOptions{S3: s} d := s3manager.NewDownloader(opts) w := newDLWriter(0) n, err := d.Download(w, &s3.GetObjectInput{ Bucket: aws.String("bucket"), Key: aws.String("key"), }) assert.Nil(t, err) assert.Equal(t, int64(0), n) assert.Equal(t, []string{"GetObject"}, *names) assert.Equal(t, []string{"bytes=0-5242879"}, *ranges) }
func TestUploadFailIfPartSizeTooSmall(t *testing.T) { opts := &s3manager.UploadOptions{PartSize: 5} mgr := s3manager.NewUploader(opts) resp, err := mgr.Upload(&s3manager.UploadInput{ Bucket: aws.String("Bucket"), Key: aws.String("Key"), Body: bytes.NewReader(buf12MB), }) assert.Nil(t, resp) assert.NotNil(t, err) aerr := err.(awserr.Error) assert.Equal(t, "ConfigError", aerr.Code()) assert.Contains(t, aerr.Message(), "part size must be at least") }
func TestUploadOrderSingleFailure(t *testing.T) { s, ops, _ := loggingSvc() s.Handlers.Send.PushBack(func(r *aws.Request) { r.HTTPResponse.StatusCode = 400 }) mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) resp, err := mgr.Upload(&s3manager.UploadInput{ Bucket: aws.String("Bucket"), Key: aws.String("Key"), Body: bytes.NewReader(buf2MB), }) assert.Error(t, err) assert.Equal(t, []string{"PutObject"}, *ops) assert.Nil(t, resp) }
func TestInputService2ProtocolTestNestedStructureMembersCase1(t *testing.T) { svc := NewInputService2ProtocolTest(nil) svc.Endpoint = "https://test" input := &InputService2TestShapeInputShape{ StructArg: &InputService2TestShapeStructType{ ScalarArg: aws.String("foo"), }, } req, _ := svc.InputService2TestCaseOperation1Request(input) r := req.HTTPRequest // build request query.Build(req) assert.NoError(t, req.Error) // assert body assert.NotNil(t, r.Body) body, _ := ioutil.ReadAll(r.Body) assert.Equal(t, util.Trim(`Action=OperationName&StructArg.ScalarArg=foo&Version=2014-01-01`), util.Trim(string(body))) // assert URL assert.Equal(t, "https://test/", r.URL.String()) // assert headers }
func TestMD5InPutBucketLifecycle(t *testing.T) { svc := s3.New(nil) req, _ := svc.PutBucketLifecycleRequest(&s3.PutBucketLifecycleInput{ Bucket: aws.String("bucketname"), LifecycleConfiguration: &s3.LifecycleConfiguration{ Rules: []*s3.LifecycleRule{ { ID: aws.String("ID"), Prefix: aws.String("Prefix"), Status: aws.String("Enabled"), }, }, }, }) assertMD5(t, req) }
// Use S3 for simplicity func TestPaginationTruncation(t *testing.T) { count := 0 client := s3.New(nil) reqNum := &count resps := []*s3.ListObjectsOutput{ {IsTruncated: aws.Boolean(true), Contents: []*s3.Object{{Key: aws.String("Key1")}}}, {IsTruncated: aws.Boolean(true), Contents: []*s3.Object{{Key: aws.String("Key2")}}}, {IsTruncated: aws.Boolean(false), Contents: []*s3.Object{{Key: aws.String("Key3")}}}, {IsTruncated: aws.Boolean(true), Contents: []*s3.Object{{Key: aws.String("Key4")}}}, } client.Handlers.Send.Clear() // mock sending client.Handlers.Unmarshal.Clear() client.Handlers.UnmarshalMeta.Clear() client.Handlers.ValidateResponse.Clear() client.Handlers.Unmarshal.PushBack(func(r *aws.Request) { r.Data = resps[*reqNum] *reqNum++ }) params := &s3.ListObjectsInput{Bucket: aws.String("bucket")} results := []string{} err := client.ListObjectsPages(params, func(p *s3.ListObjectsOutput, last bool) bool { results = append(results, *p.Contents[0].Key) return true }) assert.Equal(t, []string{"Key1", "Key2", "Key3"}, results) assert.Nil(t, err) // Try again without truncation token at all count = 0 resps[1].IsTruncated = nil resps[2].IsTruncated = aws.Boolean(true) results = []string{} err = client.ListObjectsPages(params, func(p *s3.ListObjectsOutput, last bool) bool { results = append(results, *p.Contents[0].Key) return true }) assert.Equal(t, []string{"Key1", "Key2"}, results) assert.Nil(t, err) }
func TestComputeSSEKeys(t *testing.T) { s := s3.New(nil) req, _ := s.CopyObjectRequest(&s3.CopyObjectInput{ Bucket: aws.String("bucket"), CopySource: aws.String("bucket/source"), Key: aws.String("dest"), SSECustomerKey: aws.String("key"), CopySourceSSECustomerKey: aws.String("key"), }) err := req.Build() assert.NoError(t, err) assert.Equal(t, "a2V5", req.HTTPRequest.Header.Get("x-amz-server-side-encryption-customer-key")) assert.Equal(t, "a2V5", req.HTTPRequest.Header.Get("x-amz-copy-source-server-side-encryption-customer-key")) assert.Equal(t, "PG4LipwVIkqCKLmpjKFTHQ==", req.HTTPRequest.Header.Get("x-amz-server-side-encryption-customer-key-md5")) assert.Equal(t, "PG4LipwVIkqCKLmpjKFTHQ==", req.HTTPRequest.Header.Get("x-amz-copy-source-server-side-encryption-customer-key-md5")) }