func TestPresignHandler(t *testing.T) { svc := s3.New(unit.Session) 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 TestInputService2ProtocolTestTimestampValuesCase1(t *testing.T) { sess := session.New() svc := NewInputService2ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")}) input := &InputService2TestShapeInputService2TestCaseOperation1Input{ TimeArg: aws.Time(time.Unix(1422172800, 0)), } req, _ := svc.InputService2TestCaseOperation1Request(input) r := req.HTTPRequest // build request jsonrpc.Build(req) assert.NoError(t, req.Error) // assert body assert.NotNil(t, r.Body) body, _ := ioutil.ReadAll(r.Body) awstesting.AssertJSON(t, `{"TimeArg":1422172800}`, util.Trim(string(body))) // assert URL awstesting.AssertURL(t, "https://test/", r.URL.String()) // assert headers assert.Equal(t, "application/x-amz-json-1.1", r.Header.Get("Content-Type")) assert.Equal(t, "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target")) }
func TestOutputService9ProtocolTestSupportsHeaderMapsCase1(t *testing.T) { sess := session.New() svc := NewOutputService9ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")}) buf := bytes.NewReader([]byte("{}")) req, out := svc.OutputService9TestCaseOperation1Request(nil) req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} // set headers req.HTTPResponse.Header.Set("Content-Length", "10") req.HTTPResponse.Header.Set("X-Bam", "boo") req.HTTPResponse.Header.Set("X-Foo", "bar") // unmarshal response restjson.UnmarshalMeta(req) restjson.Unmarshal(req) assert.NoError(t, req.Error) // assert response assert.NotNil(t, out) // ensure out variable is used assert.Equal(t, "10", *out.AllHeaders["Content-Length"]) assert.Equal(t, "boo", *out.AllHeaders["X-Bam"]) assert.Equal(t, "bar", *out.AllHeaders["X-Foo"]) assert.Equal(t, "boo", *out.PrefixedHeaders["Bam"]) assert.Equal(t, "bar", *out.PrefixedHeaders["Foo"]) }
func TestInputService4ProtocolTestNestedBlobsCase1(t *testing.T) { sess := session.New() svc := NewInputService4ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")}) input := &InputService4TestShapeInputService4TestCaseOperation1Input{ ListParam: [][]byte{ []byte("foo"), []byte("bar"), }, } req, _ := svc.InputService4TestCaseOperation1Request(input) r := req.HTTPRequest // build request jsonrpc.Build(req) assert.NoError(t, req.Error) // assert body assert.NotNil(t, r.Body) body, _ := ioutil.ReadAll(r.Body) awstesting.AssertJSON(t, `{"ListParam":["Zm9v","YmFy"]}`, util.Trim(string(body))) // assert URL awstesting.AssertURL(t, "https://test/", r.URL.String()) // assert headers assert.Equal(t, "application/x-amz-json-1.1", r.Header.Get("Content-Type")) assert.Equal(t, "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target")) }
func TestInputService5ProtocolTestRecursiveShapesCase3(t *testing.T) { sess := session.New() svc := NewInputService5ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")}) input := &InputService5TestShapeInputShape{ RecursiveStruct: &InputService5TestShapeRecursiveStructType{ RecursiveStruct: &InputService5TestShapeRecursiveStructType{ RecursiveStruct: &InputService5TestShapeRecursiveStructType{ RecursiveStruct: &InputService5TestShapeRecursiveStructType{ NoRecurse: aws.String("foo"), }, }, }, }, } req, _ := svc.InputService5TestCaseOperation3Request(input) r := req.HTTPRequest // build request jsonrpc.Build(req) assert.NoError(t, req.Error) // assert body assert.NotNil(t, r.Body) body, _ := ioutil.ReadAll(r.Body) awstesting.AssertJSON(t, `{"RecursiveStruct":{"RecursiveStruct":{"RecursiveStruct":{"RecursiveStruct":{"NoRecurse":"foo"}}}}}`, util.Trim(string(body))) // assert URL awstesting.AssertURL(t, "https://test/", r.URL.String()) // assert headers assert.Equal(t, "application/x-amz-json-1.1", r.Header.Get("Content-Type")) assert.Equal(t, "com.amazonaws.foo.OperationName", r.Header.Get("X-Amz-Target")) }
func TestTimeValueSlice(t *testing.T) { for idx, in := range testCasesTimeValueSlice { if in == nil { continue } out := TimeValueSlice(in) assert.Len(t, out, len(in), "Unexpected len at idx %d", idx) for i := range out { if in[i] == nil { assert.Empty(t, out[i], "Unexpected value at idx %d", idx) } else { assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx) } } out2 := TimeSlice(out) assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx) for i := range out2 { if in[i] == nil { assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx) } else { assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx) } } } }
func TestNewDefaultSession(t *testing.T) { s := session.New(&aws.Config{Region: aws.String("region")}) assert.Equal(t, "region", *s.Config.Region) assert.Equal(t, http.DefaultClient, s.Config.HTTPClient) assert.NotNil(t, s.Config.Logger) assert.Equal(t, aws.LogOff, *s.Config.LogLevel) }
func TestMissingRequiredParameters(t *testing.T) { input := &StructShape{} req := testSvc.NewRequest(&request.Operation{}, input, nil) corehandlers.ValidateParametersHandler.Fn(req) require.Error(t, req.Error) assert.Equal(t, "InvalidParameter", req.Error.(awserr.Error).Code()) assert.Equal(t, "3 validation errors:\n- missing required parameter: RequiredList\n- missing required parameter: RequiredMap\n- missing required parameter: RequiredBool", req.Error.(awserr.Error).Message()) }
func TestGlobalEndpoints(t *testing.T) { region := "mock-region-1" svcs := []string{"cloudfront", "iam", "importexport", "route53", "sts", "waf"} for _, name := range svcs { ep, sr := endpoints.EndpointForRegion(name, region, false) assert.Equal(t, fmt.Sprintf("https://%s.amazonaws.com", name), ep) assert.Equal(t, "us-east-1", sr) } }
func TestSignSeekedBody(t *testing.T) { signer := buildSigner("dynamodb", "us-east-1", time.Now(), 0, " hello") signer.Body.Read(make([]byte, 3)) // consume first 3 bytes so body is now "hello" signer.sign() hash := signer.Request.Header.Get("X-Amz-Content-Sha256") assert.Equal(t, "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", hash) start, _ := signer.Body.Seek(0, 1) assert.Equal(t, int64(3), start) }
func TestCopyDifferentStructs(t *testing.T) { type SrcFoo struct { A int B []*string C map[string]*int SrcUnique string SameNameDiffType int unexportedPtr *int ExportedPtr *int } type DstFoo struct { A int B []*string C map[string]*int DstUnique int SameNameDiffType string unexportedPtr *int ExportedPtr *int } // Create the initial value str1 := "hello" str2 := "bye bye" int1 := 1 int2 := 2 f1 := &SrcFoo{ A: 1, B: []*string{&str1, &str2}, C: map[string]*int{ "A": &int1, "B": &int2, }, SrcUnique: "unique", SameNameDiffType: 1, unexportedPtr: &int1, ExportedPtr: &int2, } // Do the copy var f2 DstFoo awsutil.Copy(&f2, f1) // Values are equal assert.Equal(t, f2.A, f1.A) assert.Equal(t, f2.B, f1.B) assert.Equal(t, f2.C, f1.C) assert.Equal(t, "unique", f1.SrcUnique) assert.Equal(t, 1, f1.SameNameDiffType) assert.Equal(t, 0, f2.DstUnique) assert.Equal(t, "", f2.SameNameDiffType) assert.Equal(t, int1, *f1.unexportedPtr) assert.Nil(t, f2.unexportedPtr) assert.Equal(t, int2, *f1.ExportedPtr) assert.Equal(t, int2, *f2.ExportedPtr) }
func TestSignRequest(t *testing.T) { signer := buildSigner("dynamodb", "us-east-1", time.Unix(0, 0), 0, "{}") signer.sign() expectedDate := "19700101T000000Z" expectedSig := "AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/dynamodb/aws4_request, SignedHeaders=host;x-amz-date;x-amz-meta-other-header;x-amz-security-token;x-amz-target, Signature=69ada33fec48180dab153576e4dd80c4e04124f80dda3eccfed8a67c2b91ed5e" q := signer.Request.Header assert.Equal(t, expectedSig, q.Get("Authorization")) assert.Equal(t, expectedDate, q.Get("X-Amz-Date")) }
func TestSharedCredentialsProviderColonInCredFile(t *testing.T) { os.Clearenv() p := SharedCredentialsProvider{Filename: "example.ini", Profile: "with_colon"} creds, err := p.Retrieve() assert.Nil(t, err, "Expect no error") assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") assert.Empty(t, creds.SessionToken, "Expect no token") }
func TestHandlerList(t *testing.T) { s := "" r := &request.Request{} l := request.HandlerList{} l.PushBack(func(r *request.Request) { s += "a" r.Data = s }) l.Run(r) assert.Equal(t, "a", s) assert.Equal(t, "a", r.Data) }
func TestSharedCredentialsProviderWithAWS_SHARED_CREDENTIALS_FILE(t *testing.T) { os.Clearenv() os.Setenv("AWS_SHARED_CREDENTIALS_FILE", "example.ini") p := SharedCredentialsProvider{} creds, err := p.Retrieve() assert.Nil(t, err, "Expect no error") assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") assert.Equal(t, "token", creds.SessionToken, "Expect session token to match") }
func TestEndpoint(t *testing.T) { c := ec2metadata.New(session.New()) op := &request.Operation{ Name: "GetMetadata", HTTPMethod: "GET", HTTPPath: path.Join("/", "meta-data", "testpath"), } req := c.NewRequest(op, nil, nil) assert.Equal(t, "http://169.254.169.254/latest", req.ClientInfo.Endpoint) assert.Equal(t, "http://169.254.169.254/latest/meta-data/testpath", req.HTTPRequest.URL.String()) }
func TestNamedHandlers(t *testing.T) { l := request.HandlerList{} named := request.NamedHandler{Name: "Name", Fn: func(r *request.Request) {}} named2 := request.NamedHandler{Name: "NotName", Fn: func(r *request.Request) {}} l.PushBackNamed(named) l.PushBackNamed(named) l.PushBackNamed(named2) l.PushBack(func(r *request.Request) {}) assert.Equal(t, 4, l.Len()) l.Remove(named) assert.Equal(t, 2, l.Len()) }
func TestSharedCredentialsProviderWithAWS_PROFILE(t *testing.T) { os.Clearenv() os.Setenv("AWS_PROFILE", "no_token") p := SharedCredentialsProvider{Filename: "example.ini", Profile: ""} creds, err := p.Retrieve() assert.Nil(t, err, "Expect no error") assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") assert.Empty(t, creds.SessionToken, "Expect no token") }
func TestCopyReader(t *testing.T) { var buf io.Reader = bytes.NewReader([]byte("hello world")) var r io.Reader awsutil.Copy(&r, buf) b, err := ioutil.ReadAll(r) assert.NoError(t, err) assert.Equal(t, []byte("hello world"), b) // empty bytes because this is not a deep copy b, err = ioutil.ReadAll(buf) assert.NoError(t, err) assert.Equal(t, []byte(""), b) }
func TestEnvProviderAlternateNames(t *testing.T) { os.Clearenv() os.Setenv("AWS_ACCESS_KEY", "access") os.Setenv("AWS_SECRET_KEY", "secret") e := EnvProvider{} creds, err := e.Retrieve() assert.Nil(t, err, "Expect no error") assert.Equal(t, "access", creds.AccessKeyID, "Expected access key ID") assert.Equal(t, "secret", creds.SecretAccessKey, "Expected secret access key") assert.Empty(t, creds.SessionToken, "Expected no token") }
// Use DynamoDB methods for simplicity func TestPaginationEachPage(t *testing.T) { db := dynamodb.New(unit.Session) 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 *request.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 *request.Request) { r.Data = resps[reqNum] reqNum++ }) params := &dynamodb.ListTablesInput{Limit: aws.Int64(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 TestOutputService1ProtocolTestScalarMembersCase1(t *testing.T) { sess := session.New() svc := NewOutputService1ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")}) buf := bytes.NewReader([]byte("{\"Str\": \"myname\", \"Num\": 123, \"FalseBool\": false, \"TrueBool\": true, \"Float\": 1.2, \"Double\": 1.3, \"Long\": 200, \"Char\": \"a\"}")) req, out := svc.OutputService1TestCaseOperation1Request(nil) req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} // set headers // unmarshal response jsonrpc.UnmarshalMeta(req) jsonrpc.Unmarshal(req) assert.NoError(t, req.Error) // assert response assert.NotNil(t, out) // ensure out variable is used assert.Equal(t, "a", *out.Char) assert.Equal(t, 1.3, *out.Double) assert.Equal(t, false, *out.FalseBool) assert.Equal(t, 1.2, *out.Float) assert.Equal(t, int64(200), *out.Long) assert.Equal(t, int64(123), *out.Num) assert.Equal(t, "myname", *out.Str) assert.Equal(t, true, *out.TrueBool) }
func TestAssumeRoleProvider(t *testing.T) { stub := &stubSTS{} p := &AssumeRoleProvider{ Client: stub, RoleARN: "roleARN", } creds, err := p.Retrieve() assert.Nil(t, err, "Expect no error") assert.Equal(t, "roleARN", creds.AccessKeyID, "Expect access key ID to be reflected role ARN") assert.Equal(t, "assumedSecretAccessKey", creds.SecretAccessKey, "Expect secret access key to match") assert.Equal(t, "assumedSessionToken", creds.SessionToken, "Expect session token to match") }
func TestEnvProviderRetrieve(t *testing.T) { os.Clearenv() os.Setenv("AWS_ACCESS_KEY_ID", "access") os.Setenv("AWS_SECRET_ACCESS_KEY", "secret") os.Setenv("AWS_SESSION_TOKEN", "token") e := EnvProvider{} creds, err := e.Retrieve() assert.Nil(t, err, "Expect no error") assert.Equal(t, "access", creds.AccessKeyID, "Expect access key ID to match") assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") assert.Equal(t, "token", creds.SessionToken, "Expect session token to match") }
func TestEC2RoleProvider(t *testing.T) { server := initTestServer("2014-12-16T01:51:37Z", false) defer server.Close() p := &ec2rolecreds.EC2RoleProvider{ Client: ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")}), } creds, err := p.Retrieve() assert.Nil(t, err, "Expect no error, %v", err) assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match") assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match") assert.Equal(t, "token", creds.SessionToken, "Expect session token to match") }
func TestStaticProviderGet(t *testing.T) { s := StaticProvider{ Value: Value{ AccessKeyID: "AKID", SecretAccessKey: "SECRET", SessionToken: "", }, } creds, err := s.Retrieve() assert.Nil(t, err, "Expect no error") assert.Equal(t, "AKID", creds.AccessKeyID, "Expect access key ID to match") assert.Equal(t, "SECRET", creds.SecretAccessKey, "Expect secret access key to match") assert.Empty(t, creds.SessionToken, "Expect no session token") }
func TestPresignRequest(t *testing.T) { signer := buildSigner("dynamodb", "us-east-1", time.Unix(0, 0), 300*time.Second, "{}") signer.sign() expectedDate := "19700101T000000Z" expectedHeaders := "host;x-amz-meta-other-header;x-amz-target" expectedSig := "5eeedebf6f995145ce56daa02902d10485246d3defb34f97b973c1f40ab82d36" expectedCred := "AKID/19700101/us-east-1/dynamodb/aws4_request" q := signer.Request.URL.Query() assert.Equal(t, expectedSig, q.Get("X-Amz-Signature")) assert.Equal(t, expectedCred, q.Get("X-Amz-Credential")) assert.Equal(t, expectedHeaders, q.Get("X-Amz-SignedHeaders")) assert.Equal(t, expectedDate, q.Get("X-Amz-Date")) }
func TestCredentialsGet(t *testing.T) { c := NewCredentials(&stubProvider{ creds: Value{ AccessKeyID: "AKID", SecretAccessKey: "SECRET", SessionToken: "", }, expired: true, }) creds, err := c.Get() assert.Nil(t, err, "Expected no error") assert.Equal(t, "AKID", creds.AccessKeyID, "Expect access key ID to match") assert.Equal(t, "SECRET", creds.SecretAccessKey, "Expect secret access key to match") assert.Empty(t, creds.SessionToken, "Expect session token to be empty") }
func TestValueAtPathFailure(t *testing.T) { var testCases = []struct { expect []interface{} errContains string data interface{} path string }{ {nil, "", data, "C.x"}, {nil, "SyntaxError: Invalid token: tDot", data, ".x"}, {nil, "", data, "X.Y.Z"}, {nil, "", data, "A[100].C"}, {nil, "", data, "A[3].C"}, {nil, "", data, "B.B.C.Z"}, {nil, "", data, "z[-1].C"}, {nil, "", nil, "A.B.C"}, {[]interface{}{}, "", Struct{}, "A"}, {nil, "", data, "A[0].B.C"}, {nil, "", data, "D"}, } for i, c := range testCases { v, err := awsutil.ValuesAtPath(c.data, c.path) if c.errContains != "" { assert.Contains(t, err.Error(), c.errContains, "case %d, expected error, %s", i, c.path) continue } else { assert.NoError(t, err, "case %d, expected no error, %s", i, c.path) } assert.Equal(t, c.expect, v, "case %d, %s", i, c.path) } }
func TestValueAtPathSuccess(t *testing.T) { var testCases = []struct { expect []interface{} data interface{} path string }{ {[]interface{}{"initial"}, data, "C"}, {[]interface{}{"value1"}, data, "A[0].C"}, {[]interface{}{"value2"}, data, "A[1].C"}, {[]interface{}{"value3"}, data, "A[2].C"}, {[]interface{}{"value3"}, data, "a[2].c"}, {[]interface{}{"value3"}, data, "A[-1].C"}, {[]interface{}{"value1", "value2", "value3"}, data, "A[].C"}, {[]interface{}{"terminal"}, data, "B . B . C"}, {[]interface{}{"initial"}, data, "A.D.X || C"}, {[]interface{}{"initial"}, data, "A[0].B || C"}, {[]interface{}{ Struct{A: []Struct{{C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}, {C: "1"}}}, Struct{A: []Struct{{C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}, {C: "2"}}}, }, data2, "A"}, } for i, c := range testCases { v, err := awsutil.ValuesAtPath(c.data, c.path) assert.NoError(t, err, "case %d, expected no error, %s", i, c.path) assert.Equal(t, c.expect, v, "case %d, %s", i, c.path) } }