Reputation: 6088
I am writing a unit test for a function that uses the AWS SDK for Go to get a secret from the AWS Secrets Manager:
main.go
//Helper function to get secret from AWS Secret Manager
func getAWSSecrets(svc secretsmanageriface.SecretsManagerAPI) (secretMap map[string]string, err error) {
//Get secret config values
req, resp := svc.GetSecretValueRequest(&secretsmanager.GetSecretValueInput{
SecretId: aws.String("my/secret/string"),
})
err = req.Send()
if err != nil {
return nil, err
}
...
}
In order to test this, I need to create a mock AWS Secret Manager Client. I've set up the basic skeleton of how that will work:
main_test.go
type MockSecretsManagerClient struct {
secretsmanageriface.SecretsManagerAPI
}
func (m *MockSecretsManagerClient) GetSecretValueRequest(input *secretsmanager.GetSecretValueInput) (req *request.Request, resp *secretsmanager.GetSecretValueOutput){
// Confused on how to mock out the returned `req`
}
// tests getAWSSecrets
func (suite *ServerTestSuite) TestGetAWSSecrets() {
//Setup test
mockSvc := &MockSecretsManagerClient{}
req, resp := getAWSSecrets(mockSvc)
}
I'm running into trouble trying to mock the returned request from GetSecretValueRequest
. Furthermore, once I mock this request, I'm not sure how to handle mocking req.Send()
. Is there a simple way to do this? Or are there any good examples of someone doing this?
Upvotes: 5
Views: 6737
Reputation: 34367
First, find the service in the "AWS SDK for Go API Reference."
Then look up the API call. Your call is here https://docs.aws.amazon.com/sdk-for-go/api/service/secretsmanager/#SecretsManager.GetSecretValueRequest
The prototype for the API call is
func (c *SecretsManager) GetSecretValueRequest(input *GetSecretValueInput) (req *request.Request, output *GetSecretValueOutput)
So it returns a request.Request and a GetSecretValueOutput
The two output items are structs and they are linked in the documentation. The mock should return those two items in the same way ie
func (m *MockSecretsManagerClient) GetSecretValueRequest(input *secretsmanager.GetSecretValueInput) (req *request.Request, resp *secretsmanager.GetSecretValueOutput) {
req = new(request.Request)
r := new(http.Response)
r.Status = "200 OK"
r.Status = 200
req.HTTPRequest = r
resp.SecretString = new(String("this is the dummy value"))
return
}
If you need the mock values to be mock like "real" data from a live API service then write a quick program to do a call and Printf
the return values using "%#v"
format. This should give you most of what you need
Upvotes: 3