Skip to content
Myr

index.test.ts

This file

Path

runtime-tests/lambda/index.test.ts

969 lines 路 29.2 KiB 路 TypeScript

Last changed by

chore: rename `runtime_tests` to `runtime-tests` (#3419)Yusuke Wadabefore adoptiondfbd717

History of this file

Take it

1import { Readable } from 'stream'2import { handle, streamHandle } from '../../src/adapter/aws-lambda/handler'3import type { LambdaEvent } from '../../src/adapter/aws-lambda/handler'4import type {5  ApiGatewayRequestContext,6  ApiGatewayRequestContextV2,7  LambdaContext,8} 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  app.get('/query-params', (c) => {112    const queryParams = c.req.query()113    return c.json(queryParams)114  })115116  app.get('/multi-query-params', (c) => {117    const multiQueryParams = c.req.queries()118    return c.json(multiQueryParams)119  })120121  const testCookie1 = {122    key: 'id',123    value: crypto.randomUUID(),124    get serialized() {125      return `${this.key}=${this.value}; Path=/`126    },127  }128  const testCookie2 = {129    key: 'secret',130    value: crypto.randomUUID(),131    get serialized() {132      return `${this.key}=${this.value}; Path=/`133    },134  }135136  app.post('/cookie', (c) => {137    setCookie(c, testCookie1.key, testCookie1.value)138    setCookie(c, testCookie2.key, testCookie2.value)139    return c.text('Cookies Set')140  })141142  app.get('/cookie', (c) => {143    const validCookies =144      getCookie(c, testCookie1.key) === testCookie1.value &&145      getCookie(c, testCookie2.key) === testCookie2.value146    if (!validCookies) {147      return c.text('Invalid Cookies')148    }149    return c.text('Valid Cookies')150  })151152  app.post('/headers', (c) => {153    if (c.req.header('foo')?.includes('bar')) {154      return c.json({ message: 'ok' })155    }156    return c.json({ message: 'fail' }, 400)157  })158159  const handler = handle(app)160161  const testApiGatewayRequestContext = {162    accountId: '123456789012',163    apiId: 'id',164    authorizer: {165      claims: null,166      scopes: null,167    },168    domainName: 'example.com',169    domainPrefix: 'id',170    extendedRequestId: 'request-id',171    httpMethod: 'GET',172    identity: {173      sourceIp: 'IP',174      userAgent: 'user-agent',175    },176    path: '/my/path',177    protocol: 'HTTP/1.1',178    requestId: 'id=',179    requestTime: '04/Mar/2020:19:15:17 +0000',180    requestTimeEpoch: 1583349317135,181    resourcePath: '/',182    stage: '$default',183    customProperty: 'customValue',184  }185186  const testApiGatewayRequestContextV2 = {187    accountId: '123456789012',188    apiId: 'urlid',189    authentication: null,190    authorizer: {191      iam: {192        accessKey: 'AKIA...',193        accountId: '111122223333',194        callerId: 'AIDA...',195        cognitoIdentity: null,196        principalOrgId: null,197        userArn: 'arn:aws:iam::111122223333:user/example-user',198        userId: 'AIDA...',199      },200    },201    domainName: 'example.com',202    domainPrefix: '<url-id>',203    http: {204      method: 'POST',205      path: '/my/path',206      protocol: 'HTTP/1.1',207      sourceIp: '123.123.123.123',208      userAgent: 'agent',209    },210    requestId: 'id',211    routeKey: '$default',212    stage: '$default',213    time: '12/Mar/2020:19:03:58 +0000',214    timeEpoch: 1583348638390,215    customProperty: 'customValue',216  }217218  const testALBRequestContext = {219    elb: {220      targetGroupArn:221        'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',222    },223  }224225  it('Should handle a GET request and return a 200 response', async () => {226    const event = {227      version: '1.0',228      resource: '/',229      httpMethod: 'GET',230      headers: { 'content-type': 'text/plain' },231      path: '/',232      body: null,233      isBase64Encoded: false,234      requestContext: testApiGatewayRequestContext,235    }236237    const response = await handler(event)238    expect(response.statusCode).toBe(200)239    expect(response.body).toBe('Hello Lambda!')240    expect(response.headers['content-type']).toMatch(/^text\/plain/)241    expect(response.isBase64Encoded).toBe(false)242  })243244  it('Should handle a GET request and return a 200 response with binary', async () => {245    const event = {246      version: '1.0',247      resource: '/binary',248      httpMethod: 'GET',249      headers: {},250      path: '/binary',251      body: null,252      isBase64Encoded: false,253      requestContext: testApiGatewayRequestContext,254    }255256    const response = await handler(event)257    expect(response.statusCode).toBe(200)258    expect(response.body).toBe('RmFrZSBJbWFnZQ==')259    expect(response.headers['content-type']).toMatch(/^image\/png/)260    expect(response.isBase64Encoded).toBe(true)261  })262263  it('Should handle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {264    const event = {265      version: '2.0',266      routeKey: '$default',267      headers: { 'content-type': 'text/plain' },268      rawPath: '/',269      rawQueryString: '',270      body: null,271      isBase64Encoded: false,272      requestContext: testApiGatewayRequestContextV2,273    }274275    testApiGatewayRequestContextV2.http.method = 'GET'276277    const response = await handler(event)278    expect(response.statusCode).toBe(200)279    expect(response.body).toBe('Hello Lambda!')280    expect(response.headers['content-type']).toMatch(/^text\/plain/)281    expect(response.isBase64Encoded).toBe(false)282  })283284  it('Should handle a GET request and return a 200 response (ALBEvent)', async () => {285    const event = {286      headers: { 'content-type': 'text/plain' },287      httpMethod: 'GET',288      path: '/',289      queryStringParameters: {290        query: '1234ABCD',291      },292      body: null,293      isBase64Encoded: false,294      requestContext: testALBRequestContext,295    }296297    const response = await handler(event)298    expect(response.statusCode).toBe(200)299    expect(response.body).toBe('Hello Lambda!')300    expect(response.headers['content-type']).toMatch(/^text\/plain/)301    expect(response.isBase64Encoded).toBe(false)302  })303304  it('Should handle a GET request and return a 404 response', async () => {305    const event = {306      version: '1.0',307      resource: '/nothing',308      httpMethod: 'GET',309      headers: { 'content-type': 'text/plain' },310      path: '/nothing',311      body: null,312      isBase64Encoded: false,313      requestContext: testApiGatewayRequestContext,314    }315316    const response = await handler(event)317    expect(response.statusCode).toBe(404)318  })319320  it('Should handle a POST request and return a 200 response', async () => {321    const searchParam = new URLSearchParams()322    searchParam.append('message', 'Good Morning Lambda!')323    const event = {324      version: '1.0',325      resource: '/post',326      httpMethod: 'POST',327      headers: {328        'Content-Type': 'application/x-www-form-urlencoded',329      },330      path: '/post',331      body: Buffer.from(searchParam.toString()).toString('base64'),332      isBase64Encoded: true,333      requestContext: testApiGatewayRequestContext,334    }335336    const response = await handler(event)337    expect(response.statusCode).toBe(200)338    expect(response.body).toBe('Good Morning Lambda!')339  })340341  it('Should handle a POST request and return a 200 response (LambdaFunctionUrlEvent)', async () => {342    const searchParam = new URLSearchParams()343    searchParam.append('message', 'Good Morning Lambda!')344    const event = {345      version: '2.0',346      routeKey: '$default',347      headers: {348        'Content-Type': 'application/x-www-form-urlencoded',349      },350      rawPath: '/post',351      rawQueryString: '',352      body: Buffer.from(searchParam.toString()).toString('base64'),353      isBase64Encoded: true,354      requestContext: testApiGatewayRequestContextV2,355    }356357    testApiGatewayRequestContextV2.http.method = 'POST'358359    const response = await handler(event)360    expect(response.statusCode).toBe(200)361    expect(response.body).toBe('Good Morning Lambda!')362  })363364  it('Should handle a POST request with binary and return a 200 response', async () => {365    const array = new Uint8Array([0xc0, 0xff, 0xee])366    const buffer = Buffer.from(array)367    const event = {368      version: '1.0',369      resource: '/post/binary',370      httpMethod: 'POST',371      headers: {372        'Content-Type': 'application/x-www-form-urlencoded',373      },374      path: '/post/binary',375      body: buffer.toString('base64'),376      isBase64Encoded: true,377      requestContext: testApiGatewayRequestContext,378    }379380    const response = await handler(event)381    expect(response.statusCode).toBe(200)382    expect(response.body).toBe('3 bytes')383  })384385  it('Should handle a request and return a 401 response with Basic auth', async () => {386    const event = {387      version: '1.0',388      resource: '/auth/abc',389      httpMethod: 'GET',390      headers: {391        'Content-Type': 'plain/text',392      },393      path: '/auth/abc',394      body: null,395      isBase64Encoded: true,396      requestContext: testApiGatewayRequestContext,397    }398399    const response = await handler(event)400    expect(response.statusCode).toBe(401)401  })402403  it('Should handle a request and return a 200 response with Basic auth', async () => {404    const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'405    const event = {406      version: '1.0',407      resource: '/auth/abc',408      httpMethod: 'GET',409      headers: {410        'Content-Type': 'plain/text',411        Authorization: `Basic ${credential}`,412      },413      path: '/auth/abc',414      body: null,415      isBase64Encoded: true,416      requestContext: testApiGatewayRequestContext,417    }418419    const response = await handler(event)420    expect(response.statusCode).toBe(200)421    expect(response.body).toBe('Good Night Lambda!')422  })423424  it('Should handle a GET request and return custom context', async () => {425    const event = {426      version: '1.0',427      resource: '/custom-context/apigw',428      httpMethod: 'GET',429      headers: { 'content-type': 'application/json' },430      path: '/custom-context/apigw',431      body: null,432      isBase64Encoded: false,433      requestContext: testApiGatewayRequestContext,434    }435436    const response = await handler(event)437    expect(response.statusCode).toBe(200)438    expect(JSON.parse(response.body).customProperty).toEqual('customValue')439  })440441  it('Should handle a GET request and context', async () => {442    const event = {443      version: '1.0',444      resource: '/lambda-context',445      httpMethod: 'GET',446      headers: { 'content-type': 'application/json' },447      path: '/lambda-context',448      body: null,449      isBase64Encoded: false,450      requestContext: testApiGatewayRequestContext,451    }452    const context: LambdaContext = {453      callbackWaitsForEmptyEventLoop: false,454      functionName: 'myLambdaFunction',455      functionVersion: '1.0.0',456      invokedFunctionArn: 'arn:aws:lambda:us-west-2:123456789012:function:myLambdaFunction',457      memoryLimitInMB: '128',458      awsRequestId: 'c6af9ac6-a7b0-11e6-80f5-76304dec7eb7',459      logGroupName: '/aws/lambda/myLambdaFunction',460      logStreamName: '2016/11/14/[$LATEST]f2d4b21cfb33490da2e8f8ef79a483s4',461      getRemainingTimeInMillis: () => {462        return 60000 // 60 seconds463      },464    }465    const response = await handler(event, context)466    expect(response.statusCode).toBe(200)467    expect(JSON.parse(response.body).callbackWaitsForEmptyEventLoop).toEqual(false)468  })469470  it('Should handle a POST request and return a 200 response with cookies set (APIGatewayProxyEvent V1 and V2)', async () => {471    const apiGatewayEvent = {472      version: '1.0',473      resource: '/cookie',474      httpMethod: 'POST',475      headers: { 'content-type': 'text/plain' },476      path: '/cookie',477      body: null,478      isBase64Encoded: false,479      requestContext: testApiGatewayRequestContext,480    }481482    const apiGatewayResponse = await handler(apiGatewayEvent)483484    expect(apiGatewayResponse.statusCode).toBe(200)485    expect(apiGatewayResponse.multiValueHeaders).toHaveProperty('set-cookie', [486      testCookie1.serialized,487      testCookie2.serialized,488    ])489490    const apiGatewayEventV2 = {491      version: '2.0',492      routeKey: '$default',493      httpMethod: 'POST',494      headers: { 'content-type': 'text/plain' },495      rawPath: '/cookie',496      rawQueryString: '',497      body: null,498      isBase64Encoded: false,499      requestContext: testApiGatewayRequestContextV2,500    }501502    const apiGatewayResponseV2 = await handler(apiGatewayEventV2)503504    expect(apiGatewayResponseV2.statusCode).toBe(200)505    expect(apiGatewayResponseV2).toHaveProperty('cookies', [506      testCookie1.serialized,507      testCookie2.serialized,508    ])509  })510511  describe('headers', () => {512    describe('single-value headers', () => {513      it('Should extract single-value headers and return 200 (ALBProxyEvent)', async () => {514        const event = {515          body: '{}',516          httpMethod: 'POST',517          isBase64Encoded: false,518          path: '/headers',519          headers: {520            host: 'localhost',521            foo: 'bar',522          },523          requestContext: testALBRequestContext,524        }525        const albResponse = await handler(event)526        expect(albResponse.statusCode).toBe(200)527        expect(albResponse.headers).toEqual(528          expect.objectContaining({529            'content-type': 'application/json; charset=UTF-8',530          })531        )532      })533534      it('Should extract single-value headers and return 200 (APIGatewayProxyEvent)', async () => {535        const apigatewayProxyEvent = {536          version: '1.0',537          resource: '/headers',538          httpMethod: 'POST',539          headers: {540            host: 'localhost',541            foo: 'bar',542          },543          path: '/headers',544          body: null,545          isBase64Encoded: false,546          requestContext: testApiGatewayRequestContext,547        }548        const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)549        expect(apiGatewayResponseV2.statusCode).toBe(200)550      })551552      it('Should extract single-value headers and return 200 (APIGatewayProxyEventV2)', async () => {553        const apigatewayProxyV2Event = {554          version: '2.0',555          routeKey: '$default',556          headers: {557            host: 'localhost',558            foo: 'bar',559          },560          rawPath: '/headers',561          rawQueryString: '',562          requestContext: testApiGatewayRequestContextV2,563          resource: '/headers',564          body: null,565          isBase64Encoded: false,566        }567        const apiGatewayResponseV2 = await handler(apigatewayProxyV2Event)568        expect(apiGatewayResponseV2.statusCode).toBe(200)569      })570    })571572    describe('multi-value headers', () => {573      it('Should extract multi-value headers and return 200 (ALBProxyEvent)', async () => {574        const event = {575          body: '{}',576          httpMethod: 'POST',577          isBase64Encoded: false,578          path: '/headers',579          multiValueHeaders: {580            host: ['localhost'],581            foo: ['bar'],582          },583          requestContext: testALBRequestContext,584        }585        const albResponse = await handler(event)586        expect(albResponse.statusCode).toBe(200)587        expect(albResponse.multiValueHeaders).toBeDefined()588        expect(albResponse.multiValueHeaders).toEqual(589          expect.objectContaining({590            'content-type': ['application/json; charset=UTF-8'],591          })592        )593      })594595      it('Should extract multi-value headers and return 200 (APIGatewayProxyEvent)', async () => {596        const apigatewayProxyEvent = {597          version: '1.0',598          resource: '/headers',599          httpMethod: 'POST',600          headers: {},601          multiValueHeaders: {602            host: ['localhost'],603            foo: ['bar'],604          },605          path: '/headers',606          body: null,607          isBase64Encoded: false,608          requestContext: testApiGatewayRequestContext,609        }610        const apiGatewayResponseV2 = await handler(apigatewayProxyEvent)611        expect(apiGatewayResponseV2.statusCode).toBe(200)612      })613    })614  })615616  it('Should handle a POST request and return a 200 response if cookies match (APIGatewayProxyEvent V1 and V2)', async () => {617    const apiGatewayEvent = {618      version: '1.0',619      resource: '/cookie',620      httpMethod: 'GET',621      headers: {622        'content-type': 'text/plain',623        cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),624      },625      path: '/cookie',626      body: null,627      isBase64Encoded: false,628      requestContext: testApiGatewayRequestContext,629    }630631    const apiGatewayResponse = await handler(apiGatewayEvent)632633    expect(apiGatewayResponse.statusCode).toBe(200)634    expect(apiGatewayResponse.body).toBe('Valid Cookies')635    expect(apiGatewayResponse.headers['content-type']).toMatch(/^text\/plain/)636    expect(apiGatewayResponse.isBase64Encoded).toBe(false)637638    const apiGatewayEventV2 = {639      version: '2.0',640      routeKey: '$default',641      headers: { 'content-type': 'text/plain' },642      rawPath: '/cookie',643      cookies: [testCookie1.serialized, testCookie2.serialized],644      rawQueryString: '',645      body: null,646      isBase64Encoded: false,647      requestContext: testApiGatewayRequestContextV2,648    }649    testApiGatewayRequestContextV2.http.method = 'GET'650651    const apiGatewayResponseV2 = await handler(apiGatewayEventV2)652653    expect(apiGatewayResponseV2.statusCode).toBe(200)654    expect(apiGatewayResponseV2.body).toBe('Valid Cookies')655    expect(apiGatewayResponseV2.headers['content-type']).toMatch(/^text\/plain/)656    expect(apiGatewayResponseV2.isBase64Encoded).toBe(false)657  })658659  it('Should handle a GET request and return a 200 response if cookies match (ALBProxyEvent) with default headers', async () => {660    const albEventDefaultHeaders = {661      version: '1.0',662      resource: '/cookie',663      httpMethod: 'GET',664      headers: {665        'content-type': 'text/plain',666        cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),667      },668      path: '/cookie',669      body: null,670      isBase64Encoded: false,671      requestContext: testALBRequestContext,672    }673674    const albResponse = await handler(albEventDefaultHeaders)675676    expect(albResponse.statusCode).toBe(200)677    expect(albResponse.body).toBe('Valid Cookies')678    expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)679    expect(albResponse.isBase64Encoded).toBe(false)680  })681682  it('Should handle a GET request and return a 200 response if cookies match (ALBProxyEvent) with multi value headers', async () => {683    const albEventMultiValueHeaders = {684      version: '1.0',685      resource: '/cookie',686      httpMethod: 'GET',687      multiValueHeaders: {688        'content-type': ['text/plain'],689        cookie: [testCookie1.serialized, testCookie2.serialized],690      },691      path: '/cookie',692      body: null,693      isBase64Encoded: false,694      requestContext: testALBRequestContext,695    }696697    const albResponse = await handler(albEventMultiValueHeaders)698699    expect(albResponse.statusCode).toBe(200)700    expect(albResponse.body).toBe('Valid Cookies')701    expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)702    expect(albResponse.isBase64Encoded).toBe(false)703  })704705  it('Should handle a POST request and return a 200 response with cookies (ALBProxyEvent) with default headers', async () => {706    const albEventDefaultHeaders = {707      version: '1.0',708      resource: '/cookie',709      httpMethod: 'POST',710      headers: {711        'content-type': 'text/plain',712        cookie: [testCookie1.serialized, testCookie2.serialized].join(', '),713      },714      path: '/cookie',715      body: null,716      isBase64Encoded: false,717      requestContext: testALBRequestContext,718    }719720    const albResponse = await handler(albEventDefaultHeaders)721722    expect(albResponse.statusCode).toBe(200)723    expect(albResponse.body).toBe('Cookies Set')724    expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)725    expect(albResponse.multiValueHeaders).toBeUndefined()726    expect(albResponse.headers['set-cookie']).toEqual(727      [testCookie1.serialized, testCookie2.serialized].join(', ')728    )729    expect(albResponse.isBase64Encoded).toBe(false)730  })731732  it('Should handle a POST request and return a 200 response with cookies (ALBProxyEvent) with multi value headers', async () => {733    const albEventDefaultHeaders = {734      version: '1.0',735      resource: '/cookie',736      httpMethod: 'POST',737      multiValueHeaders: {738        'content-type': ['text/plain'],739        cookie: [testCookie1.serialized, testCookie2.serialized],740      },741      path: '/cookie',742      body: null,743      isBase64Encoded: false,744      requestContext: testALBRequestContext,745    }746747    const albResponse = await handler(albEventDefaultHeaders)748749    expect(albResponse.statusCode).toBe(200)750    expect(albResponse.body).toBe('Cookies Set')751    expect(albResponse.headers['content-type']).toMatch(/^text\/plain/)752    expect(albResponse.multiValueHeaders).toBeDefined()753    expect(albResponse.multiValueHeaders && albResponse.multiValueHeaders['set-cookie']).toEqual(754      expect.arrayContaining([testCookie1.serialized, testCookie2.serialized])755    )756    expect(albResponse.isBase64Encoded).toBe(false)757  })758759  it('Should handle a GET request and return a 200 response with queryStringParameters (ALBProxyEvent)', async () => {760    const albEventDefaultHeaders = {761      resource: '/query-params',762      httpMethod: 'GET',763      headers: {764        'content-type': 'application/json',765      },766      queryStringParameters: {767        key1: 'value1',768        key2: 'value2',769      },770      path: '/query-params',771      body: null,772      isBase64Encoded: false,773      requestContext: testALBRequestContext,774    }775776    const albResponse = await handler(albEventDefaultHeaders)777778    expect(albResponse.statusCode).toBe(200)779    expect(albResponse.body).toContain(780      JSON.stringify({781        key1: 'value1',782        key2: 'value2',783      })784    )785    expect(albResponse.headers['content-type']).toMatch(/^application\/json/)786    expect(albResponse.isBase64Encoded).toBe(false)787  })788789  it('Should handle a GET request and return a 200 response with single value multiQueryStringParameters (ALBProxyEvent)', async () => {790    const albEventDefaultHeaders = {791      resource: '/query-params',792      httpMethod: 'GET',793      multiValueHeaders: {794        'content-type': ['application/json'],795      },796      multiValueQueryStringParameters: {797        key1: ['value1'],798        key2: ['value2'],799      },800      path: '/query-params',801      body: null,802      isBase64Encoded: false,803      requestContext: testALBRequestContext,804    }805806    const albResponse = await handler(albEventDefaultHeaders)807808    expect(albResponse.statusCode).toBe(200)809    expect(albResponse.body).toContain(810      JSON.stringify({811        key1: 'value1',812        key2: 'value2',813      })814    )815    expect(albResponse.headers['content-type']).toMatch(/^application\/json/)816    expect(albResponse.isBase64Encoded).toBe(false)817  })818819  it('Should handle a GET request and return a 200 response with multi value multiQueryStringParameters (ALBProxyEvent)', async () => {820    const albEventDefaultHeaders = {821      resource: '/query-params',822      httpMethod: 'GET',823      multiValueHeaders: {824        'content-type': ['application/json'],825      },826      multiValueQueryStringParameters: {827        key1: ['value1'],828        key2: ['value2', 'otherValue2'],829      },830      path: '/multi-query-params',831      body: null,832      isBase64Encoded: false,833      requestContext: testALBRequestContext,834    }835836    const albResponse = await handler(albEventDefaultHeaders)837838    expect(albResponse.statusCode).toBe(200)839    expect(albResponse.body).toContain(840      JSON.stringify({841        key1: ['value1'],842        key2: ['value2', 'otherValue2'],843      })844    )845    expect(albResponse.headers['content-type']).toMatch(/^application\/json/)846    expect(albResponse.isBase64Encoded).toBe(false)847  })848})849850describe('streamHandle function', () => {851  const app = new Hono<{ Bindings: Bindings }>()852853  app.get('/', (c) => {854    return c.text('Hello Lambda!')855  })856857  app.get('/stream/text', async (c) => {858    return c.streamText(async (stream) => {859      for (let i = 0; i < 3; i++) {860        await stream.writeln(`${i}`)861        await stream.sleep(1)862      }863    })864  })865866  app.get('/sse', async (c) => {867    return streamSSE(c, async (stream) => {868      let id = 0869      const maxIterations = 2870871      while (id < maxIterations) {872        const message = `Message\nIt is ${id}`873        await stream.writeSSE({ data: message, event: 'time-update', id: String(id++) })874        await stream.sleep(10)875      }876    })877  })878879  const handler = streamHandle(app)880881  it('Should streamHandle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {882    const event = {883      headers: { 'content-type': ' binary/octet-stream' },884      rawPath: '/stream/text',885      rawQueryString: '',886      body: null,887      isBase64Encoded: false,888      requestContext: testApiGatewayRequestContextV2,889    }890891    testApiGatewayRequestContextV2.http.method = 'GET'892893    const mockReadableStream = new Readable({894      // eslint-disable-next-line @typescript-eslint/no-empty-function895      read() {},896    })897898    mockReadableStream.push('0\n')899    mockReadableStream.push('1\n')900    mockReadableStream.push('2\n')901    mockReadableStream.push('3\n')902    mockReadableStream.push(null) // EOF903904    await handler(event, mockReadableStream)905906    const chunks = []907    for await (const chunk of mockReadableStream) {908      chunks.push(chunk)909    }910    expect(chunks.join('')).toContain('0\n1\n2\n3\n')911  })912913  it('Should handle a GET request for an SSE stream and return the correct chunks', async () => {914    const event = {915      headers: { 'content-type': 'text/event-stream' },916      rawPath: '/sse',917      rawQueryString: '',918      body: null,919      isBase64Encoded: false,920      requestContext: testApiGatewayRequestContextV2,921    }922923    testApiGatewayRequestContextV2.http.method = 'GET'924925    const mockReadableStream = new Readable({926      // eslint-disable-next-line @typescript-eslint/no-empty-function927      read() {},928    })929930    const initContentType = {931      'Content-Type': 'application/vnd.awslambda.http-integration-response',932    }933    mockReadableStream.push(JSON.stringify(initContentType))934935    // Send JSON formatted response headers, followed by 8 NULL characters as a separator936    const httpResponseMetadata = {937      statusCode: 200,938      headers: { 'Custom-Header': 'value' },939      cookies: ['session=abcd1234'],940    }941    const jsonResponsePrelude = JSON.stringify(httpResponseMetadata) + Buffer.alloc(8, 0).toString()942    mockReadableStream.push(jsonResponsePrelude)943944    mockReadableStream.push('data: Message\ndata: It is 0\n\n')945    mockReadableStream.push('data: Message\ndata: It is 1\n\n')946    mockReadableStream.push(null) // EOF947948    await handler(event, mockReadableStream)949950    const chunks = []951    for await (const chunk of mockReadableStream) {952      chunks.push(chunk)953    }954955    // If you have chunks, you might want to convert them to strings before checking956    const output = Buffer.concat(chunks).toString()957    expect(output).toContain('data: Message\ndata: It is 0\n\n')958    expect(output).toContain('data: Message\ndata: It is 1\n\n')959960    // Assertions for the newly added header and prelude961    expect(output).toContain('application/vnd.awslambda.http-integration-response')962    expect(output).toContain('Custom-Header')963    expect(output).toContain('session=abcd1234')964965    // Check for JSON prelude and NULL sequence966    const nullSequence = '\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000'967    expect(output).toContain(jsonResponsePrelude.replace(nullSequence, ''))968  })969})