Skip to content

Instantly share code, notes, and snippets.

@mblarsen
Last active April 19, 2019 09:35
Show Gist options
  • Save mblarsen/ff43452cdfab700e64b4318278316fe0 to your computer and use it in GitHub Desktop.
Save mblarsen/ff43452cdfab700e64b4318278316fe0 to your computer and use it in GitHub Desktop.
A small CLI wrapper + Go test wrapper for @serverless/event-mocks
func TestHandler(t *testing.T) {
req := api.Req{}
reqBody, _ := json.Marshal(map[string]interface{}{
"requestContext": map[string]interface{}{
"Authorizer": map[string]interface{}{
"claims": map[string]interface{}{
"cognito:username": "my user",
},
},
},
})
assert.MockEvent(t, "apiGateway", string(reqBody), &req)
claims := req.RequestContext.Authorizer["claims"].(map[string]interface{})
assert.Equals(t, claims["cognito:username"], "my user")
res, err := Handler(request)
// assert the response from your lambda
}
#!/usr/bin/env node
const createEvent = require("@serverless/event-mocks").default;
const type = process.argv[2];
process.stdin.resume();
process.stdin.setEncoding("utf8");
process.stdin.on("data", function(data) {
try {
data = JSON.parse(data);
process.stdout.write(JSON.stringify(createEvent(`aws:${type}`, data)));
process.exit(0);
} catch (e) {
console.log("Invalid input: " + e.message);
process.exit(1);
}
});
setTimeout(() => {
process.stdin.emit("data", "{}");
}, 50);
/* vim :set ft=js */
package assert
import (
"bytes"
"encoding/json"
"os/exec"
"path/filepath"
"runtime"
"testing"
)
// MockEvent creates a mock event of one of the following types:
// alexaSkill, alexaSmartphone, apiGateway, cloudWatch, cloudWatchLog,
// cognitoUserPool, dynamo, iot, kinesis, s3, scheduled, ses, sns, websocket
func MockEvent(t *testing.T, eventType string, body string, event interface{}) error {
t.Helper()
echo := exec.Command("echo", body)
gen := exec.Command(getGenPath(), eventType)
gen.Stdin, _ = echo.StdoutPipe()
var outBuffer bytes.Buffer
gen.Stdout = &outBuffer
_ = gen.Start()
_ = echo.Run()
_ = gen.Wait()
return json.Unmarshal(outBuffer.Bytes(), &event)
}
func getGenPath() string {
_, filename, _, _ := runtime.Caller(1)
genPath, _ := filepath.Abs(filepath.Join(filepath.Dir(filename), "../../genevent"))
return genPath
}
@mblarsen
Copy link
Author

mblarsen commented Apr 19, 2019

Example command-line usage:

echo "{\"pathParameters\":{\"proxy\": \"world\"}}" | ./genevent apiGateway

output:

{
  "body": "",
  "path": "/test/hello",
  "headers": {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Encoding": "gzip, deflate, lzma, sdch, br",
    "Accept-Language": "en-US,en;q=0.8",
    "CloudFront-Forwarded-Proto": "https",
    "CloudFront-Is-Desktop-Viewer": "true",
    "CloudFront-Is-Mobile-Viewer": "false",
    "CloudFront-Is-SmartTV-Viewer": "false",
    "CloudFront-Is-Tablet-Viewer": "false",
    "CloudFront-Viewer-Country": "US",
    "Host": "wt6mne2s9k.execute-api.us-west-2.amazonaws.com",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
    "Via": "1.1 fb7cca60f0ecd82ce07790c9c5eef16c.cloudfront.net (CloudFront)",
    "X-Amz-Cf-Id": "nBsWBOrSHMgnaROZJK1wGCZ9PcRcSpq_oSXZNQwQ10OTZL4cimZo3g==",
    "X-Forwarded-For": "192.168.100.1, 192.168.1.1",
    "X-Forwarded-Port": "443",
    "X-Forwarded-Proto": "https"
  },
  "pathParameters": {
    "proxy": "world"
  },
  "multiValueHeaders": {},
  "isBase64Encoded": false,
  "multiValueQueryStringParameters": {},
  "requestContext": {
    "accountId": "123456789012",
    "resourceId": "us4z18",
    "stage": "test",
    "requestId": "41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9",
    "identity": {
      "accessKey": "",
      "apiKeyId": "",
      "cognitoIdentityPoolId": "",
      "accountId": "",
      "cognitoIdentityId": "",
      "caller": "",
      "apiKey": "",
      "sourceIp": "192.168.100.1",
      "cognitoAuthenticationType": "",
      "cognitoAuthenticationProvider": "",
      "userArn": "",
      "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
      "user": ""
    },
    "path": "",
    "requestTimeEpoch": 0,
    "resourcePath": "/{proxy+}",
    "httpMethod": "GET",
    "apiId": "wt6mne2s9k"
  },
  "resource": "/{proxy+}",
  "httpMethod": "GET",
  "queryStringParameters": {
    "name": "me"
  },
  "stageVariables": {
    "stageVarName": "stageVarValue"
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment