With the unit test of the application we perform automated test of the application without the infrastructure. This can be done with mocked AWS calls like shown in Chapter Test using reflection or basic functions like in this example.
The application shall handle an S3 put event, so at first we generate this event and store the json. See the put event in architectures/serverless/app/test/put.json
As we only need the S3 object key from the S3 event, we write a function ExtractKey.
There are four basic steps:
const testfile = "test/put.json"
jsonFile, err := os.Open(testfile)
if err != nil {
fmt.Println(err)
panic(err)
}
fmt.Println("Successfully Opened ", testfile)
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
if err != nil {
print(err)
}
This part is quite the same most of the time. Don’t skip the if err parts, sometimes you have the wrong filepath etc etc.
var s3event events.S3Event;
err = json.Unmarshal([]byte(byteValue), &s3event)
The events are defined in github aws-lambda-go/events/. If your event is not defined, use an online json to struct website to define your own structure.
realKey := dsl.ExtractKey(s3event);
expectedKey := "my2etestkey.txt"
assert.Equal(t, expectedKey,realKey)
The key must be the same as in the event to make the test PASS:
{
"Records": [
{
...
"s3": {
...
"object": {
"key": "my2etestkey.txt",
You can guess the tested function code from the json hierarchy…
Again, the first time it may seem like a testing overkill. But the effort is not so much and you get in return:
In the next chapter the integration and end2end test are described.
See the full source on github.