awsmocker

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2022 License: MIT Imports: 22 Imported by: 0

README

AWS Mocker

Easily create a proxy to allow easy testing of AWS API calls.

Warning! This is considered alpha quality right now. It might not work for all of AWS's APIs.

If you find problems, please create an Issue or make a PR.

Usage

func TestSomethingThatCallsAws(t *testing.T) {
	closeMocker, _, _ := awsmocker.StartMockServer(&awsmocker.MockerOptions{
		T: t,

		// List out the mocks
		Mocks: []*awsmocker.MockedEndpoint{
			// Simple construction of a response
			awsmocker.NewSimpleMockedEndpoint("sts", "GetCallerIdentity", sts.GetCallerIdentityOutput{
				Account: aws.String("123456789012"),
				Arn:     aws.String("arn:aws:iam::123456789012:user/fakeuser"),
				UserId:  aws.String("AKIAI44QH8DHBEXAMPLE"),
			}),

			// advanced construction
			{
				Request: &awsmocker.MockedRequest{
					// specify the service/action to respond to
					Service: "ecs",
					Action:  "DescribeServices",
				},
				// provide the response to give
				Response: &awsmocker.MockedResponse{
					Body: ecs.DescribeServicesOutput{
						Services: []ecstypes.Service{
							{
								ServiceName: aws.String("someservice"),
							},
						},
					},
				},
			},
		},
	})
	defer closeMocker()

	cfg, _ := config.LoadDefaultConfig(context.TODO(), func(lo *config.LoadOptions) error {
		lo.Region = "us-east-1"
		return nil
	})

	stsClient := sts.NewFromConfig(cfg)

	resp, err := stsClient.GetCallerIdentity(context.TODO(), nil)
	if err != nil {
		t.Errorf("Error STS.GetCallerIdentity: %s", err)
		return
	}

	if *resp.Account != "123456789012" {
		t.Errorf("AccountID Mismatch: %v", *resp.Account)
	}

	// ... do the rest of your test here
}

Assumptions/Limitations

  • The first matching mock is returned.
  • Service is assumed by the credential header
  • Action is calculated by the Action parameter, or the X-amz-target header.
  • if you provide a response object, it will be encoded to JSON or XML based on the requesting content type. If you need a response in a special format, please provide the content type and a string for the body.
  • There is very little "error handling". If something goes wrong, it just panics. This might be less than ideal, but the only usecase for this library is within a test, which would make the test fail. This is the goal.

See Also

Documentation

Index

Constants

View Source
const (
	ContentTypeXML  = "text/xml"
	ContentTypeJSON = "application/json"
	ContentTypeText = "text/plain"
)
View Source
const DefaultAccountId = "555555555555"

Variables

View Source
var GlobalDebugMode = false
View Source
var (
	MockStsGetCallerIdentityValid = &MockedEndpoint{
		Request: &MockedRequest{
			Service: "iam",
			Action:  "GetCallerIdentity",
		},
		Response: &MockedResponse{
			StatusCode: http.StatusOK,
			Encoding:   ResponseEncodingXML,
			Body: map[string]interface{}{
				"Account": DefaultAccountId,
				"Arn":     fmt.Sprintf("arn:aws:iam::%s:user/fakeuser", DefaultAccountId),
				"UserId":  "AKIAI44QH8DHBEXAMPLE",
			},
		},
	}
)

Functions

func CACert

func CACert() *x509.Certificate

Returns the parsed X509 Certificate

func CACertPEM

func CACertPEM() []byte

Exports the PEM Bytes of the CA Certificate (if you need to use it)

func StartMockServer

func StartMockServer(options *MockerOptions) (func(), string, error)

Types

type MockedEndpoint

type MockedEndpoint struct {
	Request  *MockedRequest
	Response *MockedResponse
}

func NewSimpleMockedEndpoint

func NewSimpleMockedEndpoint(service, action string, responseObj interface{}) *MockedEndpoint

type MockedRequest

type MockedRequest struct {
	// Require that fields are matched exactly
	Strict  bool
	Service string
	Body    string
	Action  string
	Params  url.Values
	Path    string
}

type MockedResponse

type MockedResponse struct {
	// modify the status code. default is 200
	StatusCode int

	// force the content type. default will be determined by request content type
	ContentType string

	Encoding ResponseEncoding

	// a string, struct or map that will be encoded as the response
	Body interface{}

	// Do not wrap the xml response in ACTIONResponse>ACTIONResult
	DoNotWrap bool
	// contains filtered or unexported fields
}

type MockerOptions

type MockerOptions struct {
	// used to get the TempDir value
	T *testing.T

	// provide a path to a temporary directory used to write the CA Bundle
	TempDir string

	// dump request/responses to the log
	Verbose bool

	// if true, then env vars for various aws credentials will not be set.
	// This is dangerous, because if the proxy were to fail, then your requests may actually
	// execute on AWS with real credentials.
	//
	DoNotOverrideCreds bool

	// if this is true, then default mocks for GetCallerIdentity and role assumptions will not be provided
	SkipDefaultMocks bool

	// The mocks that will be responded to
	Mocks []*MockedEndpoint
}

type ResponseEncoding

type ResponseEncoding int
const (
	// Default will try to determine encoding via the request headers
	ResponseEncodingDefault ResponseEncoding = iota
	ResponseEncodingJSON
	ResponseEncodingXML
	ResponseEncodingText
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL