예제 #1
0
func ExampleLambda_CreateFunction() {
	svc := lambda.New(session.New())

	params := &lambda.CreateFunctionInput{
		Code: &lambda.FunctionCode{ // Required
			S3Bucket:        aws.String("S3Bucket"),
			S3Key:           aws.String("S3Key"),
			S3ObjectVersion: aws.String("S3ObjectVersion"),
			ZipFile:         []byte("PAYLOAD"),
		},
		FunctionName: aws.String("FunctionName"), // Required
		Handler:      aws.String("Handler"),      // Required
		Role:         aws.String("RoleArn"),      // Required
		Runtime:      aws.String("Runtime"),      // Required
		Description:  aws.String("Description"),
		MemorySize:   aws.Int64(1),
		Publish:      aws.Bool(true),
		Timeout:      aws.Int64(1),
	}
	resp, err := svc.CreateFunction(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
// Use S3 for simplicity
func TestPaginationTruncation(t *testing.T) {
	client := s3.New(unit.Session)

	reqNum := 0
	resps := []*s3.ListObjectsOutput{
		{IsTruncated: aws.Bool(true), Contents: []*s3.Object{{Key: aws.String("Key1")}}},
		{IsTruncated: aws.Bool(true), Contents: []*s3.Object{{Key: aws.String("Key2")}}},
		{IsTruncated: aws.Bool(false), Contents: []*s3.Object{{Key: aws.String("Key3")}}},
		{IsTruncated: aws.Bool(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 *request.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
	reqNum = 0
	resps[1].IsTruncated = nil
	resps[2].IsTruncated = aws.Bool(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)
}
예제 #3
0
func TestMultipleHandlers(t *testing.T) {
	r := &request.Request{}
	l := request.HandlerList{}
	l.PushBack(func(r *request.Request) { r.Data = nil })
	l.PushFront(func(r *request.Request) { r.Data = aws.Bool(true) })
	l.Run(r)
	if r.Data != nil {
		t.Error("Expected handler to execute")
	}
}
예제 #4
0
func TestSendMessageChecksumInvalidNoValidation(t *testing.T) {
	s := sqs.New(unit.Session, &aws.Config{
		DisableParamValidation:  aws.Bool(true),
		DisableComputeChecksums: aws.Bool(true),
	})
	s.Handlers.Send.Clear()

	req, _ := s.SendMessageRequest(&sqs.SendMessageInput{
		MessageBody: aws.String("test"),
	})
	req.Handlers.Send.PushBack(func(r *request.Request) {
		body := ioutil.NopCloser(bytes.NewReader([]byte("")))
		r.HTTPResponse = &http.Response{StatusCode: 200, Body: body}
		r.Data = &sqs.SendMessageOutput{
			MD5OfMessageBody: aws.String("000"),
			MessageId:        aws.String("12345"),
		}
	})
	err := req.Send()
	assert.NoError(t, err)
}
예제 #5
0
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.Bool(true),
		OptionalStruct: &ConditionalStructShape{Name: aws.String("Name")},
	}

	req := testSvc.NewRequest(&request.Operation{}, input, nil)
	corehandlers.ValidateParametersHandler.Fn(req)
	require.NoError(t, req.Error)
}
예제 #6
0
func TestMetadataNotAvailable(t *testing.T) {
	c := ec2metadata.New(session.New())
	c.Handlers.Send.Clear()
	c.Handlers.Send.PushBack(func(r *request.Request) {
		r.HTTPResponse = &http.Response{
			StatusCode: int(0),
			Status:     http.StatusText(int(0)),
			Body:       ioutil.NopCloser(bytes.NewReader([]byte{})),
		}
		r.Error = awserr.New("RequestError", "send request failed", nil)
		r.Retryable = aws.Bool(true) // network errors are retryable
	})

	available := c.Available()

	assert.False(t, available)
}
예제 #7
0
func TestNestedMissingRequiredParameters(t *testing.T) {
	input := &StructShape{
		RequiredList: []*ConditionalStructShape{{}},
		RequiredMap: map[string]*ConditionalStructShape{
			"key1": {Name: aws.String("Name")},
			"key2": {},
		},
		RequiredBool:   aws.Bool(true),
		OptionalStruct: &ConditionalStructShape{},
	}

	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[0].Name\n- missing required parameter: RequiredMap[\"key2\"].Name\n- missing required parameter: OptionalStruct.Name", req.Error.(awserr.Error).Message())
}
예제 #8
0
func (infra *Infrastructure) createLambdaFunction(region, roleArn string, payload []byte) error {
	config := aws.NewConfig().WithRegion(region)
	svc := lambda.New(session.New(), config)

	_, err := svc.GetFunction(&lambda.GetFunctionInput{
		FunctionName: aws.String("goad"),
	})

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			if awsErr.Code() == "ResourceNotFoundException" {
				_, err := svc.CreateFunction(&lambda.CreateFunctionInput{
					Code: &lambda.FunctionCode{
						ZipFile: payload,
					},
					FunctionName: aws.String("goad"),
					Handler:      aws.String("index.handler"),
					Role:         aws.String(roleArn),
					Runtime:      aws.String("nodejs"),
					MemorySize:   aws.Int64(1536),
					Publish:      aws.Bool(true),
					Timeout:      aws.Int64(300),
				})
				if err != nil {
					if awsErr, ok := err.(awserr.Error); ok {
						// Calling this function too soon after creating the role might
						// fail, so we should retry after a little while.
						// TODO: limit the number of retries.
						if awsErr.Code() == "InvalidParameterValueException" {
							time.Sleep(time.Second)
							return infra.createLambdaFunction(region, roleArn, payload)
						}
					}
					return err
				}
			}
		}
	}

	return nil
}
예제 #9
0
func ExampleLambda_UpdateEventSourceMapping() {
	svc := lambda.New(session.New())

	params := &lambda.UpdateEventSourceMappingInput{
		UUID:         aws.String("String"), // Required
		BatchSize:    aws.Int64(1),
		Enabled:      aws.Bool(true),
		FunctionName: aws.String("FunctionName"),
	}
	resp, err := svc.UpdateEventSourceMapping(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
예제 #10
0
func ExampleLambda_UpdateFunctionCode() {
	svc := lambda.New(session.New())

	params := &lambda.UpdateFunctionCodeInput{
		FunctionName:    aws.String("FunctionName"), // Required
		Publish:         aws.Bool(true),
		S3Bucket:        aws.String("S3Bucket"),
		S3Key:           aws.String("S3Key"),
		S3ObjectVersion: aws.String("S3ObjectVersion"),
		ZipFile:         []byte("PAYLOAD"),
	}
	resp, err := svc.UpdateFunctionCode(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
예제 #11
0
	"io/ioutil"
	"net/http"
	"testing"

	"github.com/gophergala2016/goad/Godeps/_workspace/src/github.com/stretchr/testify/assert"

	"github.com/aws/aws-sdk-go/awstesting/unit"
	"github.com/gophergala2016/goad/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws"
	"github.com/gophergala2016/goad/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/gophergala2016/goad/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request"
	"github.com/gophergala2016/goad/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/sqs"
)

var svc = func() *sqs.SQS {
	s := sqs.New(unit.Session, &aws.Config{
		DisableParamValidation: aws.Bool(true),
	})
	s.Handlers.Send.Clear()
	return s
}()

func TestSendMessageChecksum(t *testing.T) {
	req, _ := svc.SendMessageRequest(&sqs.SendMessageInput{
		MessageBody: aws.String("test"),
	})
	req.Handlers.Send.PushBack(func(r *request.Request) {
		body := ioutil.NopCloser(bytes.NewReader([]byte("")))
		r.HTTPResponse = &http.Response{StatusCode: 200, Body: body}
		r.Data = &sqs.SendMessageOutput{
			MD5OfMessageBody: aws.String("098f6bcd4621d373cade4e832627b4f6"),
			MessageId:        aws.String("12345"),
예제 #12
0
func setChecksumError(r *request.Request, format string, args ...interface{}) {
	r.Retryable = aws.Bool(true)
	r.Error = awserr.New("InvalidChecksum", fmt.Sprintf(format, args...), nil)
}
예제 #13
0
				}
				return
			}
		}
		if r.HTTPResponse == nil {
			// Add a dummy request response object to ensure the HTTPResponse
			// value is consistent.
			r.HTTPResponse = &http.Response{
				StatusCode: int(0),
				Status:     http.StatusText(int(0)),
				Body:       ioutil.NopCloser(bytes.NewReader([]byte{})),
			}
		}
		// Catch all other request errors.
		r.Error = awserr.New("RequestError", "send request failed", err)
		r.Retryable = aws.Bool(true) // network errors are retryable
	}
}}

// ValidateResponseHandler is a request handler to validate service response.
var ValidateResponseHandler = request.NamedHandler{Name: "core.ValidateResponseHandler", Fn: func(r *request.Request) {
	if r.HTTPResponse.StatusCode == 0 || r.HTTPResponse.StatusCode >= 300 {
		// this may be replaced by an UnmarshalError handler
		r.Error = awserr.New("UnknownError", "unknown error", nil)
	}
}}

// AfterRetryHandler performs final checks to determine if the request should
// be retried and how long to delay.
var AfterRetryHandler = request.NamedHandler{Name: "core.AfterRetryHandler", Fn: func(r *request.Request) {
	// If one of the other handlers already set the retry state
func TestPaginationNilToken(t *testing.T) {
	client := route53.New(unit.Session)

	reqNum := 0
	resps := []*route53.ListResourceRecordSetsOutput{
		{
			ResourceRecordSets: []*route53.ResourceRecordSet{
				{Name: aws.String("first.example.com.")},
			},
			IsTruncated:          aws.Bool(true),
			NextRecordName:       aws.String("second.example.com."),
			NextRecordType:       aws.String("MX"),
			NextRecordIdentifier: aws.String("second"),
			MaxItems:             aws.String("1"),
		},
		{
			ResourceRecordSets: []*route53.ResourceRecordSet{
				{Name: aws.String("second.example.com.")},
			},
			IsTruncated:    aws.Bool(true),
			NextRecordName: aws.String("third.example.com."),
			NextRecordType: aws.String("MX"),
			MaxItems:       aws.String("1"),
		},
		{
			ResourceRecordSets: []*route53.ResourceRecordSet{
				{Name: aws.String("third.example.com.")},
			},
			IsTruncated: aws.Bool(false),
			MaxItems:    aws.String("1"),
		},
	}
	client.Handlers.Send.Clear() // mock sending
	client.Handlers.Unmarshal.Clear()
	client.Handlers.UnmarshalMeta.Clear()
	client.Handlers.ValidateResponse.Clear()

	idents := []string{}
	client.Handlers.Build.PushBack(func(r *request.Request) {
		p := r.Params.(*route53.ListResourceRecordSetsInput)
		idents = append(idents, aws.StringValue(p.StartRecordIdentifier))

	})
	client.Handlers.Unmarshal.PushBack(func(r *request.Request) {
		r.Data = resps[reqNum]
		reqNum++
	})

	params := &route53.ListResourceRecordSetsInput{
		HostedZoneId: aws.String("id-zone"),
	}

	results := []string{}
	err := client.ListResourceRecordSetsPages(params, func(p *route53.ListResourceRecordSetsOutput, last bool) bool {
		results = append(results, *p.ResourceRecordSets[0].Name)
		return true
	})

	assert.NoError(t, err)
	assert.Equal(t, []string{"", "second", ""}, idents)
	assert.Equal(t, []string{"first.example.com.", "second.example.com.", "third.example.com."}, results)
}