Esempio n. 1
0
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)
	}
}
Esempio n. 2
0
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)
	}
}
Esempio n. 3
0
func validateSSERequiresSSL(r *request.Request) {
	if r.HTTPRequest.URL.Scheme != "https" {
		p, _ := awsutil.ValuesAtPath(r.Params, "SSECustomerKey||CopySourceSSECustomerKey")
		if len(p) > 0 {
			r.Error = errSSERequiresSSL
		}
	}
}
func TestNoPopulateLocationConstraintIfClassic(t *testing.T) {
	s := s3.New(unit.Session, &aws.Config{Region: aws.String("us-east-1")})
	req, _ := s.CreateBucketRequest(&s3.CreateBucketInput{
		Bucket: aws.String("bucket"),
	})
	err := req.Build()
	assert.NoError(t, err)
	v, _ := awsutil.ValuesAtPath(req.Params, "CreateBucketConfiguration.LocationConstraint")
	assert.Equal(t, 0, len(v))
}
func TestPopulateLocationConstraint(t *testing.T) {
	s := s3.New(unit.Session)
	in := &s3.CreateBucketInput{
		Bucket: aws.String("bucket"),
	}
	req, _ := s.CreateBucketRequest(in)
	err := req.Build()
	assert.NoError(t, err)
	v, _ := awsutil.ValuesAtPath(req.Params, "CreateBucketConfiguration.LocationConstraint")
	assert.Equal(t, "mock-region", *(v[0].(*string)))
	assert.Nil(t, in.CreateBucketConfiguration) // don't modify original params
}
// nextPageTokens returns the tokens to use when asking for the next page of
// data.
func (r *Request) nextPageTokens() []interface{} {
	if r.Operation.Paginator == nil {
		return nil
	}

	if r.Operation.TruncationToken != "" {
		tr, _ := awsutil.ValuesAtPath(r.Data, r.Operation.TruncationToken)
		if len(tr) == 0 {
			return nil
		}

		switch v := tr[0].(type) {
		case *bool:
			if !aws.BoolValue(v) {
				return nil
			}
		case bool:
			if v == false {
				return nil
			}
		}
	}

	tokens := []interface{}{}
	tokenAdded := false
	for _, outToken := range r.Operation.OutputTokens {
		v, _ := awsutil.ValuesAtPath(r.Data, outToken)
		if len(v) > 0 {
			tokens = append(tokens, v[0])
			tokenAdded = true
		} else {
			tokens = append(tokens, nil)
		}
	}
	if !tokenAdded {
		return nil
	}

	return tokens
}
Esempio n. 7
0
func updateHostWithBucket(r *request.Request) {
	b, _ := awsutil.ValuesAtPath(r.Params, "Bucket")
	if len(b) == 0 {
		return
	}

	if bucket := b[0].(*string); aws.StringValue(bucket) != "" && hostStyleBucketName(r, *bucket) {
		r.HTTPRequest.URL.Host = *bucket + "." + r.HTTPRequest.URL.Host
		r.HTTPRequest.URL.Path = strings.Replace(r.HTTPRequest.URL.Path, "/{Bucket}", "", -1)
		if r.HTTPRequest.URL.Path == "" {
			r.HTTPRequest.URL.Path = "/"
		}
	}
}
Esempio n. 8
0
func val(i interface{}, s string) interface{} {
	v, err := awsutil.ValuesAtPath(i, s)
	if err != nil || len(v) == 0 {
		return nil
	}
	if _, ok := v[0].(io.Reader); ok {
		return v[0]
	}

	if rv := reflect.ValueOf(v[0]); rv.Kind() == reflect.Ptr {
		return rv.Elem().Interface()
	}

	return v[0]
}
func TestFillAccountIDWithNilStruct(t *testing.T) {
	req, _ := svc.ListVaultsRequest(nil)
	err := req.Build()
	assert.NoError(t, err)

	empty := "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"

	// Sets Account ID
	v, _ := awsutil.ValuesAtPath(req.Params, "AccountId")
	assert.Equal(t, "-", *(v[0].(*string)))

	// Does not set tree hash
	assert.Equal(t, empty, req.HTTPRequest.Header.Get("x-amz-content-sha256"))
	assert.Equal(t, "", req.HTTPRequest.Header.Get("x-amz-sha256-tree-hash"))
}
Esempio n. 10
0
func TestCustomizations(t *testing.T) {
	req, _ := svc.UploadArchiveRequest(&glacier.UploadArchiveInput{
		VaultName: aws.String("vault"),
		Body:      payloadBuf,
	})
	err := req.Build()
	assert.NoError(t, err)

	// Sets API version
	assert.Equal(t, req.ClientInfo.APIVersion, req.HTTPRequest.Header.Get("x-amz-glacier-version"))

	// Sets Account ID
	v, _ := awsutil.ValuesAtPath(req.Params, "AccountId")
	assert.Equal(t, "-", *(v[0].(*string)))

	// Computes checksums
	linear := "68aff0c5a91aa0491752bfb96e3fef33eb74953804f6a2f7b708d5bcefa8ff6b"
	tree := "154e26c78fd74d0c2c9b3cc4644191619dc4f2cd539ae2a74d5fd07957a3ee6a"
	assert.Equal(t, linear, req.HTTPRequest.Header.Get("x-amz-content-sha256"))
	assert.Equal(t, tree, req.HTTPRequest.Header.Get("x-amz-sha256-tree-hash"))
}
Esempio n. 11
0
func init() {
	logLevel := Session.Config.LogLevel
	if os.Getenv("DEBUG") != "" {
		logLevel = aws.LogLevel(aws.LogDebug)
	}
	if os.Getenv("DEBUG_SIGNING") != "" {
		logLevel = aws.LogLevel(aws.LogDebugWithSigning)
	}
	if os.Getenv("DEBUG_BODY") != "" {
		logLevel = aws.LogLevel(aws.LogDebugWithHTTPBody)
	}
	Session.Config.LogLevel = logLevel

	When(`^I call the "(.+?)" API$`, func(op string) {
		call(op, nil, false)
	})

	When(`^I call the "(.+?)" API with:$`, func(op string, args [][]string) {
		call(op, args, false)
	})

	Then(`^the value at "(.+?)" should be a list$`, func(member string) {
		vals, _ := awsutil.ValuesAtPath(World["response"], member)
		assert.NotNil(T, vals)
	})

	Then(`^the response should contain a "(.+?)"$`, func(member string) {
		vals, _ := awsutil.ValuesAtPath(World["response"], member)
		assert.NotEmpty(T, vals)
	})

	When(`^I attempt to call the "(.+?)" API with:$`, func(op string, args [][]string) {
		call(op, args, true)
	})

	Then(`^I expect the response error code to be "(.+?)"$`, func(code string) {
		err, ok := World["error"].(awserr.Error)
		assert.True(T, ok, "no error returned")
		if ok {
			assert.Equal(T, code, err.Code(), "Error: %v", err)
		}
	})

	And(`^I expect the response error message to include:$`, func(data string) {
		err, ok := World["error"].(awserr.Error)
		assert.True(T, ok, "no error returned")
		if ok {
			assert.Contains(T, err.Message(), data)
		}
	})

	And(`^I expect the response error message to include one of:$`, func(table [][]string) {
		err, ok := World["error"].(awserr.Error)
		assert.True(T, ok, "no error returned")
		if ok {
			found := false
			for _, row := range table {
				if strings.Contains(err.Message(), row[0]) {
					found = true
					break
				}
			}

			assert.True(T, found, fmt.Sprintf("no error messages matched: \"%s\"", err.Message()))
		}
	})

	When(`^I call the "(.+?)" API with JSON:$`, func(s1 string, data string) {
		callWithJSON(s1, data, false)
	})

	When(`^I attempt to call the "(.+?)" API with JSON:$`, func(s1 string, data string) {
		callWithJSON(s1, data, true)
	})

	Then(`^the error code should be "(.+?)"$`, func(s1 string) {
		err, ok := World["error"].(awserr.Error)
		assert.True(T, ok, "no error returned")
		assert.Equal(T, s1, err.Code())
	})

	And(`^the error message should contain:$`, func(data string) {
		err, ok := World["error"].(awserr.Error)
		assert.True(T, ok, "no error returned")
		assert.Contains(T, err.Error(), data)
	})

	Then(`^the request should fail$`, func() {
		err, ok := World["error"].(awserr.Error)
		assert.True(T, ok, "no error returned")
		assert.Error(T, err)
	})

	Then(`^the request should be successful$`, func() {
		err, ok := World["error"].(awserr.Error)
		assert.False(T, ok, "error returned")
		assert.NoError(T, err)
	})
}
Esempio n. 12
0
// Wait waits for an operation to complete, expire max attempts, or fail. Error
// is returned if the operation fails.
func (w *Waiter) Wait() error {
	client := reflect.ValueOf(w.Client)
	in := reflect.ValueOf(w.Input)
	method := client.MethodByName(w.Config.Operation + "Request")

	for i := 0; i < w.MaxAttempts; i++ {
		res := method.Call([]reflect.Value{in})
		req := res[0].Interface().(*request.Request)
		req.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Waiter"))

		err := req.Send()
		for _, a := range w.Acceptors {
			result := false
			var vals []interface{}
			switch a.Matcher {
			case "pathAll", "path":
				// Require all matches to be equal for result to match
				vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument)
				if len(vals) == 0 {
					break
				}
				result = true
				for _, val := range vals {
					if !awsutil.DeepEqual(val, a.Expected) {
						result = false
						break
					}
				}
			case "pathAny":
				// Only a single match needs to equal for the result to match
				vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument)
				for _, val := range vals {
					if awsutil.DeepEqual(val, a.Expected) {
						result = true
						break
					}
				}
			case "status":
				s := a.Expected.(int)
				result = s == req.HTTPResponse.StatusCode
			case "error":
				if aerr, ok := err.(awserr.Error); ok {
					result = aerr.Code() == a.Expected.(string)
				}
			case "pathList":
				// ignored matcher
			default:
				logf(client, "WARNING: Waiter for %s encountered unexpected matcher: %s",
					w.Config.Operation, a.Matcher)
			}

			if !result {
				// If there was no matching result found there is nothing more to do
				// for this response, retry the request.
				continue
			}

			switch a.State {
			case "success":
				// waiter completed
				return nil
			case "failure":
				// Waiter failure state triggered
				return awserr.New("ResourceNotReady",
					fmt.Sprintf("failed waiting for successful resource state"), err)
			case "retry":
				// clear the error and retry the operation
				err = nil
			default:
				logf(client, "WARNING: Waiter for %s encountered unexpected state: %s",
					w.Config.Operation, a.State)
			}
		}
		if err != nil {
			return err
		}

		time.Sleep(time.Second * time.Duration(w.Delay))
	}

	return awserr.New("ResourceNotReady",
		fmt.Sprintf("exceeded %d wait attempts", w.MaxAttempts), nil)
}