Skip to content
Myr

index.test.ts

This file

Path

adapters/aws-lambda/test/index.test.ts

1,087 lines 路 33.0 KiB 路 TypeScript

Last changed by

test: move adapter runtime tests into `adapters/*` (#5466)Yusuke Wadabefore adoption645ddd6

History of this file

Take it

1import { Readable } from 'stream'2import { Hono } from 'hono'3import { basicAuth } from 'hono/basic-auth'4import { getCookie, setCookie } from 'hono/cookie'5import { streamSSE, streamText } from 'hono/streaming'6import {7  ALBProcessor,8  EventV1Processor,9  EventV2Processor,10  getProcessor,11  handle,12  streamHandle,13} from '../src/handler'14import type {15  ALBProxyEvent,16  APIGatewayProxyEventV2,17  LatticeProxyEventV2,18  LambdaEvent,19} from '../src/handler'20import type {21  ApiGatewayRequestContext,22  ApiGatewayRequestContextV2,23  LatticeRequestContextV2,24  LambdaContext,25} from '../src/types'26import './mock'2728type Bindings = {29  event: LambdaEvent30  lambdaContext: LambdaContext31  requestContext: ApiGatewayRequestContext | ApiGatewayRequestContextV232}3334const testApiGatewayRequestContextV2 = {35  accountId: '123456789012',36  apiId: 'urlid',37  authentication: null,38  authorizer: {39    iam: {40      accessKey: 'AKIA...',41      accountId: '111122223333',42      callerId: 'AIDA...',43      cognitoIdentity: null,44      principalOrgId: null,45      userArn: 'arn:aws:iam::111122223333:user/example-user',46      userId: 'AIDA...',47    },48  },49  domainName: 'example.com',50  domainPrefix: '<url-id>',51  http: {52    method: 'POST',53    path: '/my/path',54    protocol: 'HTTP/1.1',55    sourceIp: '123.123.123.123',56    userAgent: 'agent',57  },58  requestId: 'id',59  routeKey: '$default',60  stage: '$default',61  time: '12/Mar/2020:19:03:58 +0000',62  timeEpoch: 1583348638390,63  customProperty: 'customValue',64}6566const testLatticeRequestContext: LatticeRequestContextV2 = {67  serviceNetworkArn: 'arn:aws:vpc-lattice:us-east-1:111122223333:servicenetwork/sn-a1b2c3',68  serviceArn: 'arn:aws:vpc-lattice:us-east-1:111122223333:service/svc-a1b2c3',69  targetGroupArn: 'arn:aws:vpc-lattice:us-east-1:111122223333:targetgroup/tg-a1b2c3',70  region: 'us-east-1',71  timeEpoch: '1759915938150314',72  identity: {73    sourceVpcArn: 'arn:aws:ec2:us-east-1:111122223333:vpc/vpc-a1b2c3',74  },75}7677describe('AWS Lambda Adapter for Hono', () => {78  const app = new Hono<{ Bindings: Bindings }>()7980  app.get('/', (c) => {81    return c.text('Hello Lambda!')82  })8384  app.get('/binary', (c) => {85    return c.body('Fake Image', 200, {86      'Content-Type': 'image/png',87    })88  })8990  app.post('/post', async (c) => {91    const body = (await c.req.parseBody()) as { message: string }92    return c.text(body.message)93  })9495  app.post('/post/binary', async (c) => {96    const body = await c.req.blob()97    return c.text(`${body.size} bytes`)98  })99100  const username = 'hono-user-a'101  const password = 'hono-password-a'102  app.use('/auth/*', basicAuth({ username, password }))103  app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))104105  app.get('/lambda-event', (c) => {106    const event = c.env.event107    return c.json(event)108  })109110  app.get('/lambda-context', (c) => {111    const fnctx = c.env.lambdaContext112    return c.json(fnctx)113  })114115  app.get('/custom-context/v1/apigw', (c) => {116    const lambdaContext = c.env.requestContext117    return c.json(lambdaContext)118  })119120  app.get('/custom-context/apigw', (c) => {121    const lambdaContext = c.env.event.requestContext122    return c.json(lambdaContext)123  })124125  app.get('/custom-context/v1/lambda', (c) => {126    const lambdaContext = c.env.requestContext127    return c.json(lambdaContext)128  })129130  app.get('/custom-context/lambda', (c) => {131    const lambdaContext = c.env.event.requestContext132    return c.json(lambdaContext)133  })134135  app.get('/query-params', (c) => {136    const queryParams = c.req.query()137    return c.json(queryParams)138  })139140  app.get('/multi-query-params', (c) => {141    const multiQueryParams = c.req.queries()142    return c.json(multiQueryParams)143  })144145  const testCookie1 = {146    key: 'id',147    value: crypto.randomUUID(),148    get serialized() {149      return `${this.key}=${this.value}; Path=/`150    },151  }152  const testCookie2 = {153    key: 'secret',154    value: crypto.randomUUID(),155    get serialized() {156      return `${this.key}=${this.value}; Path=/`157    },158  }159160  app.post('/cookie', (c) => {161    setCookie(c, testCookie1.key, testCookie1.value)162    setCookie(c, testCookie2.key, testCookie2.value)163    return c.text('Cookies Set')164  })165166  app.get('/cookie', (c) => {167    const validCookies =168      getCookie(c, testCookie1.key) === testCookie1.value &&169      getCookie(c, testCookie2.key) === testCookie2.value170    if (!validCookies) {171      return c.text('Invalid Cookies')172    }173    return c.text('Valid Cookies')174  })175176  app.post('/headers', (c) => {177    if (c.req.header('foo')?.includes('bar')) {178      return c.json({ message: 'ok' })179    }180    return c.json({ message: 'fail' }, 400)181  })182183  const handler = handle(app)184185  const testApiGatewayRequestContext = {186    accountId: '123456789012',187    apiId: 'id',188    authorizer: {189      claims: null,190      scopes: null,191    },192    domainName: 'example.com',193    domainPrefix: 'id',194    extendedRequestId: 'request-id',195    httpMethod: 'GET',196    identity: {197      sourceIp: 'IP',198      userAgent: 'user-agent',199    },200    path: '/my/path',201    protocol: 'HTTP/1.1',202    requestId: 'id=',203    requestTime: '04/Mar/2020:19:15:17 +0000',204    requestTimeEpoch: 1583349317135,205    resourcePath: '/',206    stage: '$default',207    customProperty: 'customValue',208  }209210  const testALBRequestContext = {211    elb: {212      targetGroupArn:213        'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',214    },215  }216217  it('Should handle a GET request and return a 200 response', async () => {218    const event = {219      version: '1.0',220      resource: '/',221      httpMethod: 'GET',222      headers: { 'content-type': 'text/plain' },223      path: '/',224      body: null,225      isBase64Encoded: false,226      requestContext: testApiGatewayRequestContext,227    }228229    const response = await handler(event)230    expect(response.statusCode).toBe(200)231    expect(response.body).toBe('Hello Lambda!')232    expect(response.headers['content-type']).toMatch(/^text\/plain/)233    expect(response.multiValueHeaders).toBeUndefined()234    expect(response.isBase64Encoded).toBe(false)235  })236237  it('Should handle a GET request and return a 200 response with binary', async () => {238    const event = {239      version: '1.0',240      resource: '/binary',241      httpMethod: 'GET',242      headers: {},243      path: '/binary',244      body: null,245      isBase64Encoded: false,246      requestContext: testApiGatewayRequestContext,247    }248249    const response = await handler(event)250    expect(response.statusCode).toBe(200)251    expect(response.body).toBe('RmFrZSBJbWFnZQ==')252    expect(response.headers['content-type']).toMatch(/^image\/png/)253    expect(response.multiValueHeaders).toBeUndefined()254    expect(response.isBase64Encoded).toBe(true)255  })256257  it('Should handle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {258    const event = {259      version: '2.0',260      routeKey: '$default',261      headers: { 'content-type': 'text/plain' },262      rawPath: '/',263      rawQueryString: '',264      body: null,265      isBase64Encoded: false,266      requestContext: testApiGatewayRequestContextV2,267    }268269    testApiGatewayRequestContextV2.http.method = 'GET'270271    const response = await handler(event)272    expect(response.statusCode).toBe(200)273    expect(response.body).toBe('Hello Lambda!')274    expect(response.headers['content-type']).toMatch(/^text\/plain/)275    expect(response.multiValueHeaders).toBeUndefined()276    expect(response.isBase64Encoded).toBe(false)277  })278279  it('Should handle a GET request and return a 200 response (ALBEvent)', async () => {280    const event = {281      headers: { 'content-type': 'text/plain' },282      httpMethod: 'GET',283      path: '/',284      queryStringParameters: {285        query: '1234ABCD',286      },287      body: null,288      isBase64Encoded: false,289      requestContext: testALBRequestContext,290    }291292    const response = await handler(event)293    expect(response.statusCode).toBe(200)294    expect(response.body).toBe('Hello Lambda!')295    expect(response.headers['content-type']).toMatch(/^text\/plain/)296    expect(response.multiValueHeaders).toBeUndefined()297    expect(response.isBase64Encoded).toBe(false)298  })299300  it('Should handle a GET request and return a 200 response (LatticeProxyEvent)', async () => {301    const event: LatticeProxyEventV2 = {302      version: '2.0',303      path: '/?query=1234ABCD',304      method: 'GET',305      headers: { 'content-type': ['text/plain'] },306      queryStringParameters: {},307      body: null,308      isBase64Encoded: false,309      requestContext: testLatticeRequestContext,310    }311312    const response = await handler(event)313    expect(response.statusCode).toBe(200)314    expect(response.body).toBe('Hello Lambda!')315    expect(response.headers['content-type']).toMatch(/^text\/plain/)316    expect(response.multiValueHeaders).toBeUndefined()317    expect(response.isBase64Encoded).toBe(false)318  })319320  it('Should handle a GET request and return a 404 response', async () => {321    const event = {322      version: '1.0',323      resource: '/nothing',324      httpMethod: 'GET',325      headers: { 'content-type': 'text/plain' },326      path: '/nothing',327      body: null,328      isBase64Encoded: false,329      requestContext: testApiGatewayRequestContext,330    }331332    const response = await handler(event)333    expect(response.statusCode).toBe(404)334  })335336  it('Should handle a POST request and return a 200 response', async () => {337    const searchParam = new URLSearchParams()338    searchParam.append('message', 'Good Morning Lambda!')339    const event = {340      version: '1.0',341      resource: '/post',342      httpMethod: 'POST',343      headers: {344        'Content-Type': 'application/x-www-form-urlencoded',345      },346      path: '/post',347      body: Buffer.from(searchParam.toString()).toString('base64'),348      isBase64Encoded: true,349      requestContext: testApiGatewayRequestContext,350    }351352    const response = await handler(event)353    expect(response.statusCode).toBe(200)354    expect(response.body).toBe('Good Morning Lambda!')355  })356357  it('Should handle a POST request and return a 200 response (LambdaFunctionUrlEvent)', async () => {358    const searchParam = new URLSearchParams()359    searchParam.append('message', 'Good Morning Lambda!')360    const event = {361      version: '2.0',362      routeKey: '$default',363      headers: {364        'Content-Type': 'application/x-www-form-urlencoded',365      },366      rawPath: '/post',367      rawQueryString: '',368      body: Buffer.from(searchParam.toString()).toString('base64'),369      isBase64Encoded: true,370      requestContext: testApiGatewayRequestContextV2,371    }372373    testApiGatewayRequestContextV2.http.method = 'POST'374375    const response = await handler(event)376    expect(response.statusCode).toBe(200)377    expect(response.body).toBe('Good Morning Lambda!')378  })379380  it('Should handle a POST request with binary and return a 200 response', async () => {381    const array = new Uint8Array([0xc0, 0xff, 0xee])382    const buffer = Buffer.from(array)383    const event = {384      version: '1.0',385      resource: '/post/binary',386      httpMethod: 'POST',387      headers: {388        'Content-Type': 'application/x-www-form-urlencoded',389      },390      path: '/post/binary',391      body: buffer.toString('base64'),392      isBase64Encoded: true,393      requestContext: testApiGatewayRequestContext,394    }395396    const response = await handler(event)397    expect(response.statusCode).toBe(200)398    expect(response.body).toBe('3 bytes')399  })400401  it('Should handle a request and return a 401 response with Basic auth', async () => {402    const event = {403      version: '1.0',404      resource: '/auth/abc',405      httpMethod: 'GET',406      headers: {407        'Content-Type': 'plain/text',408      },409      path: '/auth/abc',410      body: null,411      isBase64Encoded: true,412      requestContext: testApiGatewayRequestContext,413    }414415    const response = await handler(event)416    expect(response.statusCode).toBe(401)417  })418419  it('Should handle a request and return a 200 response with Basic auth', async () => {420    const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'421    const event = {422      version: '1.0',423      resource: '/auth/abc',424      httpMethod: 'GET',425      headers: {426        'Content-Type': 'plain/text',427        Authorization: `Basic ${credential}`,428      },429      path: '/auth/abc',430      body: null,431      isBase64Encoded: true,432      requestContext: testApiGatewayRequestContext,433    }434435    const response = await handler(event)436    expect(response.statusCode).toBe(200)437    expect(response.body).toBe('Good Night Lambda!')438  })439440  it('Should handle a GET request and return custom context', async () => {441    const event = {442      version: '1.0',443      resource: '/custom-context/apigw',444      httpMethod: 'GET',445      headers: { 'content-type': 'application/json' },446      path: '/custom-context/apigw',447      body: null,448      isBase64Encoded: false,449      requestContext: testApiGatewayRequestContext,450    }451452    const response = await handler(event)453    expect(response.statusCode).toBe(200)454    expect(JSON.parse(response.body).customProperty).toEqual('customValue')455  })456457  it('Should handle a GET request and context', async () => {458    const event = {459      version: '1.0',460      resource: '/lambda-context',461      httpMethod: 'GET',462      headers: { 'content-type': 'application/json' },463      path: '/lambda-context',464      body: null,465      isBase64Encoded: false,466      requestContext: testApiGatewayRequestContext,467    }468    const context: LambdaContext = {469      callbackWaitsForEmptyEventLoop: false,470      functionName: 'myLambdaFunction',471      functionVersion: '1.0.0',472      invokedFunctionArn: 'arn:aws:lambda:us-west-2:123456789012:function:myLambdaFunction',473      memoryLimitInMB: '128',474      awsRequestId: 'c6af9ac6-a7b0-11e6-80f5-76304dec7eb7',475      logGroupName: '/aws/lambda/myLambdaFunction',476      logStreamName: '2016/11/14/[$LATEST]f2d4b21cfb33490da2e8f8ef79a483s4',477      getRemainingTimeInMillis: () => {478        return 60000 // 60 seconds479      },480    }481    const response = await handler(event, context)482    expect(response.statusCode).toBe(200)483    expect(JSON.parse(response.body).callbackWaitsForEmptyEventLoop).toEqual(false)484  })485486  it('Should handle a POST request and return a 200 response with cookies set (APIGatewayProxyEvent V1 and V2)', async () => {487    const apiGatewayEvent = {488      version: '1.0',489      resource: '/cookie',490      httpMethod: 'POST',491      headers: { 'content-type': 'text/plain' },492      path: '/cookie',493      body: null,494      isBase64Encoded: false,495      requestContext: testApiGatewayRequestContext,496    }497498    const apiGatewayResponse = await handler(apiGatewayEvent)499500    expect(apiGatewayResponse.statusCode).toBe(200)501    expect(apiGatewayResponse.multiValueHeaders).toHaveProperty('set-cookie', [502      testCookie1.serialized,503      testCookie2.serialized,504    ])505506    const apiGatewayEventV2 = {507      version: '2.0',508      routeKey: '$default',509      httpMethod: 'POST',510      headers: { 'content-type': 'text/plain' },511      rawPath: '/cookie',512      rawQueryString: '',513      body: null,514      isBase64Encoded: false,515      requestContext: testApiGatewayRequestContextV2,516    }517518    const apiGatewayResponseV2 = await handler(apiGatewayEventV2)519520    expect(apiGatewayResponseV2.statusCode).toBe(200)521    expect(apiGatewayResponseV2).toHaveProperty('cookies', [522      testCookie1.serialized,523      testCookie2.serialized,524    ])525  })526527  it('Should handle a POST request and return a 200 response with cookies set (LatticeProxyEvent V2)', async () => {528    const latticeProxyEvent: LatticeProxyEventV2 = {529      version: '2.0',530      path: '/cookie',531      method: 'POST',532      headers: { 'content-type': ['text/plain'] },533      queryStringParameters: {},534      body: null,535      isBase64Encoded: false,536      requestContext: testLatticeRequestContext,537    }538539    const latticeResponse = await handler(latticeProxyEvent)540541    expect(latticeResponse.statusCode).toBe(200)542    expect(latticeResponse.headers).toHaveProperty('set-cookie', [543      testCookie1.serialized,544      testCookie2.serialized,545    ])546  })547548  describe('headers', () => {549    describe('single-value headers', () => {550      it('Should extract single-value headers and return 200 (ALBProxyEvent)', async () => {551        const event = {552          body: '{}',553          httpMethod: 'POST',554          isBase64Encoded: false,555          path: '/headers',556          headers: {557            host: 'localhost',558            foo: 'bar',559          },560          requestContext: testALBRequestContext,561        }562        const albResponse = await handler(event)563        expect(albResponse.statusCode).toBe(200)564        expect(albResponse.headers).toEqual(565          expect.objectContaining({566            'content-type': 'application/json',567          })568        )569        expect(albResponse.multiValueHeaders).toBeUndefined()570      })571572      it('Should extract single-value headers and return 200 (APIGatewayProxyEvent)', async () => {573        const apigatewayProxyEvent = {574          version: '1.0',575          resource: '/headers',576          httpMethod: 'POST',577          headers: {578            host: 'localhost',579            foo: 'bar',580          },581          path: '/headers',582          body: null,583          isBase64Encoded: false,584          requestContext: testApiGatewayRequestContext,585        }586        const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)587        expect(apiGatewayResponseV2.statusCode).toBe(200)588      })589590      it('Should extract single-value headers and return 200 (APIGatewayProxyEventV2)', async () => {591        const apigatewayProxyV2Event = {592          version: '2.0',593          routeKey: '$default',594          headers: {595            host: 'localhost',596            foo: 'bar',597          },598          rawPath: '/headers',599          rawQueryString: '',600          requestContext: testApiGatewayRequestContextV2,601          resource: '/headers',602          body: null,603          isBase64Encoded: false,604        }605        const apiGatewayResponseV2 = await handler(apigatewayProxyV2Event)606        expect(apiGatewayResponseV2.statusCode).toBe(200)607      })608    })609610    describe('multi-value headers', () => {611      it('Should extract multi-value headers and return 200 (ALBProxyEvent)', async () => {612        const event = {613          body: '{}',614          httpMethod: 'POST',615          isBase64Encoded: false,616          path: '/headers',617          multiValueHeaders: {618            host: ['localhost'],619            foo: ['bar'],620          },621          requestContext: testALBRequestContext,622        }623        const albResponse = await handler(event)624        expect(albResponse.statusCode).toBe(200)625        expect(albResponse.multiValueHeaders).toBeDefined()626        expect(albResponse.multiValueHeaders).toEqual(627          expect.objectContaining({628            'content-type': ['application/json'],629          })630        )631      })632633      it('Should extract multi-value headers and return 200 (APIGatewayProxyEvent)', async () => {634        const apigatewayProxyEvent = {635          version: '1.0',636          resource: '/headers',637          httpMethod: 'POST',638          headers: {},639          multiValueHeaders: {640            host: ['localhost'],641            foo: ['bar'],642          },643          path: '/headers',644          body: null,645          isBase64Encoded: false,646          requestContext: testApiGatewayRequestContext,647        }648        const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)649        expect(apiGatewayResponseV2.statusCode).toBe(200)650      })651652      it('Should extract multi-value headers and return 200 (LatticeProxyEvent)', async () => {653        const event: LatticeProxyEventV2 = {654          version: '2.0',655          path: '/headers',656          method: 'POST',657          headers: {658            host: ['localhost'],659            foo: ['bar'],660          },661          queryStringParameters: {},662          body: null,663          isBase64Encoded: false,664          requestContext: testLatticeRequestContext,665        }666667        const response = await handler(event)668669        expect(response.statusCode).toBe(200)670      })671    })672  })673674  it('Should handle a POST request and return a 200 response if cookies match (APIGatewayProxyEvent V1 and V2)', async () => {675    const apiGatewayEvent = {676      version: '1.0',677      resource: '/cookie',678      httpMethod: 'GET',679      headers: {680        'content-type': 'text/plain',681        cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),682      },683      path: '/cookie',684      body: null,685      isBase64Encoded: false,686      requestContext: testApiGatewayRequestContext,687    }688689    const apiGatewayResponse = await handler(apiGatewayEvent)690691    expect(apiGatewayResponse.statusCode).toBe(200)692    expect(apiGatewayResponse.body).toBe('Valid Cookies')693    expect(apiGatewayResponse.headers['content-type']).toMatch(/^text\/plain/)694    expect(apiGatewayResponse.isBase64Encoded).toBe(false)695696    const apiGatewayEventV2 = {697      version: '2.0',698      routeKey: '$default',699      headers: { 'content-type': 'text/plain' },700      rawPath: '/cookie',701      cookies: [testCookie1.serialized, testCookie2.serialized],702      rawQueryString: '',703      body: null,704      isBase64Encoded: false,705      requestContext: testApiGatewayRequestContextV2,706    }707    testApiGatewayRequestContextV2.http.method = 'GET'708709    const apiGatewayResponseV2 = await handler(apiGatewayEventV2)710711    expect(apiGatewayResponseV2.statusCode).toBe(200)712    expect(apiGatewayResponseV2.body).toBe('Valid Cookies')713    expect(apiGatewayResponseV2.headers['content-type']).toMatch(/^text\/plain/)714    expect(apiGatewayResponseV2.isBase64Encoded).toBe(false)715  })716717  it('Should handle a GET request and return a 200 response if cookies match (ALBProxyEvent) with default headers', async () => {718    const albEventDefaultHeaders = {719      version: '1.0',720      resource: '/cookie',721      httpMethod: 'GET',722      headers: {723        'content-type': 'text/plain',724        cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),725      },726      path: '/cookie',727      body: null,728      isBase64Encoded: false,729      requestContext: testALBRequestContext,730    }731732    const albResponse = await handler(albEventDefaultHeaders)733734    expect(albResponse.statusCode).toBe(200)735    expect(albResponse.body).toBe('Valid Cookies')736    expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)737    expect(albResponse.multiValueHeaders).toBeUndefined()738    expect(albResponse.isBase64Encoded).toBe(false)739  })740741  it('Should handle a GET request and return a 200 response if cookies match (ALBProxyEvent) with multi value headers', async () => {742    const albEventMultiValueHeaders = {743      version: '1.0',744      resource: '/cookie',745      httpMethod: 'GET',746      multiValueHeaders: {747        'content-type': ['text/plain'],748        cookie: [testCookie1.serialized, testCookie2.serialized],749      },750      path: '/cookie',751      body: null,752      isBase64Encoded: false,753      requestContext: testALBRequestContext,754    }755756    const albResponse = await handler(albEventMultiValueHeaders)757758    expect(albResponse.statusCode).toBe(200)759    expect(albResponse.body).toBe('Valid Cookies')760    expect(albResponse.headers).toBeUndefined()761    expect(albResponse.multiValueHeaders['content-type']).toEqual([762      expect.stringMatching(/^text\/plain/),763    ])764    expect(albResponse.isBase64Encoded).toBe(false)765  })766767  it('Should handle a POST request and return a 200 response with cookies (ALBProxyEvent) with default headers', async () => {768    const albEventDefaultHeaders = {769      version: '1.0',770      resource: '/cookie',771      httpMethod: 'POST',772      headers: {773        'content-type': 'text/plain',774        cookie: [testCookie1.serialized, testCookie2.serialized].join(', '),775      },776      path: '/cookie',777      body: null,778      isBase64Encoded: false,779      requestContext: testALBRequestContext,780    }781782    const albResponse = await handler(albEventDefaultHeaders)783784    expect(albResponse.statusCode).toBe(200)785    expect(albResponse.body).toBe('Cookies Set')786    expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)787    expect(albResponse.multiValueHeaders).toBeUndefined()788    expect(albResponse.headers['set-cookie']).toEqual(testCookie1.serialized)789    expect(albResponse.isBase64Encoded).toBe(false)790  })791792  it('Should handle a POST request and return a 200 response with cookies (ALBProxyEvent) with multi value headers', async () => {793    const albEventDefaultHeaders = {794      version: '1.0',795      resource: '/cookie',796      httpMethod: 'POST',797      multiValueHeaders: {798        'content-type': ['text/plain'],799        cookie: [testCookie1.serialized, testCookie2.serialized],800      },801      path: '/cookie',802      body: null,803      isBase64Encoded: false,804      requestContext: testALBRequestContext,805    }806807    const albResponse = await handler(albEventDefaultHeaders)808809    expect(albResponse.statusCode).toBe(200)810    expect(albResponse.body).toBe('Cookies Set')811    expect(albResponse.headers).toBeUndefined()812    expect(albResponse.multiValueHeaders['set-cookie']).toEqual(813      expect.arrayContaining([testCookie1.serialized, testCookie2.serialized])814    )815    expect(albResponse.isBase64Encoded).toBe(false)816  })817818  it('Should handle a GET request and return a 200 response with queryStringParameters (ALBProxyEvent)', async () => {819    const albEventDefaultHeaders = {820      resource: '/query-params',821      httpMethod: 'GET',822      headers: {823        'content-type': 'application/json',824      },825      queryStringParameters: {826        key1: 'value1',827        key2: 'value2',828      },829      path: '/query-params',830      body: null,831      isBase64Encoded: false,832      requestContext: testALBRequestContext,833    }834835    const albResponse = await handler(albEventDefaultHeaders)836837    expect(albResponse.statusCode).toBe(200)838    expect(albResponse.body).toContain(839      JSON.stringify({840        key1: 'value1',841        key2: 'value2',842      })843    )844    expect(albResponse.headers['content-type']).toMatch(/^application\/json/)845    expect(albResponse.multiValueHeaders).toBeUndefined()846    expect(albResponse.isBase64Encoded).toBe(false)847  })848849  it('Should handle a GET request and return a 200 response with single value multiQueryStringParameters (ALBProxyEvent)', async () => {850    const albEventDefaultHeaders = {851      resource: '/query-params',852      httpMethod: 'GET',853      multiValueHeaders: {854        'content-type': ['application/json'],855      },856      multiValueQueryStringParameters: {857        key1: ['value1'],858        key2: ['value2'],859      },860      path: '/query-params',861      body: null,862      isBase64Encoded: false,863      requestContext: testALBRequestContext,864    }865866    const albResponse = await handler(albEventDefaultHeaders)867868    expect(albResponse.statusCode).toBe(200)869    expect(albResponse.body).toContain(870      JSON.stringify({871        key1: 'value1',872        key2: 'value2',873      })874    )875    expect(albResponse.headers).toBeUndefined()876    expect(albResponse.multiValueHeaders['content-type']).toEqual([877      expect.stringMatching(/^application\/json/),878    ])879    expect(albResponse.isBase64Encoded).toBe(false)880  })881882  it('Should handle a GET request and return a 200 response with multi value multiQueryStringParameters (ALBProxyEvent)', async () => {883    const albEventDefaultHeaders = {884      resource: '/query-params',885      httpMethod: 'GET',886      multiValueHeaders: {887        'content-type': ['application/json'],888      },889      multiValueQueryStringParameters: {890        key1: ['value1'],891        key2: ['value2', 'otherValue2'],892      },893      path: '/multi-query-params',894      body: null,895      isBase64Encoded: false,896      requestContext: testALBRequestContext,897    }898899    const albResponse = await handler(albEventDefaultHeaders)900901    expect(albResponse.statusCode).toBe(200)902    expect(albResponse.body).toContain(903      JSON.stringify({904        key1: ['value1'],905        key2: ['value2', 'otherValue2'],906      })907    )908    expect(albResponse.headers).toBeUndefined()909    expect(albResponse.multiValueHeaders['content-type']).toEqual([910      expect.stringMatching(/^application\/json/),911    ])912    expect(albResponse.isBase64Encoded).toBe(false)913  })914})915916describe('streamHandle function', () => {917  const app = new Hono<{ Bindings: Bindings }>()918919  app.get('/', (c) => {920    return c.text('Hello Lambda!')921  })922923  app.get('/stream/text', async (c) => {924    return streamText(c, async (stream) => {925      for (let i = 0; i < 3; i++) {926        await stream.writeln(`${i}`)927        await stream.sleep(1)928      }929    })930  })931932  app.get('/sse', async (c) => {933    return streamSSE(c, async (stream) => {934      let id = 0935      const maxIterations = 2936937      while (id < maxIterations) {938        const message = `Message\nIt is ${id}`939        await stream.writeSSE({ data: message, event: 'time-update', id: String(id++) })940        await stream.sleep(10)941      }942    })943  })944945  const handler = streamHandle(app)946947  it('Should streamHandle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {948    const event = {949      headers: { 'content-type': ' binary/octet-stream' },950      rawPath: '/stream/text',951      rawQueryString: '',952      body: null,953      isBase64Encoded: false,954      requestContext: testApiGatewayRequestContextV2,955    }956957    testApiGatewayRequestContextV2.http.method = 'GET'958959    const mockReadableStream = new Readable({960      // eslint-disable-next-line @typescript-eslint/no-empty-function961      read() {},962    })963964    mockReadableStream.push('0\n')965    mockReadableStream.push('1\n')966    mockReadableStream.push('2\n')967    mockReadableStream.push('3\n')968    mockReadableStream.push(null) // EOF969970    // @ts-expect-error should this be a ReadbleStream?971    await handler(event, mockReadableStream, vi.fn())972973    const chunks = []974    for await (const chunk of mockReadableStream) {975      chunks.push(chunk)976    }977    expect(chunks.join('')).toContain('0\n1\n2\n3\n')978  })979980  it('Should handle a GET request for an SSE stream and return the correct chunks', async () => {981    const event = {982      headers: { 'content-type': 'text/event-stream' },983      rawPath: '/sse',984      rawQueryString: '',985      body: null,986      isBase64Encoded: false,987      requestContext: testApiGatewayRequestContextV2,988    }989990    testApiGatewayRequestContextV2.http.method = 'GET'991992    const mockReadableStream = new Readable({993      // eslint-disable-next-line @typescript-eslint/no-empty-function994      read() {},995    })996997    const initContentType = {998      'Content-Type': 'application/vnd.awslambda.http-integration-response',999    }1000    mockReadableStream.push(JSON.stringify(initContentType))10011002    // Send JSON formatted response headers, followed by 8 NULL characters as a separator1003    const httpResponseMetadata = {1004      statusCode: 200,1005      headers: { 'Custom-Header': 'value' },1006      cookies: ['session=abcd1234'],1007    }1008    const jsonResponsePrelude = JSON.stringify(httpResponseMetadata) + Buffer.alloc(8, 0).toString()1009    mockReadableStream.push(jsonResponsePrelude)10101011    mockReadableStream.push('data: Message\ndata: It is 0\n\n')1012    mockReadableStream.push('data: Message\ndata: It is 1\n\n')1013    mockReadableStream.push(null) // EOF10141015    // @ts-expect-error should this be a ReadbleStream?1016    await handler(event, mockReadableStream, vi.fn())10171018    const chunks = []1019    for await (const chunk of mockReadableStream) {1020      chunks.push(chunk)1021    }10221023    // If you have chunks, you might want to convert them to strings before checking1024    const output = Buffer.concat(chunks).toString()1025    expect(output).toContain('data: Message\ndata: It is 0\n\n')1026    expect(output).toContain('data: Message\ndata: It is 1\n\n')10271028    // Assertions for the newly added header and prelude1029    expect(output).toContain('application/vnd.awslambda.http-integration-response')1030    expect(output).toContain('Custom-Header')1031    expect(output).toContain('session=abcd1234')10321033    // Check for JSON prelude and NULL sequence1034    const nullSequence = '\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000'1035    expect(output).toContain(jsonResponsePrelude.replace(nullSequence, ''))1036  })1037})10381039describe('getProcessor function', () => {1040  it('Should return ALBProcessor for an ALBProxyEvent event', () => {1041    const event: ALBProxyEvent = {1042      httpMethod: 'GET',1043      path: '/',1044      body: null,1045      isBase64Encoded: false,1046      requestContext: {1047        elb: {1048          targetGroupArn:1049            'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',1050        },1051      },1052    }10531054    const processor = getProcessor(event)1055    expect(processor).toBeInstanceOf(ALBProcessor)1056  })10571058  it('Should return EventV1Processor for an event without requestContext', () => {1059    const event = {1060      httpMethod: 'GET',1061      path: '/',1062      body: null,1063      isBase64Encoded: false,1064    }10651066    // while LambdaEvent RequestContext property is mandatory, it can be absent when testing through invoke-api or AWS Console1067    // in such cases, a V1 processor should be returned1068    const processor = getProcessor(event as unknown as LambdaEvent)1069    expect(processor).toBeInstanceOf(EventV1Processor)1070  })10711072  it('Should return EventV2Processor for an APIGatewayProxyEventV2 event', () => {1073    const event: APIGatewayProxyEventV2 = {1074      version: '2.0',1075      routeKey: '$default',1076      headers: { 'content-type': 'text/plain' },1077      rawPath: '/',1078      rawQueryString: '',1079      body: null,1080      isBase64Encoded: false,1081      requestContext: testApiGatewayRequestContextV2,1082    }10831084    const processor = getProcessor(event)1085    expect(processor).toBeInstanceOf(EventV2Processor)1086  })1087})