index.test.ts
This file
Path
runtime-tests/lambda/index.test.ts
1,045 lines · 31.4 KiB · TypeScript
Last changed by
fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
History of this fileTake it
chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
line 1why, one step back1import { Readable } from 'stream'fix(adapter/aws-lambda): add alb event requestContext undefined check for testing convenience (#3691)Omkar Patilbefore adoption7ebf854
lines 2–9why, one step back2import {3 ALBProcessor,4 EventV1Processor,5 EventV2Processor,6 getProcessor,7 handle,8 streamHandle,9} from '../../src/adapter/aws-lambda/handler'chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
line 10why, one step back10import type {fix(adapter/aws-lambda): add alb event requestContext undefined check for testing convenience (#3691)Omkar Patilbefore adoption7ebf854
lines 11–15why, one step back11 ALBProxyEvent,12 APIGatewayProxyEventV2,13 LambdaEvent,14} from '../../src/adapter/aws-lambda/handler'15import type {chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
lines 16–251why, one step back16 ApiGatewayRequestContext,17 ApiGatewayRequestContextV2,18 LambdaContext,19} from '../../src/adapter/aws-lambda/types'20import { getCookie, setCookie } from '../../src/helper/cookie'21import { streamSSE } from '../../src/helper/streaming'22import { Hono } from '../../src/hono'23import { basicAuth } from '../../src/middleware/basic-auth'24import './mock'2526type Bindings = {27 event: LambdaEvent28 lambdaContext: LambdaContext29 requestContext: ApiGatewayRequestContext | ApiGatewayRequestContextV230}3132const testApiGatewayRequestContextV2 = {33 accountId: '123456789012',34 apiId: 'urlid',35 authentication: null,36 authorizer: {37 iam: {38 accessKey: 'AKIA...',39 accountId: '111122223333',40 callerId: 'AIDA...',41 cognitoIdentity: null,42 principalOrgId: null,43 userArn: 'arn:aws:iam::111122223333:user/example-user',44 userId: 'AIDA...',45 },46 },47 domainName: 'example.com',48 domainPrefix: '<url-id>',49 http: {50 method: 'POST',51 path: '/my/path',52 protocol: 'HTTP/1.1',53 sourceIp: '123.123.123.123',54 userAgent: 'agent',55 },56 requestId: 'id',57 routeKey: '$default',58 stage: '$default',59 time: '12/Mar/2020:19:03:58 +0000',60 timeEpoch: 1583348638390,61 customProperty: 'customValue',62}6364describe('AWS Lambda Adapter for Hono', () => {65 const app = new Hono<{ Bindings: Bindings }>()6667 app.get('/', (c) => {68 return c.text('Hello Lambda!')69 })7071 app.get('/binary', (c) => {72 return c.body('Fake Image', 200, {73 'Content-Type': 'image/png',74 })75 })7677 app.post('/post', async (c) => {78 const body = (await c.req.parseBody()) as { message: string }79 return c.text(body.message)80 })8182 app.post('/post/binary', async (c) => {83 const body = await c.req.blob()84 return c.text(`${body.size} bytes`)85 })8687 const username = 'hono-user-a'88 const password = 'hono-password-a'89 app.use('/auth/*', basicAuth({ username, password }))90 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))9192 app.get('/lambda-event', (c) => {93 const event = c.env.event94 return c.json(event)95 })9697 app.get('/lambda-context', (c) => {98 const fnctx = c.env.lambdaContext99 return c.json(fnctx)100 })101102 app.get('/custom-context/v1/apigw', (c) => {103 const lambdaContext = c.env.requestContext104 return c.json(lambdaContext)105 })106107 app.get('/custom-context/apigw', (c) => {108 const lambdaContext = c.env.event.requestContext109 return c.json(lambdaContext)110 })111112 app.get('/custom-context/v1/lambda', (c) => {113 const lambdaContext = c.env.requestContext114 return c.json(lambdaContext)115 })116117 app.get('/custom-context/lambda', (c) => {118 const lambdaContext = c.env.event.requestContext119 return c.json(lambdaContext)120 })121122 app.get('/query-params', (c) => {123 const queryParams = c.req.query()124 return c.json(queryParams)125 })126127 app.get('/multi-query-params', (c) => {128 const multiQueryParams = c.req.queries()129 return c.json(multiQueryParams)130 })131132 const testCookie1 = {133 key: 'id',134 value: crypto.randomUUID(),135 get serialized() {136 return `${this.key}=${this.value}; Path=/`137 },138 }139 const testCookie2 = {140 key: 'secret',141 value: crypto.randomUUID(),142 get serialized() {143 return `${this.key}=${this.value}; Path=/`144 },145 }146147 app.post('/cookie', (c) => {148 setCookie(c, testCookie1.key, testCookie1.value)149 setCookie(c, testCookie2.key, testCookie2.value)150 return c.text('Cookies Set')151 })152153 app.get('/cookie', (c) => {154 const validCookies =155 getCookie(c, testCookie1.key) === testCookie1.value &&156 getCookie(c, testCookie2.key) === testCookie2.value157 if (!validCookies) {158 return c.text('Invalid Cookies')159 }160 return c.text('Valid Cookies')161 })162163 app.post('/headers', (c) => {164 if (c.req.header('foo')?.includes('bar')) {165 return c.json({ message: 'ok' })166 }167 return c.json({ message: 'fail' }, 400)168 })169170 const handler = handle(app)171172 const testApiGatewayRequestContext = {173 accountId: '123456789012',174 apiId: 'id',175 authorizer: {176 claims: null,177 scopes: null,178 },179 domainName: 'example.com',180 domainPrefix: 'id',181 extendedRequestId: 'request-id',182 httpMethod: 'GET',183 identity: {184 sourceIp: 'IP',185 userAgent: 'user-agent',186 },187 path: '/my/path',188 protocol: 'HTTP/1.1',189 requestId: 'id=',190 requestTime: '04/Mar/2020:19:15:17 +0000',191 requestTimeEpoch: 1583349317135,192 resourcePath: '/',193 stage: '$default',194 customProperty: 'customValue',195 }196197 const testApiGatewayRequestContextV2 = {198 accountId: '123456789012',199 apiId: 'urlid',200 authentication: null,201 authorizer: {202 iam: {203 accessKey: 'AKIA...',204 accountId: '111122223333',205 callerId: 'AIDA...',206 cognitoIdentity: null,207 principalOrgId: null,208 userArn: 'arn:aws:iam::111122223333:user/example-user',209 userId: 'AIDA...',210 },211 },212 domainName: 'example.com',213 domainPrefix: '<url-id>',214 http: {215 method: 'POST',216 path: '/my/path',217 protocol: 'HTTP/1.1',218 sourceIp: '123.123.123.123',219 userAgent: 'agent',220 },221 requestId: 'id',222 routeKey: '$default',223 stage: '$default',224 time: '12/Mar/2020:19:03:58 +0000',225 timeEpoch: 1583348638390,226 customProperty: 'customValue',227 }228229 const testALBRequestContext = {230 elb: {231 targetGroupArn:232 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',233 },234 }235236 it('Should handle a GET request and return a 200 response', async () => {237 const event = {238 version: '1.0',239 resource: '/',240 httpMethod: 'GET',241 headers: { 'content-type': 'text/plain' },242 path: '/',243 body: null,244 isBase64Encoded: false,245 requestContext: testApiGatewayRequestContext,246 }247248 const response = await handler(event)249 expect(response.statusCode).toBe(200)250 expect(response.body).toBe('Hello Lambda!')251 expect(response.headers['content-type']).toMatch(/^text\/plain/)fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
line 252why, one step back252 expect(response.multiValueHeaders).toBeUndefined()chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
lines 253–271why, one step back253 expect(response.isBase64Encoded).toBe(false)254 })255256 it('Should handle a GET request and return a 200 response with binary', async () => {257 const event = {258 version: '1.0',259 resource: '/binary',260 httpMethod: 'GET',261 headers: {},262 path: '/binary',263 body: null,264 isBase64Encoded: false,265 requestContext: testApiGatewayRequestContext,266 }267268 const response = await handler(event)269 expect(response.statusCode).toBe(200)270 expect(response.body).toBe('RmFrZSBJbWFnZQ==')271 expect(response.headers['content-type']).toMatch(/^image\/png/)fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
line 272why, one step back272 expect(response.multiValueHeaders).toBeUndefined()chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
lines 273–293why, one step back273 expect(response.isBase64Encoded).toBe(true)274 })275276 it('Should handle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {277 const event = {278 version: '2.0',279 routeKey: '$default',280 headers: { 'content-type': 'text/plain' },281 rawPath: '/',282 rawQueryString: '',283 body: null,284 isBase64Encoded: false,285 requestContext: testApiGatewayRequestContextV2,286 }287288 testApiGatewayRequestContextV2.http.method = 'GET'289290 const response = await handler(event)291 expect(response.statusCode).toBe(200)292 expect(response.body).toBe('Hello Lambda!')293 expect(response.headers['content-type']).toMatch(/^text\/plain/)fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
line 294why, one step back294 expect(response.multiValueHeaders).toBeUndefined()chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
lines 295–314why, one step back295 expect(response.isBase64Encoded).toBe(false)296 })297298 it('Should handle a GET request and return a 200 response (ALBEvent)', async () => {299 const event = {300 headers: { 'content-type': 'text/plain' },301 httpMethod: 'GET',302 path: '/',303 queryStringParameters: {304 query: '1234ABCD',305 },306 body: null,307 isBase64Encoded: false,308 requestContext: testALBRequestContext,309 }310311 const response = await handler(event)312 expect(response.statusCode).toBe(200)313 expect(response.body).toBe('Hello Lambda!')314 expect(response.headers['content-type']).toMatch(/^text\/plain/)fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
line 315why, one step back315 expect(response.multiValueHeaders).toBeUndefined()chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
lines 316–543why, one step back316 expect(response.isBase64Encoded).toBe(false)317 })318319 it('Should handle a GET request and return a 404 response', async () => {320 const event = {321 version: '1.0',322 resource: '/nothing',323 httpMethod: 'GET',324 headers: { 'content-type': 'text/plain' },325 path: '/nothing',326 body: null,327 isBase64Encoded: false,328 requestContext: testApiGatewayRequestContext,329 }330331 const response = await handler(event)332 expect(response.statusCode).toBe(404)333 })334335 it('Should handle a POST request and return a 200 response', async () => {336 const searchParam = new URLSearchParams()337 searchParam.append('message', 'Good Morning Lambda!')338 const event = {339 version: '1.0',340 resource: '/post',341 httpMethod: 'POST',342 headers: {343 'Content-Type': 'application/x-www-form-urlencoded',344 },345 path: '/post',346 body: Buffer.from(searchParam.toString()).toString('base64'),347 isBase64Encoded: true,348 requestContext: testApiGatewayRequestContext,349 }350351 const response = await handler(event)352 expect(response.statusCode).toBe(200)353 expect(response.body).toBe('Good Morning Lambda!')354 })355356 it('Should handle a POST request and return a 200 response (LambdaFunctionUrlEvent)', async () => {357 const searchParam = new URLSearchParams()358 searchParam.append('message', 'Good Morning Lambda!')359 const event = {360 version: '2.0',361 routeKey: '$default',362 headers: {363 'Content-Type': 'application/x-www-form-urlencoded',364 },365 rawPath: '/post',366 rawQueryString: '',367 body: Buffer.from(searchParam.toString()).toString('base64'),368 isBase64Encoded: true,369 requestContext: testApiGatewayRequestContextV2,370 }371372 testApiGatewayRequestContextV2.http.method = 'POST'373374 const response = await handler(event)375 expect(response.statusCode).toBe(200)376 expect(response.body).toBe('Good Morning Lambda!')377 })378379 it('Should handle a POST request with binary and return a 200 response', async () => {380 const array = new Uint8Array([0xc0, 0xff, 0xee])381 const buffer = Buffer.from(array)382 const event = {383 version: '1.0',384 resource: '/post/binary',385 httpMethod: 'POST',386 headers: {387 'Content-Type': 'application/x-www-form-urlencoded',388 },389 path: '/post/binary',390 body: buffer.toString('base64'),391 isBase64Encoded: true,392 requestContext: testApiGatewayRequestContext,393 }394395 const response = await handler(event)396 expect(response.statusCode).toBe(200)397 expect(response.body).toBe('3 bytes')398 })399400 it('Should handle a request and return a 401 response with Basic auth', async () => {401 const event = {402 version: '1.0',403 resource: '/auth/abc',404 httpMethod: 'GET',405 headers: {406 'Content-Type': 'plain/text',407 },408 path: '/auth/abc',409 body: null,410 isBase64Encoded: true,411 requestContext: testApiGatewayRequestContext,412 }413414 const response = await handler(event)415 expect(response.statusCode).toBe(401)416 })417418 it('Should handle a request and return a 200 response with Basic auth', async () => {419 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'420 const event = {421 version: '1.0',422 resource: '/auth/abc',423 httpMethod: 'GET',424 headers: {425 'Content-Type': 'plain/text',426 Authorization: `Basic ${credential}`,427 },428 path: '/auth/abc',429 body: null,430 isBase64Encoded: true,431 requestContext: testApiGatewayRequestContext,432 }433434 const response = await handler(event)435 expect(response.statusCode).toBe(200)436 expect(response.body).toBe('Good Night Lambda!')437 })438439 it('Should handle a GET request and return custom context', async () => {440 const event = {441 version: '1.0',442 resource: '/custom-context/apigw',443 httpMethod: 'GET',444 headers: { 'content-type': 'application/json' },445 path: '/custom-context/apigw',446 body: null,447 isBase64Encoded: false,448 requestContext: testApiGatewayRequestContext,449 }450451 const response = await handler(event)452 expect(response.statusCode).toBe(200)453 expect(JSON.parse(response.body).customProperty).toEqual('customValue')454 })455456 it('Should handle a GET request and context', async () => {457 const event = {458 version: '1.0',459 resource: '/lambda-context',460 httpMethod: 'GET',461 headers: { 'content-type': 'application/json' },462 path: '/lambda-context',463 body: null,464 isBase64Encoded: false,465 requestContext: testApiGatewayRequestContext,466 }467 const context: LambdaContext = {468 callbackWaitsForEmptyEventLoop: false,469 functionName: 'myLambdaFunction',470 functionVersion: '1.0.0',471 invokedFunctionArn: 'arn:aws:lambda:us-west-2:123456789012:function:myLambdaFunction',472 memoryLimitInMB: '128',473 awsRequestId: 'c6af9ac6-a7b0-11e6-80f5-76304dec7eb7',474 logGroupName: '/aws/lambda/myLambdaFunction',475 logStreamName: '2016/11/14/[$LATEST]f2d4b21cfb33490da2e8f8ef79a483s4',476 getRemainingTimeInMillis: () => {477 return 60000 // 60 seconds478 },479 }480 const response = await handler(event, context)481 expect(response.statusCode).toBe(200)482 expect(JSON.parse(response.body).callbackWaitsForEmptyEventLoop).toEqual(false)483 })484485 it('Should handle a POST request and return a 200 response with cookies set (APIGatewayProxyEvent V1 and V2)', async () => {486 const apiGatewayEvent = {487 version: '1.0',488 resource: '/cookie',489 httpMethod: 'POST',490 headers: { 'content-type': 'text/plain' },491 path: '/cookie',492 body: null,493 isBase64Encoded: false,494 requestContext: testApiGatewayRequestContext,495 }496497 const apiGatewayResponse = await handler(apiGatewayEvent)498499 expect(apiGatewayResponse.statusCode).toBe(200)500 expect(apiGatewayResponse.multiValueHeaders).toHaveProperty('set-cookie', [501 testCookie1.serialized,502 testCookie2.serialized,503 ])504505 const apiGatewayEventV2 = {506 version: '2.0',507 routeKey: '$default',508 httpMethod: 'POST',509 headers: { 'content-type': 'text/plain' },510 rawPath: '/cookie',511 rawQueryString: '',512 body: null,513 isBase64Encoded: false,514 requestContext: testApiGatewayRequestContextV2,515 }516517 const apiGatewayResponseV2 = await handler(apiGatewayEventV2)518519 expect(apiGatewayResponseV2.statusCode).toBe(200)520 expect(apiGatewayResponseV2).toHaveProperty('cookies', [521 testCookie1.serialized,522 testCookie2.serialized,523 ])524 })525526 describe('headers', () => {527 describe('single-value headers', () => {528 it('Should extract single-value headers and return 200 (ALBProxyEvent)', async () => {529 const event = {530 body: '{}',531 httpMethod: 'POST',532 isBase64Encoded: false,533 path: '/headers',534 headers: {535 host: 'localhost',536 foo: 'bar',537 },538 requestContext: testALBRequestContext,539 }540 const albResponse = await handler(event)541 expect(albResponse.statusCode).toBe(200)542 expect(albResponse.headers).toEqual(543 expect.objectContaining({fix: Remove `charset` parameter from MIME type of `application/json` (#3743)SaekiTominagabefore adoptionbaa231e
line 544why, one step back544 'content-type': 'application/json',chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
lines 545–546why, one step back545 })546 )fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
line 547why, one step back547 expect(albResponse.multiValueHeaders).toBeUndefined()chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
lines 548–605why, one step back548 })549550 it('Should extract single-value headers and return 200 (APIGatewayProxyEvent)', async () => {551 const apigatewayProxyEvent = {552 version: '1.0',553 resource: '/headers',554 httpMethod: 'POST',555 headers: {556 host: 'localhost',557 foo: 'bar',558 },559 path: '/headers',560 body: null,561 isBase64Encoded: false,562 requestContext: testApiGatewayRequestContext,563 }564 const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)565 expect(apiGatewayResponseV2.statusCode).toBe(200)566 })567568 it('Should extract single-value headers and return 200 (APIGatewayProxyEventV2)', async () => {569 const apigatewayProxyV2Event = {570 version: '2.0',571 routeKey: '$default',572 headers: {573 host: 'localhost',574 foo: 'bar',575 },576 rawPath: '/headers',577 rawQueryString: '',578 requestContext: testApiGatewayRequestContextV2,579 resource: '/headers',580 body: null,581 isBase64Encoded: false,582 }583 const apiGatewayResponseV2 = await handler(apigatewayProxyV2Event)584 expect(apiGatewayResponseV2.statusCode).toBe(200)585 })586 })587588 describe('multi-value headers', () => {589 it('Should extract multi-value headers and return 200 (ALBProxyEvent)', async () => {590 const event = {591 body: '{}',592 httpMethod: 'POST',593 isBase64Encoded: false,594 path: '/headers',595 multiValueHeaders: {596 host: ['localhost'],597 foo: ['bar'],598 },599 requestContext: testALBRequestContext,600 }601 const albResponse = await handler(event)602 expect(albResponse.statusCode).toBe(200)603 expect(albResponse.multiValueHeaders).toBeDefined()604 expect(albResponse.multiValueHeaders).toEqual(605 expect.objectContaining({fix: Remove `charset` parameter from MIME type of `application/json` (#3743)SaekiTominagabefore adoptionbaa231e
line 606why, one step back606 'content-type': ['application/json'],chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
lines 607–694why, one step back607 })608 )609 })610611 it('Should extract multi-value headers and return 200 (APIGatewayProxyEvent)', async () => {612 const apigatewayProxyEvent = {613 version: '1.0',614 resource: '/headers',615 httpMethod: 'POST',616 headers: {},617 multiValueHeaders: {618 host: ['localhost'],619 foo: ['bar'],620 },621 path: '/headers',622 body: null,623 isBase64Encoded: false,624 requestContext: testApiGatewayRequestContext,625 }626 const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)627 expect(apiGatewayResponseV2.statusCode).toBe(200)628 })629 })630 })631632 it('Should handle a POST request and return a 200 response if cookies match (APIGatewayProxyEvent V1 and V2)', async () => {633 const apiGatewayEvent = {634 version: '1.0',635 resource: '/cookie',636 httpMethod: 'GET',637 headers: {638 'content-type': 'text/plain',639 cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),640 },641 path: '/cookie',642 body: null,643 isBase64Encoded: false,644 requestContext: testApiGatewayRequestContext,645 }646647 const apiGatewayResponse = await handler(apiGatewayEvent)648649 expect(apiGatewayResponse.statusCode).toBe(200)650 expect(apiGatewayResponse.body).toBe('Valid Cookies')651 expect(apiGatewayResponse.headers['content-type']).toMatch(/^text\/plain/)652 expect(apiGatewayResponse.isBase64Encoded).toBe(false)653654 const apiGatewayEventV2 = {655 version: '2.0',656 routeKey: '$default',657 headers: { 'content-type': 'text/plain' },658 rawPath: '/cookie',659 cookies: [testCookie1.serialized, testCookie2.serialized],660 rawQueryString: '',661 body: null,662 isBase64Encoded: false,663 requestContext: testApiGatewayRequestContextV2,664 }665 testApiGatewayRequestContextV2.http.method = 'GET'666667 const apiGatewayResponseV2 = await handler(apiGatewayEventV2)668669 expect(apiGatewayResponseV2.statusCode).toBe(200)670 expect(apiGatewayResponseV2.body).toBe('Valid Cookies')671 expect(apiGatewayResponseV2.headers['content-type']).toMatch(/^text\/plain/)672 expect(apiGatewayResponseV2.isBase64Encoded).toBe(false)673 })674675 it('Should handle a GET request and return a 200 response if cookies match (ALBProxyEvent) with default headers', async () => {676 const albEventDefaultHeaders = {677 version: '1.0',678 resource: '/cookie',679 httpMethod: 'GET',680 headers: {681 'content-type': 'text/plain',682 cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),683 },684 path: '/cookie',685 body: null,686 isBase64Encoded: false,687 requestContext: testALBRequestContext,688 }689690 const albResponse = await handler(albEventDefaultHeaders)691692 expect(albResponse.statusCode).toBe(200)693 expect(albResponse.body).toBe('Valid Cookies')694 expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
line 695why, one step back695 expect(albResponse.multiValueHeaders).toBeUndefined()chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
lines 696–717why, one step back696 expect(albResponse.isBase64Encoded).toBe(false)697 })698699 it('Should handle a GET request and return a 200 response if cookies match (ALBProxyEvent) with multi value headers', async () => {700 const albEventMultiValueHeaders = {701 version: '1.0',702 resource: '/cookie',703 httpMethod: 'GET',704 multiValueHeaders: {705 'content-type': ['text/plain'],706 cookie: [testCookie1.serialized, testCookie2.serialized],707 },708 path: '/cookie',709 body: null,710 isBase64Encoded: false,711 requestContext: testALBRequestContext,712 }713714 const albResponse = await handler(albEventMultiValueHeaders)715716 expect(albResponse.statusCode).toBe(200)717 expect(albResponse.body).toBe('Valid Cookies')fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
lines 718–721why, one step back718 expect(albResponse.headers).toBeUndefined()719 expect(albResponse.multiValueHeaders['content-type']).toEqual([720 expect.stringMatching(/^text\/plain/),721 ])chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
lines 722–770why, one step back722 expect(albResponse.isBase64Encoded).toBe(false)723 })724725 it('Should handle a POST request and return a 200 response with cookies (ALBProxyEvent) with default headers', async () => {726 const albEventDefaultHeaders = {727 version: '1.0',728 resource: '/cookie',729 httpMethod: 'POST',730 headers: {731 'content-type': 'text/plain',732 cookie: [testCookie1.serialized, testCookie2.serialized].join(', '),733 },734 path: '/cookie',735 body: null,736 isBase64Encoded: false,737 requestContext: testALBRequestContext,738 }739740 const albResponse = await handler(albEventDefaultHeaders)741742 expect(albResponse.statusCode).toBe(200)743 expect(albResponse.body).toBe('Cookies Set')744 expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)745 expect(albResponse.multiValueHeaders).toBeUndefined()746 expect(albResponse.headers['set-cookie']).toEqual(747 [testCookie1.serialized, testCookie2.serialized].join(', ')748 )749 expect(albResponse.isBase64Encoded).toBe(false)750 })751752 it('Should handle a POST request and return a 200 response with cookies (ALBProxyEvent) with multi value headers', async () => {753 const albEventDefaultHeaders = {754 version: '1.0',755 resource: '/cookie',756 httpMethod: 'POST',757 multiValueHeaders: {758 'content-type': ['text/plain'],759 cookie: [testCookie1.serialized, testCookie2.serialized],760 },761 path: '/cookie',762 body: null,763 isBase64Encoded: false,764 requestContext: testALBRequestContext,765 }766767 const albResponse = await handler(albEventDefaultHeaders)768769 expect(albResponse.statusCode).toBe(200)770 expect(albResponse.body).toBe('Cookies Set')fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
lines 771–772why, one step back771 expect(albResponse.headers).toBeUndefined()772 expect(albResponse.multiValueHeaders['set-cookie']).toEqual(chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
lines 773–804why, one step back773 expect.arrayContaining([testCookie1.serialized, testCookie2.serialized])774 )775 expect(albResponse.isBase64Encoded).toBe(false)776 })777778 it('Should handle a GET request and return a 200 response with queryStringParameters (ALBProxyEvent)', async () => {779 const albEventDefaultHeaders = {780 resource: '/query-params',781 httpMethod: 'GET',782 headers: {783 'content-type': 'application/json',784 },785 queryStringParameters: {786 key1: 'value1',787 key2: 'value2',788 },789 path: '/query-params',790 body: null,791 isBase64Encoded: false,792 requestContext: testALBRequestContext,793 }794795 const albResponse = await handler(albEventDefaultHeaders)796797 expect(albResponse.statusCode).toBe(200)798 expect(albResponse.body).toContain(799 JSON.stringify({800 key1: 'value1',801 key2: 'value2',802 })803 )804 expect(albResponse.headers['content-type']).toMatch(/^application\/json/)fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
line 805why, one step back805 expect(albResponse.multiValueHeaders).toBeUndefined()chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
lines 806–834why, one step back806 expect(albResponse.isBase64Encoded).toBe(false)807 })808809 it('Should handle a GET request and return a 200 response with single value multiQueryStringParameters (ALBProxyEvent)', async () => {810 const albEventDefaultHeaders = {811 resource: '/query-params',812 httpMethod: 'GET',813 multiValueHeaders: {814 'content-type': ['application/json'],815 },816 multiValueQueryStringParameters: {817 key1: ['value1'],818 key2: ['value2'],819 },820 path: '/query-params',821 body: null,822 isBase64Encoded: false,823 requestContext: testALBRequestContext,824 }825826 const albResponse = await handler(albEventDefaultHeaders)827828 expect(albResponse.statusCode).toBe(200)829 expect(albResponse.body).toContain(830 JSON.stringify({831 key1: 'value1',832 key2: 'value2',833 })834 )fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
lines 835–838why, one step back835 expect(albResponse.headers).toBeUndefined()836 expect(albResponse.multiValueHeaders['content-type']).toEqual([837 expect.stringMatching(/^application\/json/),838 ])chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
lines 839–867why, one step back839 expect(albResponse.isBase64Encoded).toBe(false)840 })841842 it('Should handle a GET request and return a 200 response with multi value multiQueryStringParameters (ALBProxyEvent)', async () => {843 const albEventDefaultHeaders = {844 resource: '/query-params',845 httpMethod: 'GET',846 multiValueHeaders: {847 'content-type': ['application/json'],848 },849 multiValueQueryStringParameters: {850 key1: ['value1'],851 key2: ['value2', 'otherValue2'],852 },853 path: '/multi-query-params',854 body: null,855 isBase64Encoded: false,856 requestContext: testALBRequestContext,857 }858859 const albResponse = await handler(albEventDefaultHeaders)860861 expect(albResponse.statusCode).toBe(200)862 expect(albResponse.body).toContain(863 JSON.stringify({864 key1: ['value1'],865 key2: ['value2', 'otherValue2'],866 })867 )fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
lines 868–871why, one step back868 expect(albResponse.headers).toBeUndefined()869 expect(albResponse.multiValueHeaders['content-type']).toEqual([870 expect.stringMatching(/^application\/json/),871 ])chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
lines 872–993why, one step back872 expect(albResponse.isBase64Encoded).toBe(false)873 })874})875876describe('streamHandle function', () => {877 const app = new Hono<{ Bindings: Bindings }>()878879 app.get('/', (c) => {880 return c.text('Hello Lambda!')881 })882883 app.get('/stream/text', async (c) => {884 return c.streamText(async (stream) => {885 for (let i = 0; i < 3; i++) {886 await stream.writeln(`${i}`)887 await stream.sleep(1)888 }889 })890 })891892 app.get('/sse', async (c) => {893 return streamSSE(c, async (stream) => {894 let id = 0895 const maxIterations = 2896897 while (id < maxIterations) {898 const message = `Message\nIt is ${id}`899 await stream.writeSSE({ data: message, event: 'time-update', id: String(id++) })900 await stream.sleep(10)901 }902 })903 })904905 const handler = streamHandle(app)906907 it('Should streamHandle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {908 const event = {909 headers: { 'content-type': ' binary/octet-stream' },910 rawPath: '/stream/text',911 rawQueryString: '',912 body: null,913 isBase64Encoded: false,914 requestContext: testApiGatewayRequestContextV2,915 }916917 testApiGatewayRequestContextV2.http.method = 'GET'918919 const mockReadableStream = new Readable({920 // eslint-disable-next-line @typescript-eslint/no-empty-function921 read() {},922 })923924 mockReadableStream.push('0\n')925 mockReadableStream.push('1\n')926 mockReadableStream.push('2\n')927 mockReadableStream.push('3\n')928 mockReadableStream.push(null) // EOF929930 await handler(event, mockReadableStream)931932 const chunks = []933 for await (const chunk of mockReadableStream) {934 chunks.push(chunk)935 }936 expect(chunks.join('')).toContain('0\n1\n2\n3\n')937 })938939 it('Should handle a GET request for an SSE stream and return the correct chunks', async () => {940 const event = {941 headers: { 'content-type': 'text/event-stream' },942 rawPath: '/sse',943 rawQueryString: '',944 body: null,945 isBase64Encoded: false,946 requestContext: testApiGatewayRequestContextV2,947 }948949 testApiGatewayRequestContextV2.http.method = 'GET'950951 const mockReadableStream = new Readable({952 // eslint-disable-next-line @typescript-eslint/no-empty-function953 read() {},954 })955956 const initContentType = {957 'Content-Type': 'application/vnd.awslambda.http-integration-response',958 }959 mockReadableStream.push(JSON.stringify(initContentType))960961 // Send JSON formatted response headers, followed by 8 NULL characters as a separator962 const httpResponseMetadata = {963 statusCode: 200,964 headers: { 'Custom-Header': 'value' },965 cookies: ['session=abcd1234'],966 }967 const jsonResponsePrelude = JSON.stringify(httpResponseMetadata) + Buffer.alloc(8, 0).toString()968 mockReadableStream.push(jsonResponsePrelude)969970 mockReadableStream.push('data: Message\ndata: It is 0\n\n')971 mockReadableStream.push('data: Message\ndata: It is 1\n\n')972 mockReadableStream.push(null) // EOF973974 await handler(event, mockReadableStream)975976 const chunks = []977 for await (const chunk of mockReadableStream) {978 chunks.push(chunk)979 }980981 // If you have chunks, you might want to convert them to strings before checking982 const output = Buffer.concat(chunks).toString()983 expect(output).toContain('data: Message\ndata: It is 0\n\n')984 expect(output).toContain('data: Message\ndata: It is 1\n\n')985986 // Assertions for the newly added header and prelude987 expect(output).toContain('application/vnd.awslambda.http-integration-response')988 expect(output).toContain('Custom-Header')989 expect(output).toContain('session=abcd1234')990991 // Check for JSON prelude and NULL sequence992 const nullSequence = '\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000'993 expect(output).toContain(jsonResponsePrelude.replace(nullSequence, ''))fix(adapter/aws-lambda): add alb event requestContext undefined check for testing convenience (#3691)Omkar Patilbefore adoption7ebf854
lines 994–1043why, one step back994 })995})996997describe('getProcessor function', () => {998 it('Should return ALBProcessor for an ALBProxyEvent event', () => {999 const event: ALBProxyEvent = {1000 httpMethod: 'GET',1001 path: '/',1002 body: null,1003 isBase64Encoded: false,1004 requestContext: {1005 elb: {1006 targetGroupArn:1007 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',1008 },1009 },1010 }10111012 const processor = getProcessor(event)1013 expect(processor).toBeInstanceOf(ALBProcessor)1014 })10151016 it('Should return EventV1Processor for an event without requestContext', () => {1017 const event = {1018 httpMethod: 'GET',1019 path: '/',1020 body: null,1021 isBase64Encoded: false,1022 }10231024 // while LambdaEvent RequestContext property is mandatory, it can be absent when testing through invoke-api or AWS Console1025 // in such cases, a V1 processor should be returned1026 const processor = getProcessor(event as unknown as LambdaEvent)1027 expect(processor).toBeInstanceOf(EventV1Processor)1028 })10291030 it('Should return EventV2Processor for an APIGatewayProxyEventV2 event', () => {1031 const event: APIGatewayProxyEventV2 = {1032 version: '2.0',1033 routeKey: '$default',1034 headers: { 'content-type': 'text/plain' },1035 rawPath: '/',1036 rawQueryString: '',1037 body: null,1038 isBase64Encoded: false,1039 requestContext: testApiGatewayRequestContextV2,1040 }10411042 const processor = getProcessor(event)1043 expect(processor).toBeInstanceOf(EventV2Processor)chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717
lines 1044–1045why, one step back1044 })1045})