index.test.ts
This file
Path
runtime_tests/lambda/index.test.ts
657 lines 路 19.3 KiB 路 TypeScript
Last changed by
chore(lint): set `curly` rule as `all` (#2112)Yusuke Wadabefore adoptionf616ed9
History of this fileTake it
1import { Readable } from 'stream'2import type {3 ApiGatewayRequestContext,4 ApiGatewayRequestContextV2,5} from '../../src/adapter/aws-lambda/custom-context'6import { handle, streamHandle } from '../../src/adapter/aws-lambda/handler'7import type { LambdaEvent } from '../../src/adapter/aws-lambda/handler'8import type { LambdaContext } from '../../src/adapter/aws-lambda/types'9import { getCookie, setCookie } from '../../src/helper/cookie'10import { streamSSE } from '../../src/helper/streaming'11import { Hono } from '../../src/hono'12import { basicAuth } from '../../src/middleware/basic-auth'13import './mock'1415type Bindings = {16 event: LambdaEvent17 lambdaContext: LambdaContext18 requestContext: ApiGatewayRequestContext | ApiGatewayRequestContextV219}2021const testApiGatewayRequestContextV2 = {22 accountId: '123456789012',23 apiId: 'urlid',24 authentication: null,25 authorizer: {26 iam: {27 accessKey: 'AKIA...',28 accountId: '111122223333',29 callerId: 'AIDA...',30 cognitoIdentity: null,31 principalOrgId: null,32 userArn: 'arn:aws:iam::111122223333:user/example-user',33 userId: 'AIDA...',34 },35 },36 domainName: 'example.com',37 domainPrefix: '<url-id>',38 http: {39 method: 'POST',40 path: '/my/path',41 protocol: 'HTTP/1.1',42 sourceIp: '123.123.123.123',43 userAgent: 'agent',44 },45 requestId: 'id',46 routeKey: '$default',47 stage: '$default',48 time: '12/Mar/2020:19:03:58 +0000',49 timeEpoch: 1583348638390,50 customProperty: 'customValue',51}5253describe('AWS Lambda Adapter for Hono', () => {54 const app = new Hono<{ Bindings: Bindings }>()5556 app.get('/', (c) => {57 return c.text('Hello Lambda!')58 })5960 app.get('/binary', (c) => {61 return c.body('Fake Image', 200, {62 'Content-Type': 'image/png',63 })64 })6566 app.post('/post', async (c) => {67 const body = (await c.req.parseBody()) as { message: string }68 return c.text(body.message)69 })7071 app.post('/post/binary', async (c) => {72 const body = await c.req.blob()73 return c.text(`${body.size} bytes`)74 })7576 const username = 'hono-user-a'77 const password = 'hono-password-a'78 app.use('/auth/*', basicAuth({ username, password }))79 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))8081 app.get('/lambda-event', (c) => {82 const event = c.env.event83 return c.json(event)84 })8586 app.get('/lambda-context', (c) => {87 const fnctx = c.env.lambdaContext88 return c.json(fnctx)89 })9091 app.get('/custom-context/v1/apigw', (c) => {92 const lambdaContext = c.env.requestContext93 return c.json(lambdaContext)94 })9596 app.get('/custom-context/apigw', (c) => {97 const lambdaContext = c.env.event.requestContext98 return c.json(lambdaContext)99 })100101 app.get('/custom-context/v1/lambda', (c) => {102 const lambdaContext = c.env.requestContext103 return c.json(lambdaContext)104 })105106 app.get('/custom-context/lambda', (c) => {107 const lambdaContext = c.env.event.requestContext108 return c.json(lambdaContext)109 })110111 const testCookie1 = {112 key: 'id',113 value: crypto.randomUUID(),114 get serialized() {115 return `${this.key}=${this.value}; Path=/`116 },117 }118 const testCookie2 = {119 key: 'secret',120 value: crypto.randomUUID(),121 get serialized() {122 return `${this.key}=${this.value}; Path=/`123 },124 }125126 app.post('/cookie', (c) => {127 setCookie(c, testCookie1.key, testCookie1.value)128 setCookie(c, testCookie2.key, testCookie2.value)129 return c.text('Cookies Set')130 })131132 app.get('/cookie', (c) => {133 const validCookies =134 getCookie(c, testCookie1.key) === testCookie1.value &&135 getCookie(c, testCookie2.key) === testCookie2.value136 if (!validCookies) {137 return c.text('Invalid Cookies')138 }139 return c.text('Valid Cookies')140 })141142 const handler = handle(app)143144 const testApiGatewayRequestContext = {145 accountId: '123456789012',146 apiId: 'id',147 authorizer: {148 claims: null,149 scopes: null,150 },151 domainName: 'example.com',152 domainPrefix: 'id',153 extendedRequestId: 'request-id',154 httpMethod: 'GET',155 identity: {156 sourceIp: 'IP',157 userAgent: 'user-agent',158 },159 path: '/my/path',160 protocol: 'HTTP/1.1',161 requestId: 'id=',162 requestTime: '04/Mar/2020:19:15:17 +0000',163 requestTimeEpoch: 1583349317135,164 resourcePath: '/',165 stage: '$default',166 customProperty: 'customValue',167 }168169 const testApiGatewayRequestContextV2 = {170 accountId: '123456789012',171 apiId: 'urlid',172 authentication: null,173 authorizer: {174 iam: {175 accessKey: 'AKIA...',176 accountId: '111122223333',177 callerId: 'AIDA...',178 cognitoIdentity: null,179 principalOrgId: null,180 userArn: 'arn:aws:iam::111122223333:user/example-user',181 userId: 'AIDA...',182 },183 },184 domainName: 'example.com',185 domainPrefix: '<url-id>',186 http: {187 method: 'POST',188 path: '/my/path',189 protocol: 'HTTP/1.1',190 sourceIp: '123.123.123.123',191 userAgent: 'agent',192 },193 requestId: 'id',194 routeKey: '$default',195 stage: '$default',196 time: '12/Mar/2020:19:03:58 +0000',197 timeEpoch: 1583348638390,198 customProperty: 'customValue',199 }200201 const testALBRequestContext = {202 elb: {203 targetGroupArn:204 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',205 },206 }207208 it('Should handle a GET request and return a 200 response', async () => {209 const event = {210 version: '1.0',211 resource: '/',212 httpMethod: 'GET',213 headers: { 'content-type': 'text/plain' },214 path: '/',215 body: null,216 isBase64Encoded: false,217 requestContext: testApiGatewayRequestContext,218 }219220 const response = await handler(event)221 expect(response.statusCode).toBe(200)222 expect(response.body).toBe('Hello Lambda!')223 expect(response.headers['content-type']).toMatch(/^text\/plain/)224 expect(response.isBase64Encoded).toBe(false)225 })226227 it('Should handle a GET request and return a 200 response with binary', async () => {228 const event = {229 version: '1.0',230 resource: '/binary',231 httpMethod: 'GET',232 headers: {},233 path: '/binary',234 body: null,235 isBase64Encoded: false,236 requestContext: testApiGatewayRequestContext,237 }238239 const response = await handler(event)240 expect(response.statusCode).toBe(200)241 expect(response.body).toBe('RmFrZSBJbWFnZQ==')242 expect(response.headers['content-type']).toMatch(/^image\/png/)243 expect(response.isBase64Encoded).toBe(true)244 })245246 it('Should handle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {247 const event = {248 version: '2.0',249 routeKey: '$default',250 headers: { 'content-type': 'text/plain' },251 rawPath: '/',252 rawQueryString: '',253 body: null,254 isBase64Encoded: false,255 requestContext: testApiGatewayRequestContextV2,256 }257258 testApiGatewayRequestContextV2.http.method = 'GET'259260 const response = await handler(event)261 expect(response.statusCode).toBe(200)262 expect(response.body).toBe('Hello Lambda!')263 expect(response.headers['content-type']).toMatch(/^text\/plain/)264 expect(response.isBase64Encoded).toBe(false)265 })266267 it('Should handle a GET request and return a 200 response (ALBEvent)', async () => {268 const event = {269 headers: { 'content-type': 'text/plain' },270 httpMethod: 'GET',271 path: '/',272 queryStringParameters: {273 query: '1234ABCD',274 },275 body: null,276 isBase64Encoded: false,277 requestContext: testALBRequestContext,278 }279280 const response = await handler(event)281 expect(response.statusCode).toBe(200)282 expect(response.body).toBe('Hello Lambda!')283 expect(response.headers['content-type']).toMatch(/^text\/plain/)284 expect(response.isBase64Encoded).toBe(false)285 })286287 it('Should handle a GET request and return a 404 response', async () => {288 const event = {289 version: '1.0',290 resource: '/nothing',291 httpMethod: 'GET',292 headers: { 'content-type': 'text/plain' },293 path: '/nothing',294 body: null,295 isBase64Encoded: false,296 requestContext: testApiGatewayRequestContext,297 }298299 const response = await handler(event)300 expect(response.statusCode).toBe(404)301 })302303 it('Should handle a POST request and return a 200 response', async () => {304 const searchParam = new URLSearchParams()305 searchParam.append('message', 'Good Morning Lambda!')306 const event = {307 version: '1.0',308 resource: '/post',309 httpMethod: 'POST',310 headers: {311 'Content-Type': 'application/x-www-form-urlencoded',312 },313 path: '/post',314 body: Buffer.from(searchParam.toString()).toString('base64'),315 isBase64Encoded: true,316 requestContext: testApiGatewayRequestContext,317 }318319 const response = await handler(event)320 expect(response.statusCode).toBe(200)321 expect(response.body).toBe('Good Morning Lambda!')322 })323324 it('Should handle a POST request and return a 200 response (LambdaFunctionUrlEvent)', async () => {325 const searchParam = new URLSearchParams()326 searchParam.append('message', 'Good Morning Lambda!')327 const event = {328 version: '2.0',329 routeKey: '$default',330 headers: {331 'Content-Type': 'application/x-www-form-urlencoded',332 },333 rawPath: '/post',334 rawQueryString: '',335 body: Buffer.from(searchParam.toString()).toString('base64'),336 isBase64Encoded: true,337 requestContext: testApiGatewayRequestContextV2,338 }339340 testApiGatewayRequestContextV2.http.method = 'POST'341342 const response = await handler(event)343 expect(response.statusCode).toBe(200)344 expect(response.body).toBe('Good Morning Lambda!')345 })346347 it('Should handle a POST request with binary and return a 200 response', async () => {348 const array = new Uint8Array([0xc0, 0xff, 0xee])349 const buffer = Buffer.from(array)350 const event = {351 version: '1.0',352 resource: '/post/binary',353 httpMethod: 'POST',354 headers: {355 'Content-Type': 'application/x-www-form-urlencoded',356 },357 path: '/post/binary',358 body: buffer.toString('base64'),359 isBase64Encoded: true,360 requestContext: testApiGatewayRequestContext,361 }362363 const response = await handler(event)364 expect(response.statusCode).toBe(200)365 expect(response.body).toBe('3 bytes')366 })367368 it('Should handle a request and return a 401 response with Basic auth', async () => {369 const event = {370 version: '1.0',371 resource: '/auth/abc',372 httpMethod: 'GET',373 headers: {374 'Content-Type': 'plain/text',375 },376 path: '/auth/abc',377 body: null,378 isBase64Encoded: true,379 requestContext: testApiGatewayRequestContext,380 }381382 const response = await handler(event)383 expect(response.statusCode).toBe(401)384 })385386 it('Should handle a request and return a 200 response with Basic auth', async () => {387 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'388 const event = {389 version: '1.0',390 resource: '/auth/abc',391 httpMethod: 'GET',392 headers: {393 'Content-Type': 'plain/text',394 Authorization: `Basic ${credential}`,395 },396 path: '/auth/abc',397 body: null,398 isBase64Encoded: true,399 requestContext: testApiGatewayRequestContext,400 }401402 const response = await handler(event)403 expect(response.statusCode).toBe(200)404 expect(response.body).toBe('Good Night Lambda!')405 })406407 it('Should handle a GET request and return custom context', async () => {408 const event = {409 version: '1.0',410 resource: '/custom-context/apigw',411 httpMethod: 'GET',412 headers: { 'content-type': 'application/json' },413 path: '/custom-context/apigw',414 body: null,415 isBase64Encoded: false,416 requestContext: testApiGatewayRequestContext,417 }418419 const response = await handler(event)420 expect(response.statusCode).toBe(200)421 expect(JSON.parse(response.body).customProperty).toEqual('customValue')422 })423424 it('Should handle a GET request and context', async () => {425 const event = {426 version: '1.0',427 resource: '/lambda-context',428 httpMethod: 'GET',429 headers: { 'content-type': 'application/json' },430 path: '/lambda-context',431 body: null,432 isBase64Encoded: false,433 requestContext: testApiGatewayRequestContext,434 }435 const context: LambdaContext = {436 callbackWaitsForEmptyEventLoop: false,437 functionName: 'myLambdaFunction',438 functionVersion: '1.0.0',439 invokedFunctionArn: 'arn:aws:lambda:us-west-2:123456789012:function:myLambdaFunction',440 memoryLimitInMB: '128',441 awsRequestId: 'c6af9ac6-a7b0-11e6-80f5-76304dec7eb7',442 logGroupName: '/aws/lambda/myLambdaFunction',443 logStreamName: '2016/11/14/[$LATEST]f2d4b21cfb33490da2e8f8ef79a483s4',444 getRemainingTimeInMillis: () => {445 return 60000 // 60 seconds446 },447 }448 const response = await handler(event, context)449 expect(response.statusCode).toBe(200)450 expect(JSON.parse(response.body).callbackWaitsForEmptyEventLoop).toEqual(false)451 })452453 it('Should handle a POST request and return a 200 response with cookies set (APIGatewayProxyEvent V1 and V2)', async () => {454 const apiGatewayEvent = {455 version: '1.0',456 resource: '/cookie',457 httpMethod: 'POST',458 headers: { 'content-type': 'text/plain' },459 path: '/cookie',460 body: null,461 isBase64Encoded: false,462 requestContext: testApiGatewayRequestContext,463 }464465 const apiGatewayResponse = await handler(apiGatewayEvent)466467 expect(apiGatewayResponse.statusCode).toBe(200)468 expect(apiGatewayResponse.multiValueHeaders).toHaveProperty('set-cookie', [469 testCookie1.serialized,470 testCookie2.serialized,471 ])472473 const apiGatewayEventV2 = {474 version: '2.0',475 routeKey: '$default',476 httpMethod: 'POST',477 headers: { 'content-type': 'text/plain' },478 rawPath: '/cookie',479 rawQueryString: '',480 body: null,481 isBase64Encoded: false,482 requestContext: testApiGatewayRequestContextV2,483 }484485 const apiGatewayResponseV2 = await handler(apiGatewayEventV2)486487 expect(apiGatewayResponseV2.statusCode).toBe(200)488 expect(apiGatewayResponseV2).toHaveProperty('cookies', [489 testCookie1.serialized,490 testCookie2.serialized,491 ])492 })493494 it('Should handle a POST request and return a 200 response if cookies match (APIGatewayProxyEvent V1 and V2)', async () => {495 const apiGatewayEvent = {496 version: '1.0',497 resource: '/cookie',498 httpMethod: 'GET',499 headers: {500 'content-type': 'text/plain',501 cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),502 },503 path: '/cookie',504 body: null,505 isBase64Encoded: false,506 requestContext: testApiGatewayRequestContext,507 }508509 const apiGatewayResponse = await handler(apiGatewayEvent)510511 expect(apiGatewayResponse.statusCode).toBe(200)512 expect(apiGatewayResponse.body).toBe('Valid Cookies')513 expect(apiGatewayResponse.headers['content-type']).toMatch(/^text\/plain/)514 expect(apiGatewayResponse.isBase64Encoded).toBe(false)515516 const apiGatewayEventV2 = {517 version: '2.0',518 routeKey: '$default',519 headers: { 'content-type': 'text/plain' },520 rawPath: '/cookie',521 cookies: [testCookie1.serialized, testCookie2.serialized],522 rawQueryString: '',523 body: null,524 isBase64Encoded: false,525 requestContext: testApiGatewayRequestContextV2,526 }527 testApiGatewayRequestContextV2.http.method = 'GET'528529 const apiGatewayResponseV2 = await handler(apiGatewayEventV2)530531 expect(apiGatewayResponseV2.statusCode).toBe(200)532 expect(apiGatewayResponseV2.body).toBe('Valid Cookies')533 expect(apiGatewayResponseV2.headers['content-type']).toMatch(/^text\/plain/)534 expect(apiGatewayResponseV2.isBase64Encoded).toBe(false)535 })536})537538describe('streamHandle function', () => {539 const app = new Hono<{ Bindings: Bindings }>()540541 app.get('/', (c) => {542 return c.text('Hello Lambda!')543 })544545 app.get('/stream/text', async (c) => {546 return c.streamText(async (stream) => {547 for (let i = 0; i < 3; i++) {548 await stream.writeln(`${i}`)549 await stream.sleep(1)550 }551 })552 })553554 app.get('/sse', async (c) => {555 return streamSSE(c, async (stream) => {556 let id = 0557 const maxIterations = 2558559 while (id < maxIterations) {560 const message = `Message\nIt is ${id}`561 await stream.writeSSE({ data: message, event: 'time-update', id: String(id++) })562 await stream.sleep(10)563 }564 })565 })566567 const handler = streamHandle(app)568569 it('Should streamHandle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {570 const event = {571 headers: { 'content-type': ' binary/octet-stream' },572 rawPath: '/stream/text',573 rawQueryString: '',574 body: null,575 isBase64Encoded: false,576 requestContext: testApiGatewayRequestContextV2,577 }578579 testApiGatewayRequestContextV2.http.method = 'GET'580581 const mockReadableStream = new Readable({582 // eslint-disable-next-line @typescript-eslint/no-empty-function583 read() {},584 })585586 mockReadableStream.push('0\n')587 mockReadableStream.push('1\n')588 mockReadableStream.push('2\n')589 mockReadableStream.push('3\n')590 mockReadableStream.push(null) // EOF591592 await handler(event, mockReadableStream)593594 const chunks = []595 for await (const chunk of mockReadableStream) {596 chunks.push(chunk)597 }598 expect(chunks.join('')).toContain('0\n1\n2\n3\n')599 })600601 it('Should handle a GET request for an SSE stream and return the correct chunks', async () => {602 const event = {603 headers: { 'content-type': 'text/event-stream' },604 rawPath: '/sse',605 rawQueryString: '',606 body: null,607 isBase64Encoded: false,608 requestContext: testApiGatewayRequestContextV2,609 }610611 testApiGatewayRequestContextV2.http.method = 'GET'612613 const mockReadableStream = new Readable({614 // eslint-disable-next-line @typescript-eslint/no-empty-function615 read() {},616 })617618 const initContentType = {619 'Content-Type': 'application/vnd.awslambda.http-integration-response',620 }621 mockReadableStream.push(JSON.stringify(initContentType))622623 // Send JSON formatted response headers, followed by 8 NULL characters as a separator624 const httpResponseMetadata = {625 statusCode: 200,626 headers: { 'Custom-Header': 'value' },627 cookies: ['session=abcd1234'],628 }629 const jsonResponsePrelude = JSON.stringify(httpResponseMetadata) + Buffer.alloc(8, 0).toString()630 mockReadableStream.push(jsonResponsePrelude)631632 mockReadableStream.push('data: Message\ndata: It is 0\n\n')633 mockReadableStream.push('data: Message\ndata: It is 1\n\n')634 mockReadableStream.push(null) // EOF635636 await handler(event, mockReadableStream)637638 const chunks = []639 for await (const chunk of mockReadableStream) {640 chunks.push(chunk)641 }642643 // If you have chunks, you might want to convert them to strings before checking644 const output = Buffer.concat(chunks).toString()645 expect(output).toContain('data: Message\ndata: It is 0\n\n')646 expect(output).toContain('data: Message\ndata: It is 1\n\n')647648 // Assertions for the newly added header and prelude649 expect(output).toContain('application/vnd.awslambda.http-integration-response')650 expect(output).toContain('Custom-Header')651 expect(output).toContain('session=abcd1234')652653 // Check for JSON prelude and NULL sequence654 const nullSequence = '\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000'655 expect(output).toContain(jsonResponsePrelude.replace(nullSequence, ''))656 })657})