Skip to content
Myr

chore: move runtime tests into `runtime_tests` (#1062)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* chore: move runtime tests into `runtime_tests` * fixed ci

authored by Yusuke Wada · committed by GitHub · parent db7ad68 · Browse files · 40 files+1056 added−1049 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

40 files+1056 added−1049 removed

  • tests:+858 added−855 removed
  • other:+198 added−194 removed

40 files+1056 added−1049 removed

modified:.github/workflows/ci.yml+1 added-1 removed
added:runtime_tests/bun/favicon.icobinary

A binary file, added.

added:runtime_tests/bun/index.test.tsx+170 added
1import { describe, expect, it } from 'bun:test'2import { env } from '../../src/adapter'3import { serveStatic } from '../../src/adapter/bun'4import { Context } from '../../src/context'5import { Hono } from '../../src/index'6import { basicAuth } from '../../src/middleware/basic-auth'7import { jwt } from '../../src/middleware/jwt'89// Test just only minimal patterns.10// Because others are tested well in Cloudflare Workers environment already.1112describe('Basic', () => {13 const app = new Hono()14 app.get('/a/:foo', (c) => {15 c.header('x-param', c.req.param('foo'))16 c.header('x-query', c.req.query('q'))17 return c.text('Hello Bun!')18 })1920 it('Should return 200 Response', async () => {21 const req = new Request('http://localhost/a/foo?q=bar')22 const res = await app.request(req)23 expect(res.status).toBe(200)24 expect(await res.text()).toBe('Hello Bun!')25 expect(res.headers.get('x-param')).toBe('foo')26 expect(res.headers.get('x-query')).toBe('bar')27 })2829 it('returns current runtime (bun)', async () => {30 const c = new Context(new Request('http://localhost/'))31 expect(c.runtime).toBe('bun')32 })33})3435describe('Environment Variables', () => {36 it('Should return the environment variable', async () => {37 const c = new Context(new Request('http://localhost/'))38 const { NAME } = env<{ NAME: string }>(c)39 expect(NAME).toBe('Bun')40 })41})4243describe('Basic Auth Middleware', () => {44 const app = new Hono()4546 const username = 'hono-user-a'47 const password = 'hono-password-a'48 app.use(49 '/auth/*',50 basicAuth({51 username,52 password,53 })54 )5556 app.get('/auth/*', () => new Response('auth'))5758 it('Should not authorize, return 401 Response', async () => {59 const req = new Request('http://localhost/auth/a')60 const res = await app.request(req)61 expect(res.status).toBe(401)62 expect(await res.text()).toBe('Unauthorized')63 })6465 it('Should authorize, return 200 Response', async () => {66 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'67 const req = new Request('http://localhost/auth/a')68 req.headers.set('Authorization', `Basic ${credential}`)69 const res = await app.request(req)70 expect(res.status).toBe(200)71 expect(await res.text()).toBe('auth')72 })73})7475describe('Serve Static Middleware', () => {76 const app = new Hono()77 app.all('/favicon.ico', serveStatic({ path: './runtime_tests/bun/favicon.ico' }))78 app.all('/favicon-notfound.ico', serveStatic({ path: './test_bun/favicon-notfound.ico' }))79 app.use('/favicon-notfound.ico', async (c, next) => {80 await next()81 c.header('X-Custom', 'Bun')82 })8384 it('Should return static file correctly', async () => {85 const res = await app.request(new Request('http://localhost/favicon.ico'))86 await res.arrayBuffer()87 expect(res.status).toBe(200)88 expect(res.headers.get('Content-Type')).toBe('image/x-icon')89 })9091 it('Should return 404 response', async () => {92 const res = await app.request(new Request('http://localhost/favicon-notfound.ico'))93 expect(res.status).toBe(404)94 expect(res.headers.get('X-Custom')).toBe('Bun')95 })96})9798// Bun support WebCrypto since v0.2.299// So, JWT middleware works well.100describe('JWT Auth Middleware', () => {101 const app = new Hono()102 app.use('/jwt/*', jwt({ secret: 'a-secret' }))103 app.get('/jwt/a', (c) => c.text('auth'))104105 it('Should not authorize, return 401 Response', async () => {106 const req = new Request('http://localhost/jwt/a')107 const res = await app.request(req)108 expect(res.status).toBe(401)109 expect(await res.text()).toBe('Unauthorized')110 })111112 it('Should authorize, return 200 Response', async () => {113 const credential =114 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'115 const req = new Request('http://localhost/jwt/a')116 req.headers.set('Authorization', `Bearer ${credential}`)117 const res = await app.request(req)118 expect(res.status).toBe(200)119 expect(await res.text()).toBe('auth')120 })121})122123// To enable JSX middleware,124// set "jsxImportSource": "hono/jsx" in the tsconfig.json125describe('JSX Middleware', () => {126 const app = new Hono()127128 const Layout = (props: { children?: string }) => {129 return <html>{props.children}</html>130 }131132 app.get('/', (c) => {133 return c.html(<h1>Hello</h1>)134 })135 app.get('/nest', (c) => {136 return c.html(137 <h1>138 <a href='/top'>Hello</a>139 </h1>140 )141 })142 app.get('/layout', (c) => {143 return c.html(144 <Layout>145 <p>hello</p>146 </Layout>147 )148 })149150 it('Should return rendered HTML', async () => {151 const res = await app.request(new Request('http://localhost/'))152 expect(res.status).toBe(200)153 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')154 expect(await res.text()).toBe('<h1>Hello</h1>')155 })156157 it('Should return rendered HTML with nest', async () => {158 const res = await app.request(new Request('http://localhost/nest'))159 expect(res.status).toBe(200)160 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')161 expect(await res.text()).toBe('<h1><a href="/top">Hello</a></h1>')162 })163164 it('Should return rendered HTML with Layout', async () => {165 const res = await app.request(new Request('http://localhost/layout'))166 expect(res.status).toBe(200)167 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')168 expect(await res.text()).toBe('<html><p>hello</p></html>')169 })170})
added:runtime_tests/deno/.vscode/settings.json+12 added
added:runtime_tests/deno/deps.ts+1 added
added:runtime_tests/deno/favicon.icobinary

A binary file, added.

added:runtime_tests/deno/hono.test.ts+32 added
added:runtime_tests/deno/middleware.test.tsx+105 added
1/** @jsx jsx */2/** @jsxFrag Fragment */3import { basicAuth, jsx, Fragment, serveStatic, jwt } from '../../deno_dist/middleware.ts'4import { Hono } from '../../deno_dist/mod.ts'5import { assertEquals, assertMatch } from './deps.ts'67// Test just only minimal patterns.8// Because others are already tested well in Cloudflare Workers environment.910Deno.test('Basic Auth Middleware', async () => {11 const app = new Hono()1213 const username = 'hono-user-a'14 const password = 'hono-password-a'1516 app.use(17 '/auth/*',18 basicAuth({19 username,20 password,21 })22 )2324 app.get('/auth/*', () => new Response('auth'))2526 const res = await app.request('http://localhost/auth/a')27 assertEquals(res.status, 401)28 assertEquals(await res.text(), 'Unauthorized')2930 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'3132 const req = new Request('http://localhost/auth/a')33 req.headers.set('Authorization', `Basic ${credential}`)34 const resOK = await app.request(req)35 assertEquals(resOK.status, 200)36 assertEquals(await resOK.text(), 'auth')37})3839Deno.test('JSX middleware', async () => {40 const app = new Hono()41 app.get('/', (c) => {42 return c.html(<h1>Hello</h1>)43 })44 const res = await app.request('http://localhost/')45 assertEquals(res.status, 200)46 assertEquals(res.headers.get('Content-Type'), 'text/html; charset=UTF-8')47 assertEquals(await res.text(), '<h1>Hello</h1>')4849 // Fragment50 const template = (51 <>52 <p>1</p>53 <p>2</p>54 </>55 )56 assertEquals(template.toString(), '<p>1</p><p>2</p>')57})5859Deno.test('Serve Static middleware', async () => {60 const app = new Hono()61 app.all('/favicon.ico', serveStatic({ path: './runtime_tests/deno/favicon.ico' }))62 app.all(63 '/favicon-notfound.ico',64 serveStatic({ path: './runtime_tests/deno/favicon-notfound.ico' })65 )66 app.use('/favicon-notfound.ico', async (c, next) => {67 await next()68 c.header('X-Custom', 'Deno')69 })70 let res = await app.request('http://localhost/favicon.ico')71 assertEquals(res.status, 200)72 assertEquals(res.headers.get('Content-Type'), 'image/x-icon')73 res = await app.request('http://localhost/favicon-notfound.ico')74 assertEquals(res.status, 404)75 assertMatch(res.headers.get('Content-Type') || '', /^text\/plain/)76 assertEquals(res.headers.get('X-Custom'), 'Deno')77})7879Deno.test('JWT Authentication middleware', async () => {80 const app = new Hono<{ Variables: { 'x-foo': string } }>()81 app.use('/*', async (c, next) => {82 await next()83 c.header('x-foo', c.get('x-foo') || '')84 })85 app.use('/auth/*', jwt({ secret: 'a-secret' }))86 app.get('/auth/*', (c) => {87 c.set('x-foo', 'bar')88 return new Response('auth')89 })9091 const req = new Request('http://localhost/auth/a')92 const res = await app.request(req)93 assertEquals(res.status, 401)94 assertEquals(await res.text(), 'Unauthorized')95 assertEquals(res.headers.get('x-foo'), '')9697 const credential =98 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'99 const reqOK = new Request('http://localhost/auth/a')100 reqOK.headers.set('Authorization', `Bearer ${credential}`)101 const resOK = await app.request(reqOK)102 assertEquals(resOK.status, 200)103 assertEquals(await resOK.text(), 'auth')104 assertEquals(resOK.headers.get('x-foo'), 'bar')105})
added:runtime_tests/fastly/index.test.ts+96 added
1import { SHA256 } from 'crypto-js'2import { Hono } from '../../src/index'3import { basicAuth } from '../../src/middleware/basic-auth'4import { jwt } from '../../src/middleware/jwt'56// eslint-disable-next-line @typescript-eslint/ban-ts-comment7// @ts-ignore8globalThis.fastly = true910const app = new Hono()1112describe('Hello World', () => {13 app.get('/', (c) => c.text('Hello! Compute!'))14 app.get('/runtime-name', (c) => {15 return c.text(c.runtime)16 })1718 it('Should return 200', async () => {19 const res = await app.request('http://localhost/')20 expect(res.status).toBe(200)21 expect(await res.text()).toBe('Hello! Compute!')22 })2324 it('Should return the correct runtime name', async () => {25 const res = await app.request('http://localhost/runtime-name')26 expect(res.status).toBe(200)27 expect(await res.text()).toBe('fastly')28 })29})3031describe('Basic Auth Middleware without `hashFunction`', () => {32 const app = new Hono()3334 const username = 'hono-user-a'35 const password = 'hono-password-a'36 app.use(37 '/auth/*',38 basicAuth({39 username,40 password,41 })42 )4344 app.get('/auth/*', () => new Response('auth'))4546 it('Should authorize, return 401 Response', async () => {47 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'48 const req = new Request('http://localhost/auth/a')49 req.headers.set('Authorization', `Basic ${credential}`)50 const res = await app.request(req)51 expect(res.status).toBe(401)52 })53})5455describe('Basic Auth Middleware with `hashFunction`', () => {56 const app = new Hono()5758 const username = 'hono-user-a'59 const password = 'hono-password-a'60 app.use(61 '/auth/*',62 basicAuth({63 username,64 password,65 hashFunction: (m: string) => SHA256(m).toString(),66 })67 )6869 app.get('/auth/*', () => new Response('auth'))7071 it('Should not authorize, return 401 Response', async () => {72 const req = new Request('http://localhost/auth/a')73 const res = await app.request(req)74 expect(res.status).toBe(401)75 expect(await res.text()).toBe('Unauthorized')76 })7778 it('Should authorize, return 200 Response', async () => {79 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'80 const req = new Request('http://localhost/auth/a')81 req.headers.set('Authorization', `Basic ${credential}`)82 const res = await app.request(req)83 expect(res.status).toBe(200)84 expect(await res.text()).toBe('auth')85 })86})8788describe('JWT Auth Middleware does not work', () => {89 const app = new Hono()9091 it('Should throw error', () => {92 expect(() => {93 app.use('/jwt/*', jwt({ secret: 'secret' }))94 }).toThrow(/`crypto.subtle.importKey` is undefined/)95 })96})
added:runtime_tests/fastly/jest.config.js+8 added
added:runtime_tests/lagon/.env.lagon+1 added
1NAME=Lagon
added:runtime_tests/lagon/index.test.ts+209 added
1describe('Example', () => {2 test('GET /', async () => {3 const res = await fetch('http://127.0.0.1:1234')4 expect(res.status).toBe(200)5 expect(await res.text()).toBe('Hono!!')6 expect(res.headers.get('x-powered-by')).toBe('Hono')7 expect(res.headers.get('x-response-time')).toContain('ms')8 })910 test('GET /hello/anything', async () => {11 const res = await fetch('http://127.0.0.1:1234/hello/anything')12 expect(res.status).toBe(404)13 expect(res.headers.get('x-message')).toBe('This is addHeader middleware!')14 })1516 test('GET /hello', async () => {17 const res = await fetch('http://127.0.0.1:1234/hello')18 expect(res.status).toBe(200)19 expect(await res.text()).toBe('This is /hello')20 })2122 test('GET /runtime', async () => {23 const res = await fetch('http://127.0.0.1:1234/runtime')24 expect(res.status).toBe(200)25 expect(await res.text()).toBe('lagon')26 })2728 /*29 TODO: It can't resolve the file path `.env` on CI30 test('GET /env', async () => {31 const res = await fetch('http://127.0.0.1:1234/env')32 expect(res.status).toBe(200)33 expect(await res.text()).toBe('Lagon')34 })35 */3637 test('GET /entry/:id', async () => {38 const res = await fetch('http://127.0.0.1:1234/entry/42')39 expect(res.status).toBe(200)40 expect(await res.text()).toBe('Your ID is 42')41 })4243 describe('/book', () => {44 test('GET /book', async () => {45 const res = await fetch('http://127.0.0.1:1234/book')46 expect(res.status).toBe(200)47 expect(await res.text()).toBe('List Books')48 })4950 test('GET /book/:id', async () => {51 const res = await fetch('http://127.0.0.1:1234/book/3')52 expect(res.status).toBe(200)53 expect(await res.text()).toBe('Get Book: 3')54 })5556 test('POST /book', async () => {57 const res = await fetch('http://127.0.0.1:1234/book', {58 method: 'POST',59 })60 expect(res.status).toBe(200)61 expect(await res.text()).toBe('Create Book')62 })63 })6465 test('GET /redirect', async () => {66 const res = await fetch('http://127.0.0.1:1234/redirect', {67 redirect: 'manual',68 })69 expect(res.status).toBe(302)70 expect(res.headers.get('location')).toBe('/')71 })7273 describe('/basic-auth', () => {74 test('GET /basic-auth/anyroute unauthorized', async () => {75 const res = await fetch('http://127.0.0.1:1234/basic-auth/anyroute')76 expect(res.status).toBe(401)77 expect(await res.text()).toBe('Unauthorized')78 })7980 test('GET /basic-auth/anyroute', async () => {81 const res = await fetch('http://127.0.0.1:1234/basic-auth/anyroute', {82 headers: {83 authorization: `Basic ${btoa('hono:acoolproject')}`,84 },85 })86 expect(res.status).toBe(200)87 expect(await res.text()).toBe('You are authorized')88 })89 })9091 describe('/bearer-auth', () => {92 test('GET /bearer-auth/anyroute unauthorized', async () => {93 const res = await fetch('http://127.0.0.1:1234/bearer-auth/anyroute')94 expect(res.status).toBe(401)95 expect(await res.text()).toBe('Unauthorized')96 })9798 test('GET /bearer-auth/anyroute', async () => {99 const res = await fetch('http://127.0.0.1:1234/bearer-auth/anyroute', {100 headers: {101 authorization: 'Bearer secrettoken',102 },103 })104 expect(res.status).toBe(200)105 expect(await res.text()).toBe('You are authorized')106 })107 })108109 test('GET /etag/cached', async () => {110 const res = await fetch('http://127.0.0.1:1234/etag/cached')111 expect(res.status).toBe(200)112 expect(res.headers.get('etag')).toBe('"90ea638841fff3c326fc22cbd156f1146ac0ac02"')113 expect(await res.text()).toBe('Is this cached?')114 })115116 test('GET /fetch-url', async () => {117 const res = await fetch('http://127.0.0.1:1234/fetch-url')118 expect(res.status).toBe(200)119 expect(await res.text()).toBe('https://example.com/ is 200')120 })121122 test('GET /user-agent', async () => {123 const res = await fetch('http://127.0.0.1:1234/user-agent', {124 headers: {125 'user-agent': 'Lagon',126 },127 })128 expect(res.status).toBe(200)129 expect(await res.text()).toBe('Your UserAgent is Lagon')130 })131132 test('GET /api/posts', async () => {133 const res = await fetch('http://127.0.0.1:1234/api/posts')134 expect(res.status).toBe(200)135 expect(await res.json()).toEqual([136 { id: 1, title: 'Good Morning' },137 { id: 2, title: 'Good Aternoon' },138 { id: 3, title: 'Good Evening' },139 { id: 4, title: 'Good Night' },140 ])141 })142143 test('POST /api/posts', async () => {144 const res = await fetch('http://127.0.0.1:1234/api/posts', {145 method: 'POST',146 })147 expect(res.status).toBe(201)148 expect(await res.json()).toEqual({ message: 'Created!' })149 })150151 test('GET /api/default-route', async () => {152 const res = await fetch('http://127.0.0.1:1234/api/default-route')153 expect(res.status).toBe(404)154 expect(await res.text()).toBe('API endpoint is not found')155 })156157 describe('/form', () => {158 test('POST /form x-www-form-urlencoded', async () => {159 const res = await fetch('http://127.0.0.1:1234/form', {160 method: 'POST',161 headers: {162 'content-type': 'application/x-www-form-urlencoded',163 },164 body: 'username=john&password=Pa%24%24w0rd',165 })166 expect(res.status).toBe(200)167 expect(await res.json()).toEqual({168 password: 'Pa$$w0rd',169 username: 'john',170 })171 })172173 test('POST /form', async () => {174 const res = await fetch('http://127.0.0.1:1234/form', {175 method: 'POST',176 headers: {177 'content-type':178 'multipart/form-data; boundary=---------------------------9051914041544843365972754266',179 },180 body: `-----------------------------9051914041544843365972754266181Content-Disposition: form-data; name="hello"182183world!184-----------------------------9051914041544843365972754266185Content-Disposition: form-data; name="description"186187this is another field188-----------------------------9051914041544843365972754266--`,189 })190 expect(res.status).toBe(200)191 expect(await res.json()).toEqual({192 description: 'this is another field',193 hello: 'world!',194 })195 })196 })197198 test('GET /error', async () => {199 const res = await fetch('http://127.0.0.1:1234/error')200 expect(res.status).toBe(500)201 expect(await res.text()).toBe('Custom Error Message')202 })203204 test('GET /api/default-route', async () => {205 const res = await fetch('http://127.0.0.1:1234/api/default-route')206 expect(res.status).toBe(404)207 expect(await res.text()).toBe('API endpoint is not found')208 })209})
added:runtime_tests/lagon/index.ts+134 added
1import { Hono } from '../../src'2import { env } from '../../src/adapter'3import { HTTPException } from '../../src/http-exception'4import { basicAuth } from '../../src/middleware/basic-auth'5import { bearerAuth } from '../../src/middleware/bearer-auth'6import { etag } from '../../src/middleware/etag'7import { poweredBy } from '../../src/middleware/powered-by'8import { prettyJSON } from '../../src/middleware/pretty-json'910const app = new Hono()1112// Mount Builtin Middleware13app.use('*', poweredBy())14// app.use('*', logger())15app.use(16 '/basic-auth/*',17 basicAuth({18 username: 'hono',19 password: 'acoolproject',20 })21)22app.use(23 '/bearer-auth/*',24 bearerAuth({25 token: 'secrettoken',26 })27)28app.use('/etag/*', etag())2930app.get('/env', (c) => {31 const { NAME } = env<{ NAME: string }>(c)32 return c.text(NAME)33})3435// Custom Middleware36// Add Custom Header37app.use('/hello/*', async (c, next) => {38 await next()39 c.header('X-message', 'This is addHeader middleware!')40})4142// Add X-Response-Time header43app.use('*', async (c, next) => {44 const start = Date.now()45 await next()46 const ms = Date.now() - start47 c.header('X-Response-Time', `${ms}ms`)48})4950// Custom Not Found Message51app.notFound((c) => {52 return c.text('Custom 404 Not Found', 404)53})5455// Error handling56app.onError((err, c) => {57 if (err instanceof HTTPException) {58 return err.getResponse()59 }60 console.error(`${err}`)61 return c.text('Custom Error Message', 500)62})6364app.head('/', (c) => c.text('OK'))6566// Routing67app.get('/', (c) => c.text('Hono!!'))68// Use Response object directly69app.get('/hello', () => new Response('This is /hello'))7071app.get('/runtime', (c) => new Response(c.runtime))7273// Named parameter74app.get('/entry/:id', (c) => {75 const id = c.req.param('id')76 return c.text(`Your ID is ${id}`)77})7879// Nested route80const book = new Hono()81book.get('/', (c) => c.text('List Books'))82book.get('/:id', (c) => {83 const id = c.req.param('id')84 return c.text('Get Book: ' + id)85})86book.post('/', (c) => c.text('Create Book'))87app.route('/book', book)8889// Redirect90app.get('/redirect', (c) => c.redirect('/'))91// Authentication required92app.get('/basic-auth/*', (c) => c.text('You are authorized'))93app.get('/bearer-auth/*', (c) => c.text('You are authorized'))94// ETag95app.get('/etag/cached', (c) => c.text('Is this cached?'))9697// Async98app.get('/fetch-url', async (c) => {99 const response = await fetch('https://example.com/')100 return c.text(`https://example.com/ is ${response.status}`)101})102103// Request headers104app.get('/user-agent', (c) => {105 const userAgent = c.req.header('User-Agent')106 return c.text(`Your UserAgent is ${userAgent}`)107})108109// JSON110app.get('/api/posts', prettyJSON(), (c) => {111 const posts = [112 { id: 1, title: 'Good Morning' },113 { id: 2, title: 'Good Aternoon' },114 { id: 3, title: 'Good Evening' },115 { id: 4, title: 'Good Night' },116 ]117 return c.json(posts)118})119// status code120app.post('/api/posts', (c) => c.json({ message: 'Created!' }, 201))121// default route122app.get('/api/*', (c) => c.text('API endpoint is not found', 404))123124app.post('/form', async (c) => {125 const body = await c.req.parseBody()126 return c.json(body)127})128129// Throw Error130app.get('/error', () => {131 throw Error('Error has occurred')132})133134export const handler = app.fetch
added:runtime_tests/lambda/index.test.ts+118 added
1import { handle } from '../../src/adapter/aws-lambda/handler'2import { Hono } from '../../src/hono'3import { basicAuth } from '../../src/middleware/basic-auth'45describe('AWS Lambda Adapter for Hono', () => {6 const app = new Hono()78 app.get('/', (c) => {9 return c.text('Hello Lambda!')10 })1112 app.post('/post', async (c) => {13 const body = (await c.req.parseBody()) as { message: string }14 return c.text(body.message)15 })1617 const username = 'hono-user-a'18 const password = 'hono-password-a'19 app.use('/auth/*', basicAuth({ username, password }))20 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))2122 const handler = handle(app)2324 it('Should handle a GET request and return a 200 response', async () => {25 const event = {26 httpMethod: 'GET',27 headers: { 'content-type': 'text/plain' },28 path: '/',29 body: null,30 isBase64Encoded: false,31 requestContext: {32 domainName: 'example.com',33 },34 }3536 const response = await handler(event)37 expect(response.statusCode).toBe(200)38 expect(response.body).toBe('Hello Lambda!')39 expect(response.headers['content-type']).toMatch(/^text\/plain/)40 expect(response.isBase64Encoded).toBe(false)41 })4243 it('Should handle a GET request and return a 404 response', async () => {44 const event = {45 httpMethod: 'GET',46 headers: { 'content-type': 'text/plain' },47 path: '/nothing',48 body: null,49 isBase64Encoded: false,50 requestContext: {51 domainName: 'example.com',52 },53 }5455 const response = await handler(event)56 expect(response.statusCode).toBe(404)57 })5859 it('Should handle a POST request and return a 200 response', async () => {60 const searchParam = new URLSearchParams()61 searchParam.append('message', 'Good Morning Lambda!')62 const event = {63 httpMethod: 'POST',64 headers: {65 'Content-Type': 'application/x-www-form-urlencoded',66 },67 path: '/post',68 body: btoa(searchParam.toString()),69 isBase64Encoded: true,70 requestContext: {71 domainName: 'example.com',72 },73 }7475 const response = await handler(event)76 expect(response.statusCode).toBe(200)77 expect(response.body).toBe('Good Morning Lambda!')78 })7980 it('Should handle a request and return a 401 response with Basic auth', async () => {81 const event = {82 httpMethod: 'GET',83 headers: {84 'Content-Type': 'plain/text',85 },86 path: '/auth/abc',87 body: null,88 isBase64Encoded: true,89 requestContext: {90 domainName: 'example.com',91 },92 }9394 const response = await handler(event)95 expect(response.statusCode).toBe(401)96 })9798 it('Should handle a request and return a 200 response with Basic auth', async () => {99 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'100 const event = {101 httpMethod: 'GET',102 headers: {103 'Content-Type': 'plain/text',104 Authorization: `Basic ${credential}`,105 },106 path: '/auth/abc',107 body: null,108 isBase64Encoded: true,109 requestContext: {110 domainName: 'example.com',111 },112 }113114 const response = await handler(event)115 expect(response.statusCode).toBe(200)116 expect(response.body).toBe('Good Night Lambda!')117 })118})
added:runtime_tests/lambda/jest.config.js+7 added
added:runtime_tests/node/index.test.ts+97 added
1import { createAdaptorServer } from '@hono/node-server'2import request from 'supertest'3import { Hono } from '../../src'4import { env } from '../../src/adapter'5import { Context } from '../../src/context'6import { basicAuth } from '../../src/middleware/basic-auth'7import { jwt } from '../../src/middleware/jwt'89// Test only minimal patterns.10// See <https://github.com/honojs/node-server> for more tests and information.1112describe('Basic', () => {13 const app = new Hono()1415 app.get('/', (c) => {16 return c.text('Hello! Node.js!')17 })18 app.get('/runtime-name', (c) => {19 return c.text(c.runtime)20 })2122 const server = createAdaptorServer(app)2324 it('Should return 200 response', async () => {25 const res = await request(server).get('/')26 expect(res.status).toBe(200)27 expect(res.text).toBe('Hello! Node.js!')28 })2930 it('Should return correct runtime name', async () => {31 const res = await request(server).get('/runtime-name')32 expect(res.status).toBe(200)33 expect(res.text).toBe('node')34 })35})3637describe('Environment Variables', () => {38 it('Should return the environment variable', async () => {39 const c = new Context(new Request('http://localhost/'))40 const { NAME } = env<{ NAME: string }>(c)41 expect(NAME).toBe('Node')42 })43})4445describe('Basic Auth Middleware', () => {46 const app = new Hono()4748 const username = 'hono-user-a'49 const password = 'hono-password-a'50 app.use(51 '/auth/*',52 basicAuth({53 username,54 password,55 })56 )5758 app.get('/auth/*', () => new Response('auth'))5960 const server = createAdaptorServer(app)6162 it('Should not authorize, return 401 Response', async () => {63 const res = await request(server).get('/auth/a')64 expect(res.status).toBe(401)65 expect(res.text).toBe('Unauthorized')66 })6768 it('Should authorize, return 200 Response', async () => {69 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'70 const res = await request(server).get('/auth/a').set('Authorization', `Basic ${credential}`)71 expect(res.status).toBe(200)72 expect(res.text).toBe('auth')73 })74})7576describe('JWT Auth Middleware', () => {77 const app = new Hono()7879 app.use('/jwt/*', jwt({ secret: 'a-secret' }))80 app.get('/jwt/a', (c) => c.text('auth'))8182 const server = createAdaptorServer(app)8384 it('Should not authorize, return 401 Response', async () => {85 const res = await request(server).get('/jwt/a')86 expect(res.status).toBe(401)87 expect(res.text).toBe('Unauthorized')88 })8990 it('Should authorize, return 200 Response', async () => {91 const credential =92 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'93 const res = await request(server).get('/jwt/a').set('Authorization', `Bearer ${credential}`)94 expect(res.status).toBe(200)95 expect(res.text).toBe('auth')96 })97})
added:runtime_tests/node/jest.config.js+7 added
added:runtime_tests/wrangler/index.test.ts+31 added
1import { unstable_dev } from 'wrangler'2import type { UnstableDevWorker } from 'wrangler'34describe('Wrangler', () => {5 let worker: UnstableDevWorker67 beforeAll(async () => {8 worker = await unstable_dev('./runtime_tests/wrangler/index.ts', {9 vars: {10 NAME: 'Cloudflare',11 },12 experimental: { disableExperimentalWarning: true },13 })14 })1516 afterAll(async () => {17 await worker.stop()18 })1920 it('Should return Hello World', async () => {21 const res = await worker.fetch('/')22 expect(res.status).toBe(200)23 expect(await res.text()).toBe('Hello Wrangler!')24 })2526 it('Should return the environment variable', async () => {27 const res = await worker.fetch('/env')28 expect(res.status).toBe(200)29 expect(await res.text()).toBe('Cloudflare')30 })31})
added:runtime_tests/wrangler/index.ts+13 added
1import { env } from '../../src/adapter'2import { Hono } from '../../src/hono'34const app = new Hono()56app.get('/', (c) => c.text('Hello Wrangler!'))78app.get('/env', (c) => {9 const { NAME } = env<{ NAME: string }>(c)10 return c.text(NAME)11})1213export default app
added:runtime_tests/wrangler/jest.config.js+7 added
1export default {2 testMatch: ['**/runtime_tests/wrangler/**/(*.)+(test).+(ts|tsx)'],3 transform: {4 '^.+\\.(ts|tsx)$': 'ts-jest',5 },6 testPathIgnorePatterns: ['jest.config.js'],7}
deleted:test_bun/favicon.icobinary

A binary file, deleted.

deleted:test_bun/index.test.tsx-170 removed
1import { describe, expect, it } from 'bun:test'2import { env } from '../src/adapter'3import { serveStatic } from '../src/adapter/bun'4import { Context } from '../src/context'5import { Hono } from '../src/index'6import { basicAuth } from '../src/middleware/basic-auth'7import { jwt } from '../src/middleware/jwt'89// Test just only minimal patterns.10// Because others are tested well in Cloudflare Workers environment already.1112describe('Basic', () => {13 const app = new Hono()14 app.get('/a/:foo', (c) => {15 c.header('x-param', c.req.param('foo'))16 c.header('x-query', c.req.query('q'))17 return c.text('Hello Bun!')18 })1920 it('Should return 200 Response', async () => {21 const req = new Request('http://localhost/a/foo?q=bar')22 const res = await app.request(req)23 expect(res.status).toBe(200)24 expect(await res.text()).toBe('Hello Bun!')25 expect(res.headers.get('x-param')).toBe('foo')26 expect(res.headers.get('x-query')).toBe('bar')27 })2829 it('returns current runtime (bun)', async () => {30 const c = new Context(new Request('http://localhost/'))31 expect(c.runtime).toBe('bun')32 })33})3435describe('Environment Variables', () => {36 it('Should return the environment variable', async () => {37 const c = new Context(new Request('http://localhost/'))38 const { NAME } = env<{ NAME: string }>(c)39 expect(NAME).toBe('Bun')40 })41})4243describe('Basic Auth Middleware', () => {44 const app = new Hono()4546 const username = 'hono-user-a'47 const password = 'hono-password-a'48 app.use(49 '/auth/*',50 basicAuth({51 username,52 password,53 })54 )5556 app.get('/auth/*', () => new Response('auth'))5758 it('Should not authorize, return 401 Response', async () => {59 const req = new Request('http://localhost/auth/a')60 const res = await app.request(req)61 expect(res.status).toBe(401)62 expect(await res.text()).toBe('Unauthorized')63 })6465 it('Should authorize, return 200 Response', async () => {66 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'67 const req = new Request('http://localhost/auth/a')68 req.headers.set('Authorization', `Basic ${credential}`)69 const res = await app.request(req)70 expect(res.status).toBe(200)71 expect(await res.text()).toBe('auth')72 })73})7475describe('Serve Static Middleware', () => {76 const app = new Hono()77 app.all('/favicon.ico', serveStatic({ path: './test_bun/favicon.ico' }))78 app.all('/favicon-notfound.ico', serveStatic({ path: './test_bun/favicon-notfound.ico' }))79 app.use('/favicon-notfound.ico', async (c, next) => {80 await next()81 c.header('X-Custom', 'Bun')82 })8384 it('Should return static file correctly', async () => {85 const res = await app.request(new Request('http://localhost/favicon.ico'))86 await res.arrayBuffer()87 expect(res.status).toBe(200)88 expect(res.headers.get('Content-Type')).toBe('image/x-icon')89 })9091 it('Should return 404 response', async () => {92 const res = await app.request(new Request('http://localhost/favicon-notfound.ico'))93 expect(res.status).toBe(404)94 expect(res.headers.get('X-Custom')).toBe('Bun')95 })96})9798// Bun support WebCrypto since v0.2.299// So, JWT middleware works well.100describe('JWT Auth Middleware', () => {101 const app = new Hono()102 app.use('/jwt/*', jwt({ secret: 'a-secret' }))103 app.get('/jwt/a', (c) => c.text('auth'))104105 it('Should not authorize, return 401 Response', async () => {106 const req = new Request('http://localhost/jwt/a')107 const res = await app.request(req)108 expect(res.status).toBe(401)109 expect(await res.text()).toBe('Unauthorized')110 })111112 it('Should authorize, return 200 Response', async () => {113 const credential =114 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'115 const req = new Request('http://localhost/jwt/a')116 req.headers.set('Authorization', `Bearer ${credential}`)117 const res = await app.request(req)118 expect(res.status).toBe(200)119 expect(await res.text()).toBe('auth')120 })121})122123// To enable JSX middleware,124// set "jsxImportSource": "hono/jsx" in the tsconfig.json125describe('JSX Middleware', () => {126 const app = new Hono()127128 const Layout = (props: { children?: string }) => {129 return <html>{props.children}</html>130 }131132 app.get('/', (c) => {133 return c.html(<h1>Hello</h1>)134 })135 app.get('/nest', (c) => {136 return c.html(137 <h1>138 <a href='/top'>Hello</a>139 </h1>140 )141 })142 app.get('/layout', (c) => {143 return c.html(144 <Layout>145 <p>hello</p>146 </Layout>147 )148 })149150 it('Should return rendered HTML', async () => {151 const res = await app.request(new Request('http://localhost/'))152 expect(res.status).toBe(200)153 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')154 expect(await res.text()).toBe('<h1>Hello</h1>')155 })156157 it('Should return rendered HTML with nest', async () => {158 const res = await app.request(new Request('http://localhost/nest'))159 expect(res.status).toBe(200)160 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')161 expect(await res.text()).toBe('<h1><a href="/top">Hello</a></h1>')162 })163164 it('Should return rendered HTML with Layout', async () => {165 const res = await app.request(new Request('http://localhost/layout'))166 expect(res.status).toBe(200)167 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')168 expect(await res.text()).toBe('<html><p>hello</p></html>')169 })170})
deleted:test_deno/.vscode/settings.json-12 removed
1{2 "eslint.validate": [3 "javascript",4 "javascriptreact",5 "typescript",6 "typescriptreact"7 ],8 "editor.codeActionsOnSave": {9 "source.fixAll.eslint": true10 },11 "deno.enable": true12}
deleted:test_deno/deps.ts-1 removed
1export { assert, assertEquals, assertMatch } from 'https://deno.land/std@0.147.0/testing/asserts.ts'
deleted:test_deno/favicon.icobinary

A binary file, deleted.

deleted:test_deno/hono.test.ts-32 removed
1import { env } from '../deno_dist/adapter.ts'2import { Context } from '../deno_dist/context.ts'3import { Hono } from '../deno_dist/mod.ts'4import { assertEquals } from './deps.ts'56// Test just only minimal patterns.7// Because others are tested well in Cloudflare Workers environment already.89Deno.test('Hello World', async () => {10 const app = new Hono()11 app.get('/:foo', (c) => {12 c.header('x-param', c.req.param('foo'))13 c.header('x-query', c.req.query('q') || '')14 return c.text('Hello Deno!')15 })16 const res = await app.request('http://localhost/foo?q=bar')17 assertEquals(res.status, 200)18 assertEquals(await res.text(), 'Hello Deno!')19 assertEquals(res.headers.get('x-param'), 'foo')20 assertEquals(res.headers.get('x-query'), 'bar')21})2223Deno.test('runtime', async () => {24 const c = new Context(new Request('http://localhost/'))25 assertEquals(c.runtime, 'deno')26})2728Deno.test('environment variables', async () => {29 const c = new Context(new Request('http://localhost/'))30 const { NAME } = env<{ NAME: string }>(c)31 assertEquals(NAME, 'Deno')32})
deleted:test_deno/middleware.test.tsx-102 removed
1/** @jsx jsx */2/** @jsxFrag Fragment */3import { basicAuth, jsx, Fragment, serveStatic, jwt } from '../deno_dist/middleware.ts'4import { Hono } from '../deno_dist/mod.ts'5import { assertEquals, assertMatch } from './deps.ts'67// Test just only minimal patterns.8// Because others are already tested well in Cloudflare Workers environment.910Deno.test('Basic Auth Middleware', async () => {11 const app = new Hono()1213 const username = 'hono-user-a'14 const password = 'hono-password-a'1516 app.use(17 '/auth/*',18 basicAuth({19 username,20 password,21 })22 )2324 app.get('/auth/*', () => new Response('auth'))2526 const res = await app.request('http://localhost/auth/a')27 assertEquals(res.status, 401)28 assertEquals(await res.text(), 'Unauthorized')2930 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'3132 const req = new Request('http://localhost/auth/a')33 req.headers.set('Authorization', `Basic ${credential}`)34 const resOK = await app.request(req)35 assertEquals(resOK.status, 200)36 assertEquals(await resOK.text(), 'auth')37})3839Deno.test('JSX middleware', async () => {40 const app = new Hono()41 app.get('/', (c) => {42 return c.html(<h1>Hello</h1>)43 })44 const res = await app.request('http://localhost/')45 assertEquals(res.status, 200)46 assertEquals(res.headers.get('Content-Type'), 'text/html; charset=UTF-8')47 assertEquals(await res.text(), '<h1>Hello</h1>')4849 // Fragment50 const template = (51 <>52 <p>1</p>53 <p>2</p>54 </>55 )56 assertEquals(template.toString(), '<p>1</p><p>2</p>')57})5859Deno.test('Serve Static middleware', async () => {60 const app = new Hono()61 app.all('/favicon.ico', serveStatic({ path: './test_deno/favicon.ico' }))62 app.all('/favicon-notfound.ico', serveStatic({ path: './test_deno/favicon-notfound.ico' }))63 app.use('/favicon-notfound.ico', async (c, next) => {64 await next()65 c.header('X-Custom', 'Deno')66 })67 let res = await app.request('http://localhost/favicon.ico')68 assertEquals(res.status, 200)69 assertEquals(res.headers.get('Content-Type'), 'image/x-icon')70 res = await app.request('http://localhost/favicon-notfound.ico')71 assertEquals(res.status, 404)72 assertMatch(res.headers.get('Content-Type') || '', /^text\/plain/)73 assertEquals(res.headers.get('X-Custom'), 'Deno')74})7576Deno.test('JWT Authentication middleware', async () => {77 const app = new Hono<{ Variables: { 'x-foo': string } }>()78 app.use('/*', async (c, next) => {79 await next()80 c.header('x-foo', c.get('x-foo') || '')81 })82 app.use('/auth/*', jwt({ secret: 'a-secret' }))83 app.get('/auth/*', (c) => {84 c.set('x-foo', 'bar')85 return new Response('auth')86 })8788 const req = new Request('http://localhost/auth/a')89 const res = await app.request(req)90 assertEquals(res.status, 401)91 assertEquals(await res.text(), 'Unauthorized')92 assertEquals(res.headers.get('x-foo'), '')9394 const credential =95 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'96 const reqOK = new Request('http://localhost/auth/a')97 reqOK.headers.set('Authorization', `Bearer ${credential}`)98 const resOK = await app.request(reqOK)99 assertEquals(resOK.status, 200)100 assertEquals(await resOK.text(), 'auth')101 assertEquals(resOK.headers.get('x-foo'), 'bar')102})
deleted:test_fastly/index.test.ts-96 removed
1import { SHA256 } from 'crypto-js'2import { Hono } from '../src/index'3import { basicAuth } from '../src/middleware/basic-auth'4import { jwt } from '../src/middleware/jwt'56// eslint-disable-next-line @typescript-eslint/ban-ts-comment7// @ts-ignore8globalThis.fastly = true910const app = new Hono()1112describe('Hello World', () => {13 app.get('/', (c) => c.text('Hello! Compute!'))14 app.get('/runtime-name', (c) => {15 return c.text(c.runtime)16 })1718 it('Should return 200', async () => {19 const res = await app.request('http://localhost/')20 expect(res.status).toBe(200)21 expect(await res.text()).toBe('Hello! Compute!')22 })2324 it('Should return the correct runtime name', async () => {25 const res = await app.request('http://localhost/runtime-name')26 expect(res.status).toBe(200)27 expect(await res.text()).toBe('fastly')28 })29})3031describe('Basic Auth Middleware without `hashFunction`', () => {32 const app = new Hono()3334 const username = 'hono-user-a'35 const password = 'hono-password-a'36 app.use(37 '/auth/*',38 basicAuth({39 username,40 password,41 })42 )4344 app.get('/auth/*', () => new Response('auth'))4546 it('Should authorize, return 401 Response', async () => {47 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'48 const req = new Request('http://localhost/auth/a')49 req.headers.set('Authorization', `Basic ${credential}`)50 const res = await app.request(req)51 expect(res.status).toBe(401)52 })53})5455describe('Basic Auth Middleware with `hashFunction`', () => {56 const app = new Hono()5758 const username = 'hono-user-a'59 const password = 'hono-password-a'60 app.use(61 '/auth/*',62 basicAuth({63 username,64 password,65 hashFunction: (m: string) => SHA256(m).toString(),66 })67 )6869 app.get('/auth/*', () => new Response('auth'))7071 it('Should not authorize, return 401 Response', async () => {72 const req = new Request('http://localhost/auth/a')73 const res = await app.request(req)74 expect(res.status).toBe(401)75 expect(await res.text()).toBe('Unauthorized')76 })7778 it('Should authorize, return 200 Response', async () => {79 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'80 const req = new Request('http://localhost/auth/a')81 req.headers.set('Authorization', `Basic ${credential}`)82 const res = await app.request(req)83 expect(res.status).toBe(200)84 expect(await res.text()).toBe('auth')85 })86})8788describe('JWT Auth Middleware does not work', () => {89 const app = new Hono()9091 it('Should throw error', () => {92 expect(() => {93 app.use('/jwt/*', jwt({ secret: 'secret' }))94 }).toThrow(/`crypto.subtle.importKey` is undefined/)95 })96})
deleted:test_lagon/.env.lagon-1 removed
1NAME=Lagon
deleted:test_lagon/index.test.ts-209 removed
1describe('Example', () => {2 test('GET /', async () => {3 const res = await fetch('http://127.0.0.1:1234')4 expect(res.status).toBe(200)5 expect(await res.text()).toBe('Hono!!')6 expect(res.headers.get('x-powered-by')).toBe('Hono')7 expect(res.headers.get('x-response-time')).toContain('ms')8 })910 test('GET /hello/anything', async () => {11 const res = await fetch('http://127.0.0.1:1234/hello/anything')12 expect(res.status).toBe(404)13 expect(res.headers.get('x-message')).toBe('This is addHeader middleware!')14 })1516 test('GET /hello', async () => {17 const res = await fetch('http://127.0.0.1:1234/hello')18 expect(res.status).toBe(200)19 expect(await res.text()).toBe('This is /hello')20 })2122 test('GET /runtime', async () => {23 const res = await fetch('http://127.0.0.1:1234/runtime')24 expect(res.status).toBe(200)25 expect(await res.text()).toBe('lagon')26 })2728 /*29 TODO: It can't resolve the file path `.env` on CI30 test('GET /env', async () => {31 const res = await fetch('http://127.0.0.1:1234/env')32 expect(res.status).toBe(200)33 expect(await res.text()).toBe('Lagon')34 })35 */3637 test('GET /entry/:id', async () => {38 const res = await fetch('http://127.0.0.1:1234/entry/42')39 expect(res.status).toBe(200)40 expect(await res.text()).toBe('Your ID is 42')41 })4243 describe('/book', () => {44 test('GET /book', async () => {45 const res = await fetch('http://127.0.0.1:1234/book')46 expect(res.status).toBe(200)47 expect(await res.text()).toBe('List Books')48 })4950 test('GET /book/:id', async () => {51 const res = await fetch('http://127.0.0.1:1234/book/3')52 expect(res.status).toBe(200)53 expect(await res.text()).toBe('Get Book: 3')54 })5556 test('POST /book', async () => {57 const res = await fetch('http://127.0.0.1:1234/book', {58 method: 'POST',59 })60 expect(res.status).toBe(200)61 expect(await res.text()).toBe('Create Book')62 })63 })6465 test('GET /redirect', async () => {66 const res = await fetch('http://127.0.0.1:1234/redirect', {67 redirect: 'manual',68 })69 expect(res.status).toBe(302)70 expect(res.headers.get('location')).toBe('/')71 })7273 describe('/basic-auth', () => {74 test('GET /basic-auth/anyroute unauthorized', async () => {75 const res = await fetch('http://127.0.0.1:1234/basic-auth/anyroute')76 expect(res.status).toBe(401)77 expect(await res.text()).toBe('Unauthorized')78 })7980 test('GET /basic-auth/anyroute', async () => {81 const res = await fetch('http://127.0.0.1:1234/basic-auth/anyroute', {82 headers: {83 authorization: `Basic ${btoa('hono:acoolproject')}`,84 },85 })86 expect(res.status).toBe(200)87 expect(await res.text()).toBe('You are authorized')88 })89 })9091 describe('/bearer-auth', () => {92 test('GET /bearer-auth/anyroute unauthorized', async () => {93 const res = await fetch('http://127.0.0.1:1234/bearer-auth/anyroute')94 expect(res.status).toBe(401)95 expect(await res.text()).toBe('Unauthorized')96 })9798 test('GET /bearer-auth/anyroute', async () => {99 const res = await fetch('http://127.0.0.1:1234/bearer-auth/anyroute', {100 headers: {101 authorization: 'Bearer secrettoken',102 },103 })104 expect(res.status).toBe(200)105 expect(await res.text()).toBe('You are authorized')106 })107 })108109 test('GET /etag/cached', async () => {110 const res = await fetch('http://127.0.0.1:1234/etag/cached')111 expect(res.status).toBe(200)112 expect(res.headers.get('etag')).toBe('"90ea638841fff3c326fc22cbd156f1146ac0ac02"')113 expect(await res.text()).toBe('Is this cached?')114 })115116 test('GET /fetch-url', async () => {117 const res = await fetch('http://127.0.0.1:1234/fetch-url')118 expect(res.status).toBe(200)119 expect(await res.text()).toBe('https://example.com/ is 200')120 })121122 test('GET /user-agent', async () => {123 const res = await fetch('http://127.0.0.1:1234/user-agent', {124 headers: {125 'user-agent': 'Lagon',126 },127 })128 expect(res.status).toBe(200)129 expect(await res.text()).toBe('Your UserAgent is Lagon')130 })131132 test('GET /api/posts', async () => {133 const res = await fetch('http://127.0.0.1:1234/api/posts')134 expect(res.status).toBe(200)135 expect(await res.json()).toEqual([136 { id: 1, title: 'Good Morning' },137 { id: 2, title: 'Good Aternoon' },138 { id: 3, title: 'Good Evening' },139 { id: 4, title: 'Good Night' },140 ])141 })142143 test('POST /api/posts', async () => {144 const res = await fetch('http://127.0.0.1:1234/api/posts', {145 method: 'POST',146 })147 expect(res.status).toBe(201)148 expect(await res.json()).toEqual({ message: 'Created!' })149 })150151 test('GET /api/default-route', async () => {152 const res = await fetch('http://127.0.0.1:1234/api/default-route')153 expect(res.status).toBe(404)154 expect(await res.text()).toBe('API endpoint is not found')155 })156157 describe('/form', () => {158 test('POST /form x-www-form-urlencoded', async () => {159 const res = await fetch('http://127.0.0.1:1234/form', {160 method: 'POST',161 headers: {162 'content-type': 'application/x-www-form-urlencoded',163 },164 body: 'username=john&password=Pa%24%24w0rd',165 })166 expect(res.status).toBe(200)167 expect(await res.json()).toEqual({168 password: 'Pa$$w0rd',169 username: 'john',170 })171 })172173 test('POST /form', async () => {174 const res = await fetch('http://127.0.0.1:1234/form', {175 method: 'POST',176 headers: {177 'content-type':178 'multipart/form-data; boundary=---------------------------9051914041544843365972754266',179 },180 body: `-----------------------------9051914041544843365972754266181Content-Disposition: form-data; name="hello"182183world!184-----------------------------9051914041544843365972754266185Content-Disposition: form-data; name="description"186187this is another field188-----------------------------9051914041544843365972754266--`,189 })190 expect(res.status).toBe(200)191 expect(await res.json()).toEqual({192 description: 'this is another field',193 hello: 'world!',194 })195 })196 })197198 test('GET /error', async () => {199 const res = await fetch('http://127.0.0.1:1234/error')200 expect(res.status).toBe(500)201 expect(await res.text()).toBe('Custom Error Message')202 })203204 test('GET /api/default-route', async () => {205 const res = await fetch('http://127.0.0.1:1234/api/default-route')206 expect(res.status).toBe(404)207 expect(await res.text()).toBe('API endpoint is not found')208 })209})
deleted:test_lagon/index.ts-134 removed
1import { Hono } from '../src'2import { env } from '../src/adapter'3import { HTTPException } from '../src/http-exception'4import { basicAuth } from '../src/middleware/basic-auth'5import { bearerAuth } from '../src/middleware/bearer-auth'6import { etag } from '../src/middleware/etag'7import { poweredBy } from '../src/middleware/powered-by'8import { prettyJSON } from '../src/middleware/pretty-json'910const app = new Hono()1112// Mount Builtin Middleware13app.use('*', poweredBy())14// app.use('*', logger())15app.use(16 '/basic-auth/*',17 basicAuth({18 username: 'hono',19 password: 'acoolproject',20 })21)22app.use(23 '/bearer-auth/*',24 bearerAuth({25 token: 'secrettoken',26 })27)28app.use('/etag/*', etag())2930app.get('/env', (c) => {31 const { NAME } = env<{ NAME: string }>(c)32 return c.text(NAME)33})3435// Custom Middleware36// Add Custom Header37app.use('/hello/*', async (c, next) => {38 await next()39 c.header('X-message', 'This is addHeader middleware!')40})4142// Add X-Response-Time header43app.use('*', async (c, next) => {44 const start = Date.now()45 await next()46 const ms = Date.now() - start47 c.header('X-Response-Time', `${ms}ms`)48})4950// Custom Not Found Message51app.notFound((c) => {52 return c.text('Custom 404 Not Found', 404)53})5455// Error handling56app.onError((err, c) => {57 if (err instanceof HTTPException) {58 return err.getResponse()59 }60 console.error(`${err}`)61 return c.text('Custom Error Message', 500)62})6364app.head('/', (c) => c.text('OK'))6566// Routing67app.get('/', (c) => c.text('Hono!!'))68// Use Response object directly69app.get('/hello', () => new Response('This is /hello'))7071app.get('/runtime', (c) => new Response(c.runtime))7273// Named parameter74app.get('/entry/:id', (c) => {75 const id = c.req.param('id')76 return c.text(`Your ID is ${id}`)77})7879// Nested route80const book = new Hono()81book.get('/', (c) => c.text('List Books'))82book.get('/:id', (c) => {83 const id = c.req.param('id')84 return c.text('Get Book: ' + id)85})86book.post('/', (c) => c.text('Create Book'))87app.route('/book', book)8889// Redirect90app.get('/redirect', (c) => c.redirect('/'))91// Authentication required92app.get('/basic-auth/*', (c) => c.text('You are authorized'))93app.get('/bearer-auth/*', (c) => c.text('You are authorized'))94// ETag95app.get('/etag/cached', (c) => c.text('Is this cached?'))9697// Async98app.get('/fetch-url', async (c) => {99 const response = await fetch('https://example.com/')100 return c.text(`https://example.com/ is ${response.status}`)101})102103// Request headers104app.get('/user-agent', (c) => {105 const userAgent = c.req.header('User-Agent')106 return c.text(`Your UserAgent is ${userAgent}`)107})108109// JSON110app.get('/api/posts', prettyJSON(), (c) => {111 const posts = [112 { id: 1, title: 'Good Morning' },113 { id: 2, title: 'Good Aternoon' },114 { id: 3, title: 'Good Evening' },115 { id: 4, title: 'Good Night' },116 ]117 return c.json(posts)118})119// status code120app.post('/api/posts', (c) => c.json({ message: 'Created!' }, 201))121// default route122app.get('/api/*', (c) => c.text('API endpoint is not found', 404))123124app.post('/form', async (c) => {125 const body = await c.req.parseBody()126 return c.json(body)127})128129// Throw Error130app.get('/error', () => {131 throw Error('Error has occurred')132})133134export const handler = app.fetch
deleted:test_lambda/index.test.ts-118 removed
1import { handle } from '../src/adapter/aws-lambda/handler'2import { Hono } from '../src/hono'3import { basicAuth } from '../src/middleware/basic-auth'45describe('AWS Lambda Adapter for Hono', () => {6 const app = new Hono()78 app.get('/', (c) => {9 return c.text('Hello Lambda!')10 })1112 app.post('/post', async (c) => {13 const body = (await c.req.parseBody()) as { message: string }14 return c.text(body.message)15 })1617 const username = 'hono-user-a'18 const password = 'hono-password-a'19 app.use('/auth/*', basicAuth({ username, password }))20 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))2122 const handler = handle(app)2324 it('Should handle a GET request and return a 200 response', async () => {25 const event = {26 httpMethod: 'GET',27 headers: { 'content-type': 'text/plain' },28 path: '/',29 body: null,30 isBase64Encoded: false,31 requestContext: {32 domainName: 'example.com',33 },34 }3536 const response = await handler(event)37 expect(response.statusCode).toBe(200)38 expect(response.body).toBe('Hello Lambda!')39 expect(response.headers['content-type']).toMatch(/^text\/plain/)40 expect(response.isBase64Encoded).toBe(false)41 })4243 it('Should handle a GET request and return a 404 response', async () => {44 const event = {45 httpMethod: 'GET',46 headers: { 'content-type': 'text/plain' },47 path: '/nothing',48 body: null,49 isBase64Encoded: false,50 requestContext: {51 domainName: 'example.com',52 },53 }5455 const response = await handler(event)56 expect(response.statusCode).toBe(404)57 })5859 it('Should handle a POST request and return a 200 response', async () => {60 const searchParam = new URLSearchParams()61 searchParam.append('message', 'Good Morning Lambda!')62 const event = {63 httpMethod: 'POST',64 headers: {65 'Content-Type': 'application/x-www-form-urlencoded',66 },67 path: '/post',68 body: btoa(searchParam.toString()),69 isBase64Encoded: true,70 requestContext: {71 domainName: 'example.com',72 },73 }7475 const response = await handler(event)76 expect(response.statusCode).toBe(200)77 expect(response.body).toBe('Good Morning Lambda!')78 })7980 it('Should handle a request and return a 401 response with Basic auth', async () => {81 const event = {82 httpMethod: 'GET',83 headers: {84 'Content-Type': 'plain/text',85 },86 path: '/auth/abc',87 body: null,88 isBase64Encoded: true,89 requestContext: {90 domainName: 'example.com',91 },92 }9394 const response = await handler(event)95 expect(response.statusCode).toBe(401)96 })9798 it('Should handle a request and return a 200 response with Basic auth', async () => {99 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'100 const event = {101 httpMethod: 'GET',102 headers: {103 'Content-Type': 'plain/text',104 Authorization: `Basic ${credential}`,105 },106 path: '/auth/abc',107 body: null,108 isBase64Encoded: true,109 requestContext: {110 domainName: 'example.com',111 },112 }113114 const response = await handler(event)115 expect(response.statusCode).toBe(200)116 expect(response.body).toBe('Good Night Lambda!')117 })118})
deleted:test_node/index.test.ts-97 removed
1import { createAdaptorServer } from '@hono/node-server'2import request from 'supertest'3import { Hono } from '../src'4import { env } from '../src/adapter'5import { Context } from '../src/context'6import { basicAuth } from '../src/middleware/basic-auth'7import { jwt } from '../src/middleware/jwt'89// Test only minimal patterns.10// See <https://github.com/honojs/node-server> for more tests and information.1112describe('Basic', () => {13 const app = new Hono()1415 app.get('/', (c) => {16 return c.text('Hello! Node.js!')17 })18 app.get('/runtime-name', (c) => {19 return c.text(c.runtime)20 })2122 const server = createAdaptorServer(app)2324 it('Should return 200 response', async () => {25 const res = await request(server).get('/')26 expect(res.status).toBe(200)27 expect(res.text).toBe('Hello! Node.js!')28 })2930 it('Should return correct runtime name', async () => {31 const res = await request(server).get('/runtime-name')32 expect(res.status).toBe(200)33 expect(res.text).toBe('node')34 })35})3637describe('Environment Variables', () => {38 it('Should return the environment variable', async () => {39 const c = new Context(new Request('http://localhost/'))40 const { NAME } = env<{ NAME: string }>(c)41 expect(NAME).toBe('Node')42 })43})4445describe('Basic Auth Middleware', () => {46 const app = new Hono()4748 const username = 'hono-user-a'49 const password = 'hono-password-a'50 app.use(51 '/auth/*',52 basicAuth({53 username,54 password,55 })56 )5758 app.get('/auth/*', () => new Response('auth'))5960 const server = createAdaptorServer(app)6162 it('Should not authorize, return 401 Response', async () => {63 const res = await request(server).get('/auth/a')64 expect(res.status).toBe(401)65 expect(res.text).toBe('Unauthorized')66 })6768 it('Should authorize, return 200 Response', async () => {69 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'70 const res = await request(server).get('/auth/a').set('Authorization', `Basic ${credential}`)71 expect(res.status).toBe(200)72 expect(res.text).toBe('auth')73 })74})7576describe('JWT Auth Middleware', () => {77 const app = new Hono()7879 app.use('/jwt/*', jwt({ secret: 'a-secret' }))80 app.get('/jwt/a', (c) => c.text('auth'))8182 const server = createAdaptorServer(app)8384 it('Should not authorize, return 401 Response', async () => {85 const res = await request(server).get('/jwt/a')86 expect(res.status).toBe(401)87 expect(res.text).toBe('Unauthorized')88 })8990 it('Should authorize, return 200 Response', async () => {91 const credential =92 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'93 const res = await request(server).get('/jwt/a').set('Authorization', `Bearer ${credential}`)94 expect(res.status).toBe(200)95 expect(res.text).toBe('auth')96 })97})
deleted:test_wrangler/index.test.ts-31 removed
1import { unstable_dev } from 'wrangler'2import type { UnstableDevWorker } from 'wrangler'34describe('Wrangler', () => {5 let worker: UnstableDevWorker67 beforeAll(async () => {8 worker = await unstable_dev('./test_wrangler/index.ts', {9 vars: {10 NAME: 'Cloudflare',11 },12 experimental: { disableExperimentalWarning: true },13 })14 })1516 afterAll(async () => {17 await worker.stop()18 })1920 it('Should return Hello World', async () => {21 const res = await worker.fetch('/')22 expect(res.status).toBe(200)23 expect(await res.text()).toBe('Hello Wrangler!')24 })2526 it('Should return the environment variable', async () => {27 const res = await worker.fetch('/env')28 expect(res.status).toBe(200)29 expect(await res.text()).toBe('Cloudflare')30 })31})
deleted:test_wrangler/index.ts-13 removed
1import { env } from '../src/adapter'2import { Hono } from '../src/hono'34const app = new Hono()56app.get('/', (c) => c.text('Hello Wrangler!'))78app.get('/env', (c) => {9 const { NAME } = env<{ NAME: string }>(c)10 return c.text(NAME)11})1213export default app
deleted:jest.fastly.config.js-7 removed
1export default {2 testMatch: ['**/test_fastly/**/*.+(ts|tsx|js)'],3 transform: {4 '^.+\\.(ts|tsx)$': 'ts-jest',5 },6 preset: 'jest-preset-fastly-js-compute/typescript/esm',7}
deleted:jest.lambda.config.js-6 removed
1export default {2 testMatch: ['**/test_lambda/**/*.+(ts|tsx|js)'],3 transform: {4 '^.+\\.(ts|tsx)$': 'ts-jest',5 },6}
deleted:jest.node.config.js-6 removed
1export default {2 testMatch: ['**/test_node/**/*.+(ts|tsx|js)'],3 transform: {4 '^.+\\.(ts|tsx)$': 'ts-jest',5 },6}
deleted:jest.wrangler.config.js-6 removed
1export default {2 testMatch: ['**/test_wrangler/**/(*.)+(test).+(ts|tsx)'],3 transform: {4 '^.+\\.(ts|tsx)$': 'ts-jest',5 },6}
modified:package.json+7 added-7 removed
9 unmodified lines
10 "dist"11 ],12 "scripts": {13 "test": "jest",14 "test:deno": "env NAME=Deno deno test --allow-read --allow-env test_deno",15 "test:bun": "env NAME=Bun bun test --jsx-import-source ../src/middleware/jsx/jsx-dev-runtime test_bun/index.test.tsx",16 "test:fastly": "jest --config ./jest.fastly.config.js",17 "test:lagon": "start-server-and-test \"lagon dev test_lagon/index.ts\" http://127.0.0.1:1234 \"yarn jest test_lagon/index.test.ts --testMatch '**/*.test.ts'\"",18 "test:node": "env NAME=Node jest --config ./jest.node.config.js",19 "test:wrangler": "jest --config ./jest.wrangler.config.js",20 "test:lambda": "env NAME=Node jest --config ./jest.lambda.config.js",14 "test:deno": "env NAME=Deno deno test --allow-read --allow-env runtime_tests/deno",15 "test:bun": "env NAME=Bun bun test --jsx-import-source ../../src/middleware/jsx/jsx-dev-runtime runtime_tests/bun/index.test.tsx",16 "test:fastly": "jest --config ./runtime_tests/fastly/jest.config.js",17 "test:lagon": "start-server-and-test \"lagon dev runtime_tests/lagon/index.ts\" http://127.0.0.1:1234 \"yarn jest runtime_tests/lagon/index.test.ts --testMatch '**/*.test.ts'\"",18 "test:node": "env NAME=Node jest --config ./runtime_tests/node/jest.config.js",19 "test:wrangler": "jest --config ./runtime_tests/wrangler/jest.config.js",20 "test:lambda": "env NAME=Node jest --config ./runtime_tests/lambda/jest.config.js",21 "test:all": "yarn test && yarn test:deno && yarn test:bun && yarn test:fastly && yarn test:lagon && yarn test:node && yarn test:wrangler && yarn test:lambda",22 "lint": "eslint --ext js,ts src .eslintrc.cjs",23 "lint:fix": "eslint --ext js,ts src .eslintrc.cjs --fix",24 "denoify": "rimraf deno_dist && denoify && rimraf 'deno_dist/**/*.test.ts'",
320 unmodified lines