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
Provenance
- Commit
f29761e- Tree
44da6ba- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
db7ad68
40 files changed+1056 added−1049 removed
modified:.github/workflows/ci.yml+1 added-1 removed
25 unmodified lines2627282930303132333469 unmodified lines25 unmodified lines - uses: actions/checkout@v2 - uses: denoland/setup-deno@v1 with: deno-version: v1.x - run: env NAME=Deno deno test --allow-read --allow-env test_deno - run: env NAME=Deno deno test --allow-read --allow-env runtime_tests/deno
bun: name: 'Bun' runs-on: ubuntu-latest69 unmodified linesadded:runtime_tests/bun/favicon.icobinary
A binary file, added.
added:runtime_tests/bun/index.test.tsx+170 added
1+import { describe, expect, it } from 'bun:test'2+import { env } from '../../src/adapter'3+import { serveStatic } from '../../src/adapter/bun'4+import { Context } from '../../src/context'5+import { Hono } from '../../src/index'6+import { basicAuth } from '../../src/middleware/basic-auth'7+import { jwt } from '../../src/middleware/jwt'8+9+// Test just only minimal patterns.10+// Because others are tested well in Cloudflare Workers environment already.11+12+describe('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+ })19+20+ 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+ })28+29+ it('returns current runtime (bun)', async () => {30+ const c = new Context(new Request('http://localhost/'))31+ expect(c.runtime).toBe('bun')32+ })33+})34+35+describe('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+})42+43+describe('Basic Auth Middleware', () => {44+ const app = new Hono()45+46+ const username = 'hono-user-a'47+ const password = 'hono-password-a'48+ app.use(49+ '/auth/*',50+ basicAuth({51+ username,52+ password,53+ })54+ )55+56+ app.get('/auth/*', () => new Response('auth'))57+58+ 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+ })64+65+ 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+})74+75+describe('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+ })83+84+ 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+ })90+91+ 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+})97+98+// Bun support WebCrypto since v0.2.299+// So, JWT middleware works well.100+describe('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'))104+105+ 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+ })111+112+ 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+})122+123+// To enable JSX middleware,124+// set "jsxImportSource": "hono/jsx" in the tsconfig.json125+describe('JSX Middleware', () => {126+ const app = new Hono()127+128+ const Layout = (props: { children?: string }) => {129+ return <html>{props.children}</html>130+ }131+132+ 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+ })149+150+ 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+ })156+157+ 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+ })163+164+ 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
123456789101112{ "eslint.validate": [ "javascript", "javascriptreact", "typescript", "typescriptreact" ], "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, "deno.enable": true}No newline at end of fileadded:runtime_tests/deno/deps.ts+1 added
1export { assert, assertEquals, assertMatch } from 'https://deno.land/std@0.147.0/testing/asserts.ts'added:runtime_tests/deno/favicon.icobinary
A binary file, added.
added:runtime_tests/deno/hono.test.ts+32 added
1234567891011121314151617181920212223242526272829303132import { env } from '../../deno_dist/adapter.ts'import { Context } from '../../deno_dist/context.ts'import { Hono } from '../../deno_dist/mod.ts'import { assertEquals } from './deps.ts'
// Test just only minimal patterns.// Because others are tested well in Cloudflare Workers environment already.
Deno.test('Hello World', async () => { const app = new Hono() app.get('/:foo', (c) => { c.header('x-param', c.req.param('foo')) c.header('x-query', c.req.query('q') || '') return c.text('Hello Deno!') }) const res = await app.request('http://localhost/foo?q=bar') assertEquals(res.status, 200) assertEquals(await res.text(), 'Hello Deno!') assertEquals(res.headers.get('x-param'), 'foo') assertEquals(res.headers.get('x-query'), 'bar')})
Deno.test('runtime', async () => { const c = new Context(new Request('http://localhost/')) assertEquals(c.runtime, 'deno')})
Deno.test('environment variables', async () => { const c = new Context(new Request('http://localhost/')) const { NAME } = env<{ NAME: string }>(c) assertEquals(NAME, 'Deno')})added:runtime_tests/deno/middleware.test.tsx+105 added
1+/** @jsx jsx */2+/** @jsxFrag Fragment */3+import { basicAuth, jsx, Fragment, serveStatic, jwt } from '../../deno_dist/middleware.ts'4+import { Hono } from '../../deno_dist/mod.ts'5+import { assertEquals, assertMatch } from './deps.ts'6+7+// Test just only minimal patterns.8+// Because others are already tested well in Cloudflare Workers environment.9+10+Deno.test('Basic Auth Middleware', async () => {11+ const app = new Hono()12+13+ const username = 'hono-user-a'14+ const password = 'hono-password-a'15+16+ app.use(17+ '/auth/*',18+ basicAuth({19+ username,20+ password,21+ })22+ )23+24+ app.get('/auth/*', () => new Response('auth'))25+26+ const res = await app.request('http://localhost/auth/a')27+ assertEquals(res.status, 401)28+ assertEquals(await res.text(), 'Unauthorized')29+30+ const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'31+32+ 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+})38+39+Deno.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>')48+49+ // 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+})58+59+Deno.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+})78+79+Deno.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+ })90+91+ 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'), '')96+97+ 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
1+import { SHA256 } from 'crypto-js'2+import { Hono } from '../../src/index'3+import { basicAuth } from '../../src/middleware/basic-auth'4+import { jwt } from '../../src/middleware/jwt'5+6+// eslint-disable-next-line @typescript-eslint/ban-ts-comment7+// @ts-ignore8+globalThis.fastly = true9+10+const app = new Hono()11+12+describe('Hello World', () => {13+ app.get('/', (c) => c.text('Hello! Compute!'))14+ app.get('/runtime-name', (c) => {15+ return c.text(c.runtime)16+ })17+18+ 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+ })23+24+ 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+})30+31+describe('Basic Auth Middleware without `hashFunction`', () => {32+ const app = new Hono()33+34+ const username = 'hono-user-a'35+ const password = 'hono-password-a'36+ app.use(37+ '/auth/*',38+ basicAuth({39+ username,40+ password,41+ })42+ )43+44+ app.get('/auth/*', () => new Response('auth'))45+46+ 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+})54+55+describe('Basic Auth Middleware with `hashFunction`', () => {56+ const app = new Hono()57+58+ 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+ )68+69+ app.get('/auth/*', () => new Response('auth'))70+71+ 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+ })77+78+ 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+})87+88+describe('JWT Auth Middleware does not work', () => {89+ const app = new Hono()90+91+ 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
12345678export default { testMatch: ['**/runtime_tests/fastly/**/*.+(ts|tsx|js)'], transform: { '^.+\\.(ts|tsx)$': 'ts-jest', }, preset: 'jest-preset-fastly-js-compute/typescript/esm', testPathIgnorePatterns: ['jest.config.js'],}added:runtime_tests/lagon/.env.lagon+1 added
1+NAME=Lagonadded:runtime_tests/lagon/index.test.ts+209 added
1+describe('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+ })9+10+ 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+ })15+16+ 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+ })21+22+ 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+ })27+28+ /*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+ */36+37+ 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+ })42+43+ 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+ })49+50+ 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+ })55+56+ 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+ })64+65+ 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+ })72+73+ 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+ })79+80+ 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+ })90+91+ 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+ })97+98+ 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+ })108+109+ 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+ })115+116+ 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+ })121+122+ 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+ })131+132+ 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+ })142+143+ 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+ })150+151+ 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+ })156+157+ 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+ })172+173+ 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: `-----------------------------9051914041544843365972754266181+Content-Disposition: form-data; name="hello"182+183+world!184+-----------------------------9051914041544843365972754266185+Content-Disposition: form-data; name="description"186+187+this 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+ })197+198+ 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+ })203+204+ 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
1+import { Hono } from '../../src'2+import { env } from '../../src/adapter'3+import { HTTPException } from '../../src/http-exception'4+import { basicAuth } from '../../src/middleware/basic-auth'5+import { bearerAuth } from '../../src/middleware/bearer-auth'6+import { etag } from '../../src/middleware/etag'7+import { poweredBy } from '../../src/middleware/powered-by'8+import { prettyJSON } from '../../src/middleware/pretty-json'9+10+const app = new Hono()11+12+// Mount Builtin Middleware13+app.use('*', poweredBy())14+// app.use('*', logger())15+app.use(16+ '/basic-auth/*',17+ basicAuth({18+ username: 'hono',19+ password: 'acoolproject',20+ })21+)22+app.use(23+ '/bearer-auth/*',24+ bearerAuth({25+ token: 'secrettoken',26+ })27+)28+app.use('/etag/*', etag())29+30+app.get('/env', (c) => {31+ const { NAME } = env<{ NAME: string }>(c)32+ return c.text(NAME)33+})34+35+// Custom Middleware36+// Add Custom Header37+app.use('/hello/*', async (c, next) => {38+ await next()39+ c.header('X-message', 'This is addHeader middleware!')40+})41+42+// Add X-Response-Time header43+app.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+})49+50+// Custom Not Found Message51+app.notFound((c) => {52+ return c.text('Custom 404 Not Found', 404)53+})54+55+// Error handling56+app.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+})63+64+app.head('/', (c) => c.text('OK'))65+66+// Routing67+app.get('/', (c) => c.text('Hono!!'))68+// Use Response object directly69+app.get('/hello', () => new Response('This is /hello'))70+71+app.get('/runtime', (c) => new Response(c.runtime))72+73+// Named parameter74+app.get('/entry/:id', (c) => {75+ const id = c.req.param('id')76+ return c.text(`Your ID is ${id}`)77+})78+79+// Nested route80+const book = new Hono()81+book.get('/', (c) => c.text('List Books'))82+book.get('/:id', (c) => {83+ const id = c.req.param('id')84+ return c.text('Get Book: ' + id)85+})86+book.post('/', (c) => c.text('Create Book'))87+app.route('/book', book)88+89+// Redirect90+app.get('/redirect', (c) => c.redirect('/'))91+// Authentication required92+app.get('/basic-auth/*', (c) => c.text('You are authorized'))93+app.get('/bearer-auth/*', (c) => c.text('You are authorized'))94+// ETag95+app.get('/etag/cached', (c) => c.text('Is this cached?'))96+97+// Async98+app.get('/fetch-url', async (c) => {99+ const response = await fetch('https://example.com/')100+ return c.text(`https://example.com/ is ${response.status}`)101+})102+103+// Request headers104+app.get('/user-agent', (c) => {105+ const userAgent = c.req.header('User-Agent')106+ return c.text(`Your UserAgent is ${userAgent}`)107+})108+109+// JSON110+app.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 code120+app.post('/api/posts', (c) => c.json({ message: 'Created!' }, 201))121+// default route122+app.get('/api/*', (c) => c.text('API endpoint is not found', 404))123+124+app.post('/form', async (c) => {125+ const body = await c.req.parseBody()126+ return c.json(body)127+})128+129+// Throw Error130+app.get('/error', () => {131+ throw Error('Error has occurred')132+})133+134+export const handler = app.fetchadded:runtime_tests/lambda/index.test.ts+118 added
1+import { handle } from '../../src/adapter/aws-lambda/handler'2+import { Hono } from '../../src/hono'3+import { basicAuth } from '../../src/middleware/basic-auth'4+5+describe('AWS Lambda Adapter for Hono', () => {6+ const app = new Hono()7+8+ app.get('/', (c) => {9+ return c.text('Hello Lambda!')10+ })11+12+ app.post('/post', async (c) => {13+ const body = (await c.req.parseBody()) as { message: string }14+ return c.text(body.message)15+ })16+17+ 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!'))21+22+ const handler = handle(app)23+24+ 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+ }35+36+ 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+ })42+43+ 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+ }54+55+ const response = await handler(event)56+ expect(response.statusCode).toBe(404)57+ })58+59+ 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+ }74+75+ const response = await handler(event)76+ expect(response.statusCode).toBe(200)77+ expect(response.body).toBe('Good Morning Lambda!')78+ })79+80+ 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+ }93+94+ const response = await handler(event)95+ expect(response.statusCode).toBe(401)96+ })97+98+ 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+ }113+114+ 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
1234567export default { testMatch: ['**/runtime_tests/lambda/**/*.+(ts|tsx|js)'], transform: { '^.+\\.(ts|tsx)$': 'ts-jest', }, testPathIgnorePatterns: ['jest.config.js'],}added:runtime_tests/node/index.test.ts+97 added
1+import { createAdaptorServer } from '@hono/node-server'2+import request from 'supertest'3+import { Hono } from '../../src'4+import { env } from '../../src/adapter'5+import { Context } from '../../src/context'6+import { basicAuth } from '../../src/middleware/basic-auth'7+import { jwt } from '../../src/middleware/jwt'8+9+// Test only minimal patterns.10+// See <https://github.com/honojs/node-server> for more tests and information.11+12+describe('Basic', () => {13+ const app = new Hono()14+15+ app.get('/', (c) => {16+ return c.text('Hello! Node.js!')17+ })18+ app.get('/runtime-name', (c) => {19+ return c.text(c.runtime)20+ })21+22+ const server = createAdaptorServer(app)23+24+ 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+ })29+30+ 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+})36+37+describe('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+})44+45+describe('Basic Auth Middleware', () => {46+ const app = new Hono()47+48+ const username = 'hono-user-a'49+ const password = 'hono-password-a'50+ app.use(51+ '/auth/*',52+ basicAuth({53+ username,54+ password,55+ })56+ )57+58+ app.get('/auth/*', () => new Response('auth'))59+60+ const server = createAdaptorServer(app)61+62+ 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+ })67+68+ 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+})75+76+describe('JWT Auth Middleware', () => {77+ const app = new Hono()78+79+ app.use('/jwt/*', jwt({ secret: 'a-secret' }))80+ app.get('/jwt/a', (c) => c.text('auth'))81+82+ const server = createAdaptorServer(app)83+84+ 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+ })89+90+ 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
1234567export default { testMatch: ['**/runtime_tests/node/**/*.+(ts|tsx|js)'], transform: { '^.+\\.(ts|tsx)$': 'ts-jest', }, testPathIgnorePatterns: ['jest.config.js'],}added:runtime_tests/wrangler/index.test.ts+31 added
1+import { unstable_dev } from 'wrangler'2+import type { UnstableDevWorker } from 'wrangler'3+4+describe('Wrangler', () => {5+ let worker: UnstableDevWorker6+7+ beforeAll(async () => {8+ worker = await unstable_dev('./runtime_tests/wrangler/index.ts', {9+ vars: {10+ NAME: 'Cloudflare',11+ },12+ experimental: { disableExperimentalWarning: true },13+ })14+ })15+16+ afterAll(async () => {17+ await worker.stop()18+ })19+20+ 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+ })25+26+ 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
1+import { env } from '../../src/adapter'2+import { Hono } from '../../src/hono'3+4+const app = new Hono()5+6+app.get('/', (c) => c.text('Hello Wrangler!'))7+8+app.get('/env', (c) => {9+ const { NAME } = env<{ NAME: string }>(c)10+ return c.text(NAME)11+})12+13+export default appadded:runtime_tests/wrangler/jest.config.js+7 added
1+export 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
1-import { describe, expect, it } from 'bun:test'2-import { env } from '../src/adapter'3-import { serveStatic } from '../src/adapter/bun'4-import { Context } from '../src/context'5-import { Hono } from '../src/index'6-import { basicAuth } from '../src/middleware/basic-auth'7-import { jwt } from '../src/middleware/jwt'8-9-// Test just only minimal patterns.10-// Because others are tested well in Cloudflare Workers environment already.11-12-describe('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- })19-20- 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- })28-29- it('returns current runtime (bun)', async () => {30- const c = new Context(new Request('http://localhost/'))31- expect(c.runtime).toBe('bun')32- })33-})34-35-describe('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-})42-43-describe('Basic Auth Middleware', () => {44- const app = new Hono()45-46- const username = 'hono-user-a'47- const password = 'hono-password-a'48- app.use(49- '/auth/*',50- basicAuth({51- username,52- password,53- })54- )55-56- app.get('/auth/*', () => new Response('auth'))57-58- 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- })64-65- 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-})74-75-describe('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- })83-84- 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- })90-91- 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-})97-98-// Bun support WebCrypto since v0.2.299-// So, JWT middleware works well.100-describe('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'))104-105- 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- })111-112- 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-})122-123-// To enable JSX middleware,124-// set "jsxImportSource": "hono/jsx" in the tsconfig.json125-describe('JSX Middleware', () => {126- const app = new Hono()127-128- const Layout = (props: { children?: string }) => {129- return <html>{props.children}</html>130- }131-132- 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- })149-150- 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- })156-157- 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- })163-164- 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
1-export { 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
1-import { env } from '../deno_dist/adapter.ts'2-import { Context } from '../deno_dist/context.ts'3-import { Hono } from '../deno_dist/mod.ts'4-import { assertEquals } from './deps.ts'5-6-// Test just only minimal patterns.7-// Because others are tested well in Cloudflare Workers environment already.8-9-Deno.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-})22-23-Deno.test('runtime', async () => {24- const c = new Context(new Request('http://localhost/'))25- assertEquals(c.runtime, 'deno')26-})27-28-Deno.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 */3-import { basicAuth, jsx, Fragment, serveStatic, jwt } from '../deno_dist/middleware.ts'4-import { Hono } from '../deno_dist/mod.ts'5-import { assertEquals, assertMatch } from './deps.ts'6-7-// Test just only minimal patterns.8-// Because others are already tested well in Cloudflare Workers environment.9-10-Deno.test('Basic Auth Middleware', async () => {11- const app = new Hono()12-13- const username = 'hono-user-a'14- const password = 'hono-password-a'15-16- app.use(17- '/auth/*',18- basicAuth({19- username,20- password,21- })22- )23-24- app.get('/auth/*', () => new Response('auth'))25-26- const res = await app.request('http://localhost/auth/a')27- assertEquals(res.status, 401)28- assertEquals(await res.text(), 'Unauthorized')29-30- const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'31-32- 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-})38-39-Deno.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>')48-49- // 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-})58-59-Deno.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-})75-76-Deno.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- })87-88- 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'), '')93-94- 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
1-import { SHA256 } from 'crypto-js'2-import { Hono } from '../src/index'3-import { basicAuth } from '../src/middleware/basic-auth'4-import { jwt } from '../src/middleware/jwt'5-6-// eslint-disable-next-line @typescript-eslint/ban-ts-comment7-// @ts-ignore8-globalThis.fastly = true9-10-const app = new Hono()11-12-describe('Hello World', () => {13- app.get('/', (c) => c.text('Hello! Compute!'))14- app.get('/runtime-name', (c) => {15- return c.text(c.runtime)16- })17-18- 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- })23-24- 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-})30-31-describe('Basic Auth Middleware without `hashFunction`', () => {32- const app = new Hono()33-34- const username = 'hono-user-a'35- const password = 'hono-password-a'36- app.use(37- '/auth/*',38- basicAuth({39- username,40- password,41- })42- )43-44- app.get('/auth/*', () => new Response('auth'))45-46- 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-})54-55-describe('Basic Auth Middleware with `hashFunction`', () => {56- const app = new Hono()57-58- 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- )68-69- app.get('/auth/*', () => new Response('auth'))70-71- 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- })77-78- 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-})87-88-describe('JWT Auth Middleware does not work', () => {89- const app = new Hono()90-91- 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
1-NAME=Lagondeleted:test_lagon/index.test.ts-209 removed
1-describe('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- })9-10- 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- })15-16- 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- })21-22- 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- })27-28- /*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- */36-37- 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- })42-43- 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- })49-50- 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- })55-56- 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- })64-65- 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- })72-73- 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- })79-80- 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- })90-91- 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- })97-98- 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- })108-109- 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- })115-116- 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- })121-122- 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- })131-132- 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- })142-143- 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- })150-151- 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- })156-157- 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- })172-173- 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: `-----------------------------9051914041544843365972754266181-Content-Disposition: form-data; name="hello"182-183-world!184------------------------------9051914041544843365972754266185-Content-Disposition: form-data; name="description"186-187-this 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- })197-198- 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- })203-204- 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
1-import { Hono } from '../src'2-import { env } from '../src/adapter'3-import { HTTPException } from '../src/http-exception'4-import { basicAuth } from '../src/middleware/basic-auth'5-import { bearerAuth } from '../src/middleware/bearer-auth'6-import { etag } from '../src/middleware/etag'7-import { poweredBy } from '../src/middleware/powered-by'8-import { prettyJSON } from '../src/middleware/pretty-json'9-10-const app = new Hono()11-12-// Mount Builtin Middleware13-app.use('*', poweredBy())14-// app.use('*', logger())15-app.use(16- '/basic-auth/*',17- basicAuth({18- username: 'hono',19- password: 'acoolproject',20- })21-)22-app.use(23- '/bearer-auth/*',24- bearerAuth({25- token: 'secrettoken',26- })27-)28-app.use('/etag/*', etag())29-30-app.get('/env', (c) => {31- const { NAME } = env<{ NAME: string }>(c)32- return c.text(NAME)33-})34-35-// Custom Middleware36-// Add Custom Header37-app.use('/hello/*', async (c, next) => {38- await next()39- c.header('X-message', 'This is addHeader middleware!')40-})41-42-// Add X-Response-Time header43-app.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-})49-50-// Custom Not Found Message51-app.notFound((c) => {52- return c.text('Custom 404 Not Found', 404)53-})54-55-// Error handling56-app.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-})63-64-app.head('/', (c) => c.text('OK'))65-66-// Routing67-app.get('/', (c) => c.text('Hono!!'))68-// Use Response object directly69-app.get('/hello', () => new Response('This is /hello'))70-71-app.get('/runtime', (c) => new Response(c.runtime))72-73-// Named parameter74-app.get('/entry/:id', (c) => {75- const id = c.req.param('id')76- return c.text(`Your ID is ${id}`)77-})78-79-// Nested route80-const book = new Hono()81-book.get('/', (c) => c.text('List Books'))82-book.get('/:id', (c) => {83- const id = c.req.param('id')84- return c.text('Get Book: ' + id)85-})86-book.post('/', (c) => c.text('Create Book'))87-app.route('/book', book)88-89-// Redirect90-app.get('/redirect', (c) => c.redirect('/'))91-// Authentication required92-app.get('/basic-auth/*', (c) => c.text('You are authorized'))93-app.get('/bearer-auth/*', (c) => c.text('You are authorized'))94-// ETag95-app.get('/etag/cached', (c) => c.text('Is this cached?'))96-97-// Async98-app.get('/fetch-url', async (c) => {99- const response = await fetch('https://example.com/')100- return c.text(`https://example.com/ is ${response.status}`)101-})102-103-// Request headers104-app.get('/user-agent', (c) => {105- const userAgent = c.req.header('User-Agent')106- return c.text(`Your UserAgent is ${userAgent}`)107-})108-109-// JSON110-app.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 code120-app.post('/api/posts', (c) => c.json({ message: 'Created!' }, 201))121-// default route122-app.get('/api/*', (c) => c.text('API endpoint is not found', 404))123-124-app.post('/form', async (c) => {125- const body = await c.req.parseBody()126- return c.json(body)127-})128-129-// Throw Error130-app.get('/error', () => {131- throw Error('Error has occurred')132-})133-134-export const handler = app.fetchdeleted:test_lambda/index.test.ts-118 removed
1-import { handle } from '../src/adapter/aws-lambda/handler'2-import { Hono } from '../src/hono'3-import { basicAuth } from '../src/middleware/basic-auth'4-5-describe('AWS Lambda Adapter for Hono', () => {6- const app = new Hono()7-8- app.get('/', (c) => {9- return c.text('Hello Lambda!')10- })11-12- app.post('/post', async (c) => {13- const body = (await c.req.parseBody()) as { message: string }14- return c.text(body.message)15- })16-17- 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!'))21-22- const handler = handle(app)23-24- 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- }35-36- 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- })42-43- 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- }54-55- const response = await handler(event)56- expect(response.statusCode).toBe(404)57- })58-59- 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- }74-75- const response = await handler(event)76- expect(response.statusCode).toBe(200)77- expect(response.body).toBe('Good Morning Lambda!')78- })79-80- 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- }93-94- const response = await handler(event)95- expect(response.statusCode).toBe(401)96- })97-98- 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- }113-114- 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
1-import { createAdaptorServer } from '@hono/node-server'2-import request from 'supertest'3-import { Hono } from '../src'4-import { env } from '../src/adapter'5-import { Context } from '../src/context'6-import { basicAuth } from '../src/middleware/basic-auth'7-import { jwt } from '../src/middleware/jwt'8-9-// Test only minimal patterns.10-// See <https://github.com/honojs/node-server> for more tests and information.11-12-describe('Basic', () => {13- const app = new Hono()14-15- app.get('/', (c) => {16- return c.text('Hello! Node.js!')17- })18- app.get('/runtime-name', (c) => {19- return c.text(c.runtime)20- })21-22- const server = createAdaptorServer(app)23-24- 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- })29-30- 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-})36-37-describe('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-})44-45-describe('Basic Auth Middleware', () => {46- const app = new Hono()47-48- const username = 'hono-user-a'49- const password = 'hono-password-a'50- app.use(51- '/auth/*',52- basicAuth({53- username,54- password,55- })56- )57-58- app.get('/auth/*', () => new Response('auth'))59-60- const server = createAdaptorServer(app)61-62- 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- })67-68- 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-})75-76-describe('JWT Auth Middleware', () => {77- const app = new Hono()78-79- app.use('/jwt/*', jwt({ secret: 'a-secret' }))80- app.get('/jwt/a', (c) => c.text('auth'))81-82- const server = createAdaptorServer(app)83-84- 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- })89-90- 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
1-import { unstable_dev } from 'wrangler'2-import type { UnstableDevWorker } from 'wrangler'3-4-describe('Wrangler', () => {5- let worker: UnstableDevWorker6-7- beforeAll(async () => {8- worker = await unstable_dev('./test_wrangler/index.ts', {9- vars: {10- NAME: 'Cloudflare',11- },12- experimental: { disableExperimentalWarning: true },13- })14- })15-16- afterAll(async () => {17- await worker.stop()18- })19-20- 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- })25-26- 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
1-import { env } from '../src/adapter'2-import { Hono } from '../src/hono'3-4-const app = new Hono()5-6-app.get('/', (c) => c.text('Hello Wrangler!'))7-8-app.get('/env', (c) => {9- const { NAME } = env<{ NAME: string }>(c)10- return c.text(NAME)11-})12-13-export default appdeleted:jest.fastly.config.js-7 removed
1-export 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
1-export default {2- testMatch: ['**/test_lambda/**/*.+(ts|tsx|js)'],3- transform: {4- '^.+\\.(ts|tsx)$': 'ts-jest',5- },6-}deleted:jest.node.config.js-6 removed
1-export default {2- testMatch: ['**/test_node/**/*.+(ts|tsx|js)'],3- transform: {4- '^.+\\.(ts|tsx)$': 'ts-jest',5- },6-}deleted:jest.wrangler.config.js-6 removed
1-export 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 lines10 "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