Using JSON Data

Get test json

To get test data I call the real Systems Manager API with the AWS CLI. This works for most services. E.g. not for Dynamodb.

Call for putting a parameter into Systems Manager Parameter Store

aws ssm put-parameter --name "/go-on-aws/table" --type "String" --value "ordinarytablename"

get the json answer

aws ssm get-parameter --name "/go-on-aws/table"

Gives you:

{
    "Parameter": {
        "Name": "/go-on-aws/table",
        "Type": "String",
        "Value": "ordinarytablename",
        "Version": 1,
        "LastModifiedDate": "2021-12-08T18:56:47.478000+01:00",
        "ARN": "arn:aws:ssm:eu-central-1:555555555555:parameter/go-on-aws/table",
        "DataType": "text"
    }
}

Save file

Now I save the file in the subdirectory testdata, because GO ignores files inside the directory with the name “testdata”.

If i want to test for other values, I can create different files with variations of the values.

Read the file

Inside the Test function at first, the file is read:

testfile := "testdata/ssm-get-parameter.json"
		data, err := ioutil.ReadFile(testfile)
		if err != nil {
			fmt.Println("File reading error: ", err)
		}

Convert json to struct

Then the file content is converted to a struct from type GetParameterOutput:

out := &ssm.GetParameterOutput{}
	err = json.Unmarshal(data, out); 
	if err != nil {
		t.Error(err)
	}

Return struct

The mock function now returns the GetParameterOutput and nil as no-error:

	return out,nil

All together

The rest of the test code remains the same as in the previous chapter:

func TestGetTableNameFile(t *testing.T) {
	GetParameterFunc := func(ctx context.Context, params *ssm.GetParameterInput) (*ssm.GetParameterOutput, error) {	
		
		testfile := "testdata/ssm-get-parameter.json"
		data, err := ioutil.ReadFile(testfile)
		if err != nil {
			fmt.Println("File reading error: ", err)
		}
		
		out := &ssm.GetParameterOutput{}
		err = json.Unmarshal(data, out); 
		if err != nil {
			t.Error(err)
		}
		return out,nil
	}

	// Create a Mock Handler
	mockCfg := awsmock.NewAwsMockHandler()
	// add a function to the handler
	// Routing per paramater types
	mockCfg.AddHandler(GetParameterFunc)

	client := ssm.NewFromConfig(mockCfg.AwsConfig())
	name := reflection.GetTableName(client)

	assert.Equal(t, "totalfancyname",*name)
}

You can use almost any CLI output, but not DynamoDB. This is a special case…

See also

Source

See the full source on github.

Sources