我一直在研究aws lambda。人们如何测试api网关的线束请求响应?在Java中,我有一个lambda,有点像这样。
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
...
@Test
void turnsBarToFooTest() {
TestContext ctx = new TestContext(); //implements com.amazonaws.services.lambda.runtime.Context
Fooer handler = new Fooer();
APIGatewayProxyRequestEvent request = new APIGatewayProxyRequestEvent();
Map<String, String> params = HashMap.of("thing_to_foo", "bar");
request.setPathParameters(params.toJavaMap());
APIGatewayProxyResponseEvent response = handler.handleRequest(request, ctx);
assertEquals(200, response.getStatusCode().intValue());
assertEquals("foo", response.getBody());
}
我喜欢用Jest和ES6做一些非常简单的事情来复制上面的内容。是否有类似的已知事件对象?如何用开玩笑将它们连接起来。
答案 0 :(得分:1)
我在Lambda for CloudFront中创建了基于Host头添加安全头的功能。为了进行测试,我使用了JEST,并且基本上在AWS中模拟了对象。
google.test.js
:
const handler = require('../../src/functions/google').handler;
const testEventGenerator = require('./cloudfront-event-template-generator');
test('it adds xss protection', () => {
const event = testEventGenerator();
const callback = jest.fn();
handler(event, {}, callback);
expect(event.Records[0].cf.response.headers['x-xss-protection'][0].key).toBe('X-XSS-Protection');
expect(event.Records[0].cf.response.headers['x-xss-protection'][0].value).toBe('1; mode=block');
expect(callback.mock.calls.length).toBe(1);
});
cloudfront-event-template-generator.js
:
module.exports = () => ({
Records: [
{
cf: {
config: {
distributionId: 'EXAMPLE'
},
request: {
headers: {
host: [
{
key: 'host',
value: 'www.google.com'
}
]
}
},
response: {
status: 200,
headers: {
'last-modified': [
{
key: 'Last-Modified',
value: '2016-11-25'
}
],
vary: [
{
key: 'Vary',
value: '*'
}
],
'x-amz-meta-last-modified': [
{
key: 'X-Amz-Meta-Last-Modified',
value: '2016-01-01'
}
]
},
statusDescription: 'OK'
}
}
}
]
});
答案 1 :(得分:0)
我开玩笑做我想做的事。马丁对测试响应的想法会有所帮助,因为它会更加复杂,谢谢。
test('fooer will foo a bar', done => {
const context = {}
const request = {pathParameters:{thing_to_foo:'foo'}}
const callback = (bar, foo) => {
expect(foo.body).toBe('bar')
done()
}
myHandler.handler(request, context, callback)
})