chore: rm `*.ts.test` from deno_dist (#338)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent e593dfb · Browse files · 34 files·+6 added−4808 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
34 files+6 added−4808 removed
- tests:+0 added−4802 removed
- other:+6 added−6 removed
Provenance
- Commit
6030c05- Tree
c428e7e- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
e593dfb
34 files changed+6 added−4808 removed
deleted:deno_dist/middleware/basic-auth/index.test.ts-159 removed
1-import { Buffer } from "https://deno.land/std@0.85.0/node/buffer.ts";2-import { SHA256 } from 'crypto-js DENOIFY: DEPENDENCY UNMET (DEV DEPENDENCY)'3-import { Hono } from '../../hono.ts'4-import { basicAuth } from './index.ts'5-6-describe('Basic Auth by Middleware', () => {7- const crypto = global.crypto8- beforeAll(() => {9- global.crypto = require('crypto').webcrypto10- })11- afterAll(() => {12- global.crypto = crypto13- })14-15- const app = new Hono()16-17- const username = 'hono-user-a'18- const password = 'hono-password-a'19- const unicodePassword = '炎'20-21- const usernameB = 'hono-user-b'22- const passwordB = 'hono-password-b'23-24- const usernameC = 'hono-user-c'25- const passwordC = 'hono-password-c'26-27- app.use(28- '/auth/*',29- basicAuth({30- username,31- password,32- })33- )34-35- app.use(36- '/auth-unicode/*',37- basicAuth({38- username: username,39- password: unicodePassword,40- })41- )42-43- app.use(44- '/auth-multi/*',45- basicAuth(46- {47- username: usernameB,48- password: passwordB,49- },50- {51- username: usernameC,52- password: passwordC,53- }54- )55- )56-57- app.use(58- '/auth-override-func/*',59- basicAuth({60- username: username,61- password: password,62- hashFunction: (data: string) => SHA256(data).toString(),63- })64- )65-66- app.use('/nested/*', async (c, next) => {67- const auth = basicAuth({ username: username, password: password })68- await auth(c, next)69- })70-71- app.get('/auth/*', () => new Response('auth'))72- app.get('/auth-unicode/*', () => new Response('auth'))73- app.get('/auth-multi/*', () => new Response('auth'))74- app.get('/auth-override-func/*', () => new Response('auth'))75-76- app.get('/nested/*', () => new Response('nested'))77-78- it('Should not authorize', async () => {79- const req = new Request('http://localhost/auth/a')80- const res = await app.request(req)81- expect(res).not.toBeNull()82- expect(res.status).toBe(401)83- expect(await res.text()).toBe('Unauthorized')84- })85-86- it('Should authorize', async () => {87- const credential = Buffer.from(username + ':' + password).toString('base64')88-89- const req = new Request('http://localhost/auth/a')90- req.headers.set('Authorization', `Basic ${credential}`)91- const res = await app.request(req)92- expect(res).not.toBeNull()93- expect(res.status).toBe(200)94- expect(await res.text()).toBe('auth')95- })96-97- it('Should authorize Unicode', async () => {98- const credential = Buffer.from(username + ':' + unicodePassword).toString('base64')99-100- const req = new Request('http://localhost/auth-unicode/a')101- req.headers.set('Authorization', `Basic ${credential}`)102- const res = await app.request(req)103- expect(res).not.toBeNull()104- expect(res.status).toBe(200)105- expect(await res.text()).toBe('auth')106- })107-108- it('Should authorize multiple users', async () => {109- let credential = Buffer.from(usernameB + ':' + passwordB).toString('base64')110-111- let req = new Request('http://localhost/auth-multi/b')112- req.headers.set('Authorization', `Basic ${credential}`)113- let res = await app.request(req)114- expect(res).not.toBeNull()115- expect(res.status).toBe(200)116- expect(await res.text()).toBe('auth')117-118- credential = Buffer.from(usernameC + ':' + passwordC).toString('base64')119- req = new Request('http://localhost/auth-multi/c')120- req.headers.set('Authorization', `Basic ${credential}`)121- res = await app.request(req)122- expect(res).not.toBeNull()123- expect(res.status).toBe(200)124- expect(await res.text()).toBe('auth')125- })126-127- it('Should authorize with sha256 function override', async () => {128- const credential = Buffer.from(username + ':' + password).toString('base64')129-130- const req = new Request('http://localhost/auth-override-func/a')131- req.headers.set('Authorization', `Basic ${credential}`)132- const res = await app.request(req)133- expect(res).not.toBeNull()134- expect(res.status).toBe(200)135- expect(await res.text()).toBe('auth')136- })137-138- it('Should authorize - nested', async () => {139- const credential = Buffer.from(username + ':' + password).toString('base64')140-141- const req = new Request('http://localhost/nested')142- req.headers.set('Authorization', `Basic ${credential}`)143- const res = await app.request(req)144- expect(res).not.toBeNull()145- expect(res.status).toBe(200)146- expect(await res.text()).toBe('nested')147- })148-149- it('Should not authorize - nested', async () => {150- const credential = Buffer.from('foo' + ':' + 'bar').toString('base64')151-152- const req = new Request('http://localhost/nested')153- req.headers.set('Authorization', `Basic ${credential}`)154- const res = await app.request(req)155- expect(res).not.toBeNull()156- expect(res.status).toBe(401)157- expect(await res.text()).toBe('Unauthorized')158- })159-})deleted:deno_dist/middleware/bearer-auth/index.test.ts-67 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import { Hono } from '../../hono.ts'import { bearerAuth } from './index.ts'
describe('Bearer Auth by Middleware', () => { const app = new Hono()
const token = 'abcdefg12345-._~+/='
app.use('/auth/*', bearerAuth({ token })) app.use('/authBot/*', bearerAuth({ token, prefix: 'Bot' }))
app.get('/auth/*', () => new Response('auth')) app.get('/authBot/*', () => new Response('auth bot'))
it('Should authorize', async () => { const req = new Request('http://localhost/auth/a') req.headers.set('Authorization', 'Bearer abcdefg12345-._~+/=') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth') })
it('Should not authorize - no authorization header', async () => { const req = new Request('http://localhost/auth/a') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(401) expect(await res.text()).toBe('Unauthorized') })
it('Should not authorize - invalid request', async () => { const req = new Request('http://localhost/auth/a') req.headers.set('Authorization', 'Beare abcdefg12345-._~+/=') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(400) expect(await res.text()).toBe('Bad Request') })
it('Should not authorize - invalid token', async () => { const req = new Request('http://localhost/auth/a') req.headers.set('Authorization', 'Bearer invalid-token') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(401) expect(await res.text()).toBe('Unauthorized') })
it('Should authorize', async () => { const req = new Request('http://localhost/authBot/a') req.headers.set('Authorization', 'Bot abcdefg12345-._~+/=') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth bot') })
it('Should not authorize - invalid request', async () => { const req = new Request('http://localhost/authBot/a') req.headers.set('Authorization', 'Bearer abcdefg12345-._~+/=') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(400) expect(await res.text()).toBe('Bad Request') })})deleted:deno_dist/middleware/body-parse/index.test.ts-62 removed
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import { Hono } from '../../hono.ts'import { bodyParse } from './index.ts'
describe('Parse Body Middleware', () => { const app = new Hono()
app.use('*', bodyParse()) app.post('/json', async (ctx) => { return ctx.json(ctx.req.parsedBody, 200) }) app.post('/text', async (ctx) => { return ctx.text(ctx.req.parsedBody, 200) }) app.post('/form', async (ctx) => { return ctx.json(ctx.req.parsedBody, 200) })
it('POST with JSON', async () => { const payload = { message: 'hello hono' } const req = new Request('http://localhost/json', { method: 'POST', body: JSON.stringify(payload), headers: new Headers({ 'Content-Type': 'application/json' }), }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(req.parsedBody).toEqual(payload) expect(await res.json()).toEqual(payload) })
it('POST with text', async () => { const payload = 'hello' const req = new Request('http://localhost/text', { method: 'POST', body: 'hello', headers: new Headers({ 'Content-Type': 'application/text' }), }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(req.parsedBody).toEqual(payload) expect(await res.text()).toEqual(payload) })
it('POST with form', async () => { const formData = new URLSearchParams() formData.append('message', 'hello') const req = new Request('https://localhost/form', { method: 'POST', body: formData, headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(req.parsedBody).toEqual({ message: 'hello' }) expect(await res.json()).toEqual({ message: 'hello' }) })})deleted:deno_dist/middleware/cookie/index.test.ts-95 removed
1-import { Hono } from '../../hono.ts'2-import { cookie } from './index.ts'3-4-describe('Cookie Middleware', () => {5- describe('Parse cookie', () => {6- const apps: Record<string, Hono> = {}7- apps['get by name'] = (() => {8- const app = new Hono()9-10- app.use('/cookie', cookie())11-12- app.get('/cookie', (c) => {13- const yummyCookie = c.req.cookie('yummy_cookie')14- const tastyCookie = c.req.cookie('tasty_cookie')15- const res = new Response('Good cookie')16- res.headers.set('Yummy-Cookie', yummyCookie)17- res.headers.set('Tasty-Cookie', tastyCookie)18- return res19- })20-21- return app22- })()23-24- apps['get all as an object'] = (() => {25- const app = new Hono()26-27- app.use('/cookie', cookie())28-29- app.get('/cookie', (c) => {30- const { yummy_cookie: yummyCookie, tasty_cookie: tastyCookie } = c.req.cookie()31- const res = new Response('Good cookie')32- res.headers.set('Yummy-Cookie', yummyCookie)33- res.headers.set('Tasty-Cookie', tastyCookie)34- return res35- })36-37- return app38- })()39-40- describe.each(Object.keys(apps))('%s', (name) => {41- const app = apps[name]42- it('Parse cookie on c.req.cookie', async () => {43- const req = new Request('http://localhost/cookie')44- const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry '45- req.headers.set('Cookie', cookieString)46- const res = await app.request(req)47-48- expect(res.headers.get('Yummy-Cookie')).toBe('choco')49- expect(res.headers.get('Tasty-Cookie')).toBe('strawberry')50- })51- })52- })53-54- describe('Set cookie', () => {55- const app = new Hono()56-57- app.use('/set-cookie', cookie())58-59- app.get('/set-cookie', (c) => {60- c.cookie('delicious_cookie', 'macha')61- return c.text('Give cookie')62- })63-64- it('Set cookie on c.cookie', async () => {65- const res = await app.request('http://localhost/set-cookie')66- expect(res.status).toBe(200)67- const header = res.headers.get('Set-Cookie')68- expect(header).toBe('delicious_cookie=macha')69- })70-71- app.use('/set-cookie-complex', cookie())72-73- app.get('/set-cookie-complex', (c) => {74- c.cookie('great_cookie', 'banana', {75- path: '/',76- secure: true,77- domain: 'example.com',78- httpOnly: true,79- maxAge: 1000,80- expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),81- sameSite: 'Strict',82- })83- return c.text('Give cookie')84- })85-86- it('Complex pattern', async () => {87- const res = await app.request('http://localhost/set-cookie-complex')88- expect(res.status).toBe(200)89- const header = res.headers.get('Set-Cookie')90- expect(header).toBe(91- 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'92- )93- })94- })95-})deleted:deno_dist/middleware/cors/index.test.ts-69 removed
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import { Hono } from '../../hono.ts'import { cors } from '../../middleware/cors/index.ts'
describe('CORS by Middleware', () => { const app = new Hono()
app.use('/api/*', cors()) app.use( '/api2/*', cors({ origin: 'http://example.com', allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'], allowMethods: ['POST', 'GET', 'OPTIONS'], exposeHeaders: ['Content-Length', 'X-Kuma-Revision'], maxAge: 600, credentials: true, }) )
app.all('/api/abc', (c) => { return c.json({ success: true }) }) app.all('/api2/abc', (c) => { return c.json({ success: true }) })
it('GET default', async () => { const res = await app.request('http://localhost/api/abc')
expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*') expect(res.headers.get('Vary')).toBeNull() })
it('Preflight default', async () => { const req = new Request('https://localhost/api/abc', { method: 'OPTIONS' }) req.headers.append('Access-Control-Request-Headers', 'X-PINGOTHER, Content-Type') const res = await app.request(req)
expect(res.status).toBe(204) expect(res.headers.get('Access-Control-Allow-Methods')?.split(',')[0]).toBe('GET') expect(res.headers.get('Access-Control-Allow-Headers')?.split(',')).toEqual([ 'X-PINGOTHER', 'Content-Type', ]) })
it('Preflight with options', async () => { const req = new Request('https://localhost/api2/abc', { method: 'OPTIONS' }) const res = await app.request(req)
expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com') expect(res.headers.get('Vary')?.split(/\s*,\s*/)).toEqual(expect.arrayContaining(['Origin'])) expect(res.headers.get('Access-Control-Allow-Headers')?.split(/\s*,\s*/)).toEqual([ 'X-Custom-Header', 'Upgrade-Insecure-Requests', ]) expect(res.headers.get('Access-Control-Allow-Methods')?.split(/\s*,\s*/)).toEqual([ 'POST', 'GET', 'OPTIONS', ]) expect(res.headers.get('Access-Control-Expose-Headers')?.split(/\s*,\s*/)).toEqual([ 'Content-Length', 'X-Kuma-Revision', ]) expect(res.headers.get('Access-Control-Max-Age')).toBe('600') expect(res.headers.get('Access-Control-Allow-Credentials')).toBe('true') })})deleted:deno_dist/middleware/etag/index.test.ts-51 removed
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051import { Hono } from '../../hono.ts'import { etag } from './index.ts'
describe('Etag Middleware', () => { const app = new Hono()
app.use('/etag/*', etag()) app.get('/etag/abc', (c) => { return c.text('Hono is cool') }) app.get('/etag/def', (c) => { return c.json({ message: 'Hono is cool' }) })
app.use('/etag-weak/*', etag({ weak: true })) app.get('/etag-weak/abc', (c) => { return c.text('Hono is cool') })
it('Should return etag header', async () => { let res = await app.request('http://localhost/etag/abc') expect(res.headers.get('ETag')).not.toBeFalsy() expect(res.headers.get('ETag')).toBe('"4e32298b1cb4edc595237405e5b696e105c2399a"')
res = await app.request('http://localhost/etag/def') expect(res.headers.get('ETag')).not.toBeFalsy() expect(res.headers.get('ETag')).toBe('"c1d44ff03aff1372856c281854f454e2e1d15b7c"') })
it('Should return etag header - weak', async () => { const res = await app.request('http://localhost/etag-weak/abc') expect(res.headers.get('ETag')).not.toBeFalsy() expect(res.headers.get('ETag')).toBe('W/"4e32298b1cb4edc595237405e5b696e105c2399a"') })
it('Should return 304 response', async () => { let res = await app.request('http://localhost/etag/abc') expect(res.status).toBe(200) expect(res.headers.get('ETag')).not.toBeFalsy() const etag = res.headers.get('Etag') || ''
const req = new Request('http://localhost/etag/abc', { headers: { 'If-None-Match': etag, }, }) res = await app.request(req) expect(res.status).toBe(304) expect(await res.text()).toBe('') })})deleted:deno_dist/middleware/graphql-server/index.test.ts-573 removed
1-import {2- buildSchema,3- GraphQLSchema,4- GraphQLString,5- GraphQLObjectType,6- GraphQLNonNull,7-} from 'https://cdn.skypack.dev/graphql@16.4.0?dts'8-import { Hono } from '../../hono.ts'9-import { errorMessages, graphqlServer } from './index.ts'10-11-// Do not show `console.error` messages12-jest.spyOn(console, 'error').mockImplementation()13-14-describe('errorMessages', () => {15- const messages = errorMessages(['message a', 'message b'])16- expect(messages).toEqual({17- errors: [18- {19- message: 'message a',20- },21- {22- message: 'message b',23- },24- ],25- })26-})27-28-describe('GraphQL Middleware - Simple way', () => {29- // Construct a schema, using GraphQL schema language30- const schema = buildSchema(`31- type Query {32- hello: String33- }34-`)35-36- // The root provides a resolver function for each API endpoint37- const rootValue = {38- hello: () => 'Hello world!',39- }40-41- const app = new Hono()42-43- app.use(44- '/graphql',45- graphqlServer({46- schema,47- rootValue,48- })49- )50-51- app.all('*', (c) => {52- c.header('foo', 'bar')53- return c.text('fallback')54- })55-56- it('Should return GraphQL response', async () => {57- const query = 'query { hello }'58- const body = {59- query: query,60- }61-62- const res = await app.request('http://localhost/graphql', {63- method: 'POST',64- headers: {65- 'Content-Type': 'application/json',66- },67- body: JSON.stringify(body),68- })69- expect(res).not.toBeNull()70- expect(res.status).toBe(200)71- expect(await res.text()).toBe('{"data":{"hello":"Hello world!"}}')72- expect(res.headers.get('foo')).toBeNull() // GraphQL Server middleware should be Handler73- })74-})75-76-const QueryRootType = new GraphQLObjectType({77- name: 'QueryRoot',78- fields: {79- test: {80- type: GraphQLString,81- args: {82- who: { type: GraphQLString },83- },84- resolve: (_root, args: { who?: string }) => 'Hello ' + (args.who ?? 'World'),85- },86- thrower: {87- type: GraphQLString,88- resolve() {89- throw new Error('Throws!')90- },91- },92- },93-})94-95-const TestSchema = new GraphQLSchema({96- query: QueryRootType,97- mutation: new GraphQLObjectType({98- name: 'MutationRoot',99- fields: {100- writeTest: {101- type: QueryRootType,102- resolve: () => ({}),103- },104- },105- }),106-})107-108-const urlString = (query?: Record<string, string>): string => {109- const base = 'http://localhost/graphql'110- if (!query) return base111- const queryString = new URLSearchParams(query).toString()112- return `${base}?${queryString}`113-}114-115-describe('GraphQL Middleware - GET functionality', () => {116- const app = new Hono()117- app.use(118- '/graphql',119- graphqlServer({120- schema: TestSchema,121- })122- )123-124- it('Allows GET with variable values', async () => {125- const query = {126- query: 'query helloWho($who: String){ test(who: $who) }',127- variables: JSON.stringify({ who: 'Dolly' }),128- }129-130- const res = await app.request(urlString(query), {131- method: 'GET',132- })133- expect(res.status).toBe(200)134- expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')135- })136-137- it('Allows GET with operation name', async () => {138- const query = {139- query: `140- query helloYou { test(who: "You"), ...shared }141- query helloWorld { test(who: "World"), ...shared }142- query helloDolly { test(who: "Dolly"), ...shared }143- fragment shared on QueryRoot {144- shared: test(who: "Everyone")145- }146- `,147- operationName: 'helloWorld',148- }149-150- const res = await app.request(urlString(query), {151- method: 'GET',152- })153- expect(res.status).toBe(200)154- expect(await res.json()).toEqual({155- data: {156- test: 'Hello World',157- shared: 'Hello Everyone',158- },159- })160- })161-162- it('Reports validation errors', async () => {163- const query = { query: '{ test, unknownOne, unknownTwo }' }164- const res = await app.request(urlString(query), {165- method: 'GET',166- })167- expect(res.status).toBe(400)168- })169-170- it('Errors when missing operation name', async () => {171- const query = {172- query: `173- query TestQuery { test }174- mutation TestMutation { writeTest { test } }175- `,176- }177- const res = await app.request(urlString(query), {178- method: 'GET',179- })180- expect(res.status).toBe(500)181- })182-183- it('Errors when sending a mutation via GET', async () => {184- const query = {185- query: 'mutation TestMutation { writeTest { test } }',186- }187- const res = await app.request(urlString(query), {188- method: 'GET',189- })190- expect(res.status).toBe(405)191- })192-193- it('Errors when selecting a mutation within a GET', async () => {194- const query = {195- operationName: 'TestMutation',196- query: `197- query TestQuery { test }198- mutation TestMutation { writeTest { test } }199- `,200- }201- const res = await app.request(urlString(query), {202- method: 'GET',203- })204- expect(res.status).toBe(405)205- })206-207- it('Allows a mutation to exist within a GET', async () => {208- const query = {209- operationName: 'TestQuery',210- query: `211- mutation TestMutation { writeTest { test } }212- query TestQuery { test }213- `,214- }215- const res = await app.request(urlString(query), {216- method: 'GET',217- })218- expect(res.status).toBe(200)219- expect(await res.json()).toEqual({220- data: {221- test: 'Hello World',222- },223- })224- })225-})226-227-describe('GraphQL Middleware - POST functionality', () => {228- const app = new Hono()229- app.use(230- '/graphql',231- graphqlServer({232- schema: TestSchema,233- })234- )235-236- it('Allows POST with JSON encoding', async () => {237- const query = { query: '{test}' }238-239- const res = await app.request(urlString(), {240- method: 'POST',241- headers: {242- 'Content-Type': 'application/json',243- },244- body: JSON.stringify(query),245- })246- expect(res.status).toBe(200)247- expect(await res.text()).toBe('{"data":{"test":"Hello World"}}')248- })249-250- it('Allows sending a mutation via POST', async () => {251- const query = { query: 'mutation TestMutation { writeTest { test } }' }252- const res = await app.request(urlString(), {253- method: 'POST',254- headers: {255- 'Content-Type': 'application/json',256- },257- body: JSON.stringify(query),258- })259- expect(res.status).toBe(200)260- expect(await res.text()).toBe('{"data":{"writeTest":{"test":"Hello World"}}}')261- })262-263- it('Allows POST with url encoding', async () => {264- const query = {265- query: '{test}',266- }267- const res = await app.request(urlString(query), {268- method: 'POST',269- })270- expect(res.status).toBe(200)271- expect(await res.text()).toBe('{"data":{"test":"Hello World"}}')272- })273-274- it('Supports POST JSON query with string variables', async () => {275- const query = {276- query: 'query helloWho($who: String){ test(who: $who) }',277- variables: JSON.stringify({ who: 'Dolly' }),278- }279- const res = await app.request(urlString(), {280- method: 'POST',281- headers: {282- 'Content-Type': 'application/json',283- },284- body: JSON.stringify(query),285- })286- expect(res.status).toBe(200)287- expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')288- })289-290- it('Supports POST url encoded query with string variables', async () => {291- const searchParams = new URLSearchParams({292- query: 'query helloWho($who: String){ test(who: $who) }',293- variables: JSON.stringify({ who: 'Dolly' }),294- })295- const res = await app.request(urlString(), {296- method: 'POST',297- headers: {298- 'Content-Type': 'application/x-www-form-urlencoded',299- },300- body: searchParams.toString(),301- })302- expect(res.status).toBe(200)303- expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')304- })305-306- it('Supports POST JSON query with GET variable values', async () => {307- const variables = {308- variables: JSON.stringify({ who: 'Dolly' }),309- }310- const query = { query: 'query helloWho($who: String){ test(who: $who) }' }311- const res = await app.request(urlString(variables), {312- method: 'POST',313- headers: {314- 'Content-Type': 'application/json',315- },316- body: JSON.stringify(query),317- })318- expect(res.status).toBe(200)319- expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')320- })321-322- it('Supports POST url encoded query with GET variable values', async () => {323- const searchParams = new URLSearchParams({324- query: 'query helloWho($who: String){ test(who: $who) }',325- })326- const variables = {327- variables: JSON.stringify({ who: 'Dolly' }),328- }329- const res = await app.request(urlString(variables), {330- method: 'POST',331- headers: {332- 'Content-Type': 'application/x-www-form-urlencoded',333- },334- body: searchParams.toString(),335- })336- expect(res.status).toBe(200)337- expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')338- })339-340- it('Supports POST raw text query with GET variable values', async () => {341- const variables = {342- variables: JSON.stringify({ who: 'Dolly' }),343- }344- const res = await app.request(urlString(variables), {345- method: 'POST',346- headers: {347- 'Content-Type': 'application/graphql',348- },349- body: 'query helloWho($who: String){ test(who: $who) }',350- })351- expect(res.status).toBe(200)352- expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')353- })354-355- it('Allows POST with operation name', async () => {356- const query = {357- query: `358- query helloYou { test(who: "You"), ...shared }359- query helloWorld { test(who: "World"), ...shared }360- query helloDolly { test(who: "Dolly"), ...shared }361- fragment shared on QueryRoot {362- shared: test(who: "Everyone")363- }364- `,365- operationName: 'helloWorld',366- }367- const res = await app.request(urlString(), {368- method: 'POST',369- headers: {370- 'Content-Type': 'application/json',371- },372- body: JSON.stringify(query),373- })374- expect(res.status).toBe(200)375- expect(await res.json()).toEqual({376- data: {377- test: 'Hello World',378- shared: 'Hello Everyone',379- },380- })381- })382-383- it('Allows POST with GET operation name', async () => {384- const res = await app.request(385- urlString({386- operationName: 'helloWorld',387- }),388- {389- method: 'POST',390- headers: {391- 'Content-Type': 'application/graphql',392- },393- body: `394- query helloYou { test(who: "You"), ...shared }395- query helloWorld { test(who: "World"), ...shared }396- query helloDolly { test(who: "Dolly"), ...shared }397- fragment shared on QueryRoot {398- shared: test(who: "Everyone")399- }400- `,401- }402- )403- expect(res.status).toBe(200)404- expect(await res.json()).toEqual({405- data: {406- test: 'Hello World',407- shared: 'Hello Everyone',408- },409- })410- })411-})412-413-describe('Pretty printing', () => {414- it('Supports pretty printing', async () => {415- const app = new Hono()416-417- app.use(418- '/graphql',419- graphqlServer({420- schema: TestSchema,421- pretty: true,422- })423- )424-425- const res = await app.request(urlString({ query: '{test}' }))426- expect(await res.text()).toEqual(427- [428- // Pretty printed JSON429- '{',430- ' "data": {',431- ' "test": "Hello World"',432- ' }',433- '}',434- ].join('\n')435- )436- })437-})438-439-describe('Error handling functionality', () => {440- const app = new Hono()441- app.use(442- '/graphql',443- graphqlServer({444- schema: TestSchema,445- })446- )447-448- it('Handles query errors from non-null top field errors', async () => {449- const schema = new GraphQLSchema({450- query: new GraphQLObjectType({451- name: 'Query',452- fields: {453- test: {454- type: new GraphQLNonNull(GraphQLString),455- resolve() {456- throw new Error('Throws!')457- },458- },459- },460- }),461- })462- const app = new Hono()463-464- app.use('/graphql', graphqlServer({ schema }))465-466- const res = await app.request(467- urlString({468- query: '{ test }',469- })470- )471-472- expect(res.status).toBe(500)473- })474-475- it('Handles syntax errors caught by GraphQL', async () => {476- const res = await app.request(477- urlString({478- query: 'syntax_error',479- }),480- {481- method: 'GET',482- }483- )484-485- expect(res.status).toBe(400)486- })487-488- it('Handles errors caused by a lack of query', async () => {489- const res = await app.request(urlString(), {490- method: 'GET',491- })492-493- expect(res.status).toBe(400)494- })495-496- it('Handles invalid JSON bodies', async () => {497- const res = await app.request(urlString(), {498- method: 'POST',499- headers: {500- 'Content-Type': 'application/json',501- },502- body: JSON.stringify([]),503- })504-505- expect(res.status).toBe(400)506- })507-508- it('Handles incomplete JSON bodies', async () => {509- const res = await app.request(urlString(), {510- method: 'POST',511- headers: {512- 'Content-Type': 'application/json',513- },514- body: '{"query":',515- })516- expect(res.status).toBe(400)517- })518-519- it('Handles plain POST text', async () => {520- const res = await app.request(521- urlString({522- variables: JSON.stringify({ who: 'Dolly' }),523- }),524- {525- method: 'POST',526- headers: {527- 'Content-Type': 'text/plain',528- },529- body: 'query helloWho($who: String){ test(who: $who) }',530- }531- )532- expect(res.status).toBe(400)533- })534-535- it('Handles poorly formed variables', async () => {536- const res = await app.request(537- urlString({538- variables: 'who:You',539- query: 'query helloWho($who: String){ test(who: $who) }',540- }),541- {542- method: 'GET',543- }544- )545- expect(res.status).toBe(400)546- })547-548- it('Handles invalid variables', async () => {549- const res = await app.request(urlString(), {550- method: 'POST',551- headers: {552- 'Content-Type': 'application/json',553- },554- body: JSON.stringify({555- query: 'query helloWho($who: String){ test(who: $who) }',556- variables: { who: ['John', 'Jane'] },557- }),558- })559- expect(res.status).toBe(500)560- })561-562- it('Handles unsupported HTTP methods', async () => {563- const res = await app.request(urlString({ query: '{test}' }), {564- method: 'PUT',565- })566-567- expect(res.status).toBe(405)568- expect(res.headers.get('allow')).toBe('GET, POST')569- expect(await res.json()).toEqual({570- errors: [{ message: 'GraphQL only supports GET and POST requests.' }],571- })572- })573-})deleted:deno_dist/middleware/graphql-server/parse-body.test.ts-61 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061import { parseBody } from './parse-body.ts'
describe('parseBody', () => { it('Should return a blank JSON object', async () => { const req = new Request('http://localhost/graphql') const res = await parseBody(req) expect(res).toEqual({}) })
it('With Content-Type: application/graphql', async () => { const req = new Request('http://localhost/graphql', { method: 'POST', headers: { 'Content-Type': 'application/graphql', }, body: 'query { hello }', }) const res = await parseBody(req) expect(res).toEqual({ query: 'query { hello }' }) })
it('With Content-Type: application/json', async () => { const variables = JSON.stringify({ who: 'Dolly' }) const req = new Request('http://localhost/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: 'query { hello }', variables: variables, }), }) const res = await parseBody(req) expect(res).toEqual({ query: 'query { hello }', variables: variables, }) })
it('With Content-Type: application/x-www-form-urlencoded', async () => { const variables = JSON.stringify({ who: 'Dolly' })
const searchParams = new URLSearchParams() searchParams.append('query', 'query { hello }') searchParams.append('variables', variables) const req = new Request('http://localhost/graphql', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: searchParams.toString(), }) const res = await parseBody(req)
expect(res).toEqual({ query: 'query { hello }', variables: variables, }) })})deleted:deno_dist/middleware/html/index.test.ts-41 removed
1234567891011121314151617181920212223242526272829303132333435363738394041import { html, raw } from './index.ts'
describe('Tagged Template Literals', () => { it('Should escape special characters', () => { const name = 'John "Johnny" Smith' // eslint-disable-next-line quotes expect(html`<p>I'm ${name}.</p>`.toString()).toBe("<p>I'm John "Johnny" Smith.</p>") })
describe('Booleans, Null, and Undefined Are Ignored', () => { it.each([true, false, undefined, null])('%s', (item) => { expect(html`${item}`.toString()).toBe('') })
it('falsy value', () => { expect(html`${0}`.toString()).toBe('0') }) })
it('Should call $array.flat(Infinity)', () => { const values = [ 'Name:', ['John "Johnny" Smith', undefined, null], ' Contact:', [html`<a href="http://example.com/">My Website</a>`], ] expect(html`<p>${values}</p>`.toString()).toBe( '<p>Name:John "Johnny" Smith Contact:<a href="http://example.com/">My Website</a></p>' ) })})
describe('raw', () => { it('Should be marked as escaped.', () => { const name = 'John "Johnny" Smith' expect(html`<p>I'm ${raw(name)}.</p>`.toString()).toBe( // eslint-disable-next-line quotes "<p>I'm John "Johnny" Smith.</p>" ) })})deleted:deno_dist/middleware/jwt/index.test.ts-95 removed
1-import { Hono } from '../../hono.ts'2-import { jwt } from './index.ts'3-4-describe('Jwt Auth by Middleware', () => {5- const crypto = global.crypto6- beforeAll(() => {7- global.crypto = require('crypto').webcrypto8- })9- afterAll(() => {10- global.crypto = crypto11- })12-13- const app = new Hono()14-15- app.use('/*', async (c, next) => {16- await next()17- c.header('x-foo', c.get('x-foo') || '')18- })19-20- app.use('/auth/*', jwt({ secret: 'a-secret' }))21- app.use('/auth-unicode/*', jwt({ secret: 'a-secret' }))22-23- app.get('/auth/*', (c) => {24- c.set('x-foo', 'bar')25- return new Response('auth')26- })27- app.get('/auth-unicode/*', (c) => {28- c.set('x-foo', 'bar')29- return new Response('auth')30- })31-32- it('Should not authorize', async () => {33- const req = new Request('http://localhost/auth/a')34- const res = await app.request(req)35- expect(res).not.toBeNull()36- expect(res.status).toBe(401)37- expect(await res.text()).toBe('Unauthorized')38- expect(res.headers.get('x-foo')).toBeFalsy()39- })40-41- it('Should authorize', async () => {42- const credential =43- 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'44- const req = new Request('http://localhost/auth/a')45- req.headers.set('Authorization', `Bearer ${credential}`)46- const res = await app.request(req)47- expect(res).not.toBeNull()48- expect(res.status).toBe(200)49- expect(await res.text()).toBe('auth')50- expect(res.headers.get('x-foo')).toBe('bar')51- })52-53- it('Should authorize Unicode', async () => {54- const credential =55- 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'56-57- const req = new Request('http://localhost/auth-unicode/a')58- req.headers.set('Authorization', `Basic ${credential}`)59- const res = await app.request(req)60- expect(res).not.toBeNull()61- expect(res.status).toBe(200)62- expect(await res.text()).toBe('auth')63- expect(res.headers.get('x-foo')).toBe('bar')64- })65-66- it('Should not authorize Unicode', async () => {67- const invalidToken =68- 'ssyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'69-70- const url = 'http://localhost/auth-unicode/a'71- const req = new Request(url)72- req.headers.set('Authorization', `Basic ${invalidToken}`)73- const res = await app.request(req)74- expect(res).not.toBeNull()75- expect(res.status).toBe(401)76- expect(res.headers.get('www-authenticate')).toEqual(77- `Bearer realm="${url}",error="invalid_token",error_description="token verification failure"`78- )79- expect(res.headers.get('x-foo')).toBeFalsy()80- })81-82- it('Should not authorize', async () => {83- const invalid_token = 'invalid token'84- const url = 'http://localhost/auth/a'85- const req = new Request(url)86- req.headers.set('Authorization', `Bearer ${invalid_token}`)87- const res = await app.request(req)88- expect(res).not.toBeNull()89- expect(res.status).toBe(401)90- expect(res.headers.get('www-authenticate')).toEqual(91- `Bearer realm="${url}",error="invalid_request",error_description="no authorization included in request"`92- )93- expect(res.headers.get('x-foo')).toBeFalsy()94- })95-})deleted:deno_dist/middleware/logger/index.test.ts-55 removed
1-import { Hono } from '../../hono.ts'2-import { logger } from './index.ts'3-4-describe('Logger by Middleware', () => {5- const app = new Hono()6-7- let log = ''8- const logFn = (str: string) => {9- log = str10- }11-12- const shortRandomString = 'hono'13- const longRandomString = 'hono'.repeat(1000)14-15- app.use('*', logger(logFn))16- app.get('/short', (c) => c.text(shortRandomString))17- app.get('/long', (c) => c.text(longRandomString))18- app.get('/empty', (c) => c.text(''))19-20- it('Log status 200 with empty body', async () => {21- const res = await app.request('http://localhost/empty')22- expect(res).not.toBeNull()23- expect(res.status).toBe(200)24- expect(log.startsWith(' --> GET /empty \x1b[32m200\x1b[0m')).toBe(true)25- expect(log).toMatch(/m?s$/)26- })27-28- it('Log status 200 with small body', async () => {29- const res = await app.request('http://localhost/short')30- expect(res).not.toBeNull()31- expect(res.status).toBe(200)32- expect(log.startsWith(' --> GET /short \x1b[32m200\x1b[0m')).toBe(true)33- expect(log).toMatch(/m?s$/)34- })35-36- it('Log status 200 with big body', async () => {37- const res = await app.request('http://localhost/long')38- expect(res).not.toBeNull()39- expect(res.status).toBe(200)40- expect(log.startsWith(' --> GET /long \x1b[32m200\x1b[0m')).toBe(true)41- expect(log).toMatch(/m?s$/)42- })43-44- it('Log status 404', async () => {45- const msg = 'Default 404 Not Found'46- app.all('*', (c) => {47- return c.text(msg, 404)48- })49- const res = await app.request('http://localhost/notfound')50- expect(res).not.toBeNull()51- expect(res.status).toBe(404)52- expect(log.startsWith(' --> GET /notfound \x1b[33m404\x1b[0m')).toBe(true)53- expect(log).toMatch(/m?s$/)54- })55-})deleted:deno_dist/middleware/mustache/mustache.test.ts-73 removed
1-import { Hono } from '../../hono.ts'2-import { mustache } from './mustache.ts'3-4-// Mock5-const store: { [key: string]: string } = {6- 'index.abcdef.mustache': '{{> header}}Title: {{ title }}{{> footer}}',7- 'header.abcdef.mustache': '<html><body>',8- 'footer.abcdef.mustache': '</body></html>',9- 'view/index.abcdef.mustache': '<h1>With Root</h1>',10- 'view/options.abcdef.mustache': '<h1>With Options</h1>',11-}12-const manifest = JSON.stringify({13- 'index.mustache': 'index.abcdef.mustache',14- 'header.mustache': 'header.abcdef.mustache',15- 'footer.mustache': 'footer.abcdef.mustache',16- 'view/index.mustache': 'view/index.abcdef.mustache',17-})18-19-Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })20-Object.assign(global, {21- __STATIC_CONTENT: {22- get: (path: string) => {23- return store[path]24- },25- },26-})27-28-describe('Mustache by Middleware', () => {29- const app = new Hono()30-31- app.use('/foo', mustache())32- app.get('/foo', (c) => {33- return c.render(34- 'index',35- { title: 'Hono!' },36- {37- header: 'header',38- footer: 'footer',39- }40- )41- })42-43- app.use('/bar', mustache({ root: 'view' }))44- app.get('/bar', (c) => {45- return c.render('index')46- })47-48- const manifest = {49- 'view/options.mustache': 'view/options.abcdef.mustache',50- }51- app.use('/options', mustache({ root: 'view', manifest: manifest }))52- app.get('/options', (c) => {53- return c.render('options')54- })55-56- it('Mustache template rendering', async () => {57- const res = await app.request('http://localhost/foo')58- expect(res.status).toBe(200)59- expect(await res.text()).toBe('<html><body>Title: Hono!</body></html>')60- })61-62- it('Mustache template rendering with root', async () => {63- const res = await app.request('http://localhost/bar')64- expect(res.status).toBe(200)65- expect(await res.text()).toBe('<h1>With Root</h1>')66- })67-68- it('Mustache template rendering with options', async () => {69- const res = await app.request('http://localhost/options')70- expect(res.status).toBe(200)71- expect(await res.text()).toBe('<h1>With Options</h1>')72- })73-})deleted:deno_dist/middleware/powered-by/index.test.ts-16 removed
1-import { Hono } from '../../hono.ts'2-import { poweredBy } from './index.ts'3-4-describe('Powered by Middleware', () => {5- const app = new Hono()6-7- app.use('*', poweredBy())8- app.get('/', (c) => c.text('root'))9-10- it('Should return with X-Powered-By header', async () => {11- const res = await app.request('http://localhost/')12- expect(res).not.toBeNull()13- expect(res.status).toBe(200)14- expect(res.headers.get('X-Powered-By')).toBe('Hono')15- })16-})deleted:deno_dist/middleware/pretty-json/index.test.ts-34 removed
1-import { Hono } from '../../hono.ts'2-import { prettyJSON } from './index.ts'3-4-describe('JSON pretty by Middleware', () => {5- it('Should return pretty JSON output', async () => {6- const app = new Hono()7- app.use('*', prettyJSON())8- app.get('/', (c) => {9- return c.json({ message: 'Hono!' })10- })11-12- const res = await app.request('http://localhost/?pretty')13- expect(res).not.toBeNull()14- expect(res.status).toBe(200)15- expect(await res.text()).toBe(`{16- "message": "Hono!"17-}`)18- })19-20- it('Should return pretty JSON output with 4 spaces', async () => {21- const app = new Hono()22- app.use('*', prettyJSON({ space: 4 }))23- app.get('/', (c) => {24- return c.json({ message: 'Hono!' })25- })26-27- const res = await app.request('http://localhost/?pretty')28- expect(res).not.toBeNull()29- expect(res.status).toBe(200)30- expect(await res.text()).toBe(`{31- "message": "Hono!"32-}`)33- })34-})deleted:deno_dist/middleware/serve-static/serve-static.test.ts-135 removed
1-import type { Context } from '../../context.ts'2-import type { Next } from '../../hono.ts'3-import { Hono } from '../../hono.ts'4-import { serveStatic } from './index.ts'5-6-// Mock7-const store: Record<string, string> = {8- 'assets/static/plain.abcdef.txt': 'This is plain.txt',9- 'assets/static/hono.abcdef.html': '<h1>Hono!</h1>',10- 'assets/static/top/index.abcdef.html': '<h1>Top</h1>',11- 'static-no-root/plain.abcdef.txt': 'That is plain.txt',12- 'assets/static/options/foo.abcdef.txt': 'With options',13-}14-const manifest = JSON.stringify({15- 'assets/static/plain.txt': 'assets/static/plain.abcdef.txt',16- 'assets/static/hono.html': 'assets/static/hono.abcdef.html',17- 'assets/static/top/index.html': 'assets/static/top/index.abcdef.html',18- 'static-no-root/plain.txt': 'static-no-root/plain.abcdef.txt',19-})20-21-Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })22-Object.assign(global, {23- __STATIC_CONTENT: {24- get: (path: string) => {25- return store[path]26- },27- },28-})29-30-describe('ServeStatic Middleware', () => {31- const app = new Hono()32- app.use('/static/*', serveStatic({ root: './assets' }))33- app.use('/static-no-root/*', serveStatic())34-35- it('Should return plain.txt', async () => {36- const res = await app.request('http://localhost/static/plain.txt')37- expect(res.status).toBe(200)38- expect(await res.text()).toBe('This is plain.txt')39- expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')40- })41-42- it('Should return hono.html', async () => {43- const res = await app.request('http://localhost/static/hono.html')44- expect(res.status).toBe(200)45- expect(await res.text()).toBe('<h1>Hono!</h1>')46- expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')47- })48-49- it('Should return 404 response', async () => {50- const res = await app.request('http://localhost/static/not-found.html')51- expect(res.status).toBe(404)52- })53-54- it('Should return plan.txt', async () => {55- const res = await app.request('http://localhost/static-no-root/plain.txt')56- expect(res.status).toBe(200)57- expect(await res.text()).toBe('That is plain.txt')58- expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')59- })60-61- it('Should return index.html', async () => {62- const res = await app.request('http://localhost/static/top')63- expect(res.status).toBe(200)64- expect(await res.text()).toBe('<h1>Top</h1>')65- expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')66- })67-})68-69-describe('With options', () => {70- const manifest = {71- 'assets/static/options/foo.txt': 'assets/static/options/foo.abcdef.txt',72- }73-74- const app = new Hono()75- app.use('/static/*', serveStatic({ root: './assets', manifest: manifest }))76-77- it('Should return foo.txt', async () => {78- const res = await app.request('http://localhost/static/options/foo.txt')79- expect(res.status).toBe(200)80- expect(await res.text()).toBe('With options')81- expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')82- })83-})84-85-describe('With `file` options', () => {86- const app = new Hono()87- app.get('/foo/*', serveStatic({ path: './assets/static/hono.html' }))88- app.get('/bar/*', serveStatic({ path: './static/hono.html', root: './assets' }))89-90- it('Should return hono.html', async () => {91- const res = await app.request('http://localhost/foo/fallback')92- expect(res.status).toBe(200)93- expect(await res.text()).toBe('<h1>Hono!</h1>')94- })95-96- it('Should return hono.html - with `root` option', async () => {97- const res = await app.request('http://localhost/bar/fallback')98- expect(res.status).toBe(200)99- expect(await res.text()).toBe('<h1>Hono!</h1>')100- })101-})102-103-describe('With middleware', () => {104- const app = new Hono()105- const md1 = async (c: Context, next: Next) => {106- await next()107- c.res.headers.append('x-foo', 'bar')108- }109- const md2 = async (c: Context, next: Next) => {110- await next()111- c.res.headers.append('x-foo2', 'bar2')112- }113-114- app.use('/static/*', md1)115- app.use('/static/*', md2)116- app.use('/static/*', serveStatic({ root: './assets' }))117- app.get('/static/foo', (c) => {118- return c.text('bar')119- })120-121- it('Should return plain.txt with correct headers', async () => {122- const res = await app.request('http://localhost/static/plain.txt')123- expect(res.status).toBe(200)124- expect(await res.text()).toBe('This is plain.txt')125- expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')126- expect(res.headers.get('x-foo')).toBe('bar')127- expect(res.headers.get('x-foo2')).toBe('bar2')128- })129-130- it('Should return 200 Response', async () => {131- const res = await app.request('http://localhost/static/foo')132- expect(res.status).toBe(200)133- expect(await res.text()).toBe('bar')134- })135-})deleted:deno_dist/router/reg-exp-router/router.test.ts-295 removed
1-import { METHOD_NAME_ALL } from '../../router.ts'2-import { RegExpRouter } from './router.ts'3-4-describe('Basic Usage', () => {5- const router = new RegExpRouter<string>()6-7- router.add('GET', '/hello', 'get hello')8- router.add('POST', '/hello', 'post hello')9-10- it('get, post hello', async () => {11- let res = router.match('GET', '/hello')12- expect(res).not.toBeNull()13- expect(res?.handlers).toEqual(['get hello'])14-15- res = router.match('POST', '/hello')16- expect(res).not.toBeNull()17- expect(res?.handlers).toEqual(['post hello'])18-19- res = router.match('PUT', '/hello')20- expect(res).toBeNull()21-22- res = router.match('GET', '/')23- expect(res).toBeNull()24- })25-})26-27-describe('Complex', () => {28- let router: RegExpRouter<string>29- beforeEach(() => {30- router = new RegExpRouter<string>()31- })32-33- it('Named Param', async () => {34- router.add('GET', '/entry/:id', 'get entry')35- const res = router.match('GET', '/entry/123')36- expect(res).not.toBeNull()37- expect(res?.handlers).toEqual(['get entry'])38- expect(res?.params['id']).toBe('123')39- })40-41- it('Wildcard', async () => {42- router.add('GET', '/wild/*/card', 'get wildcard')43- const res = router.match('GET', '/wild/xxx/card')44- expect(res).not.toBeNull()45- expect(res?.handlers).toEqual(['get wildcard'])46- })47-48- it('Default', async () => {49- router.add('GET', '/api/abc', 'get api')50- router.add('GET', '/api/*', 'fallback')51- let res = router.match('GET', '/api/abc')52- expect(res).not.toBeNull()53- expect(res?.handlers).toEqual(['get api', 'fallback'])54- res = router.match('GET', '/api/def')55- expect(res).not.toBeNull()56- expect(res?.handlers).toEqual(['fallback'])57- })58-59- it('Regexp', async () => {60- router.add('GET', '/post/:date{[0-9]+}/:title{[a-z]+}', 'get post')61- let res = router.match('GET', '/post/20210101/hello')62- expect(res).not.toBeNull()63- expect(res?.handlers).toEqual(['get post'])64- expect(res?.params['date']).toBe('20210101')65- expect(res?.params['title']).toBe('hello')66- res = router.match('GET', '/post/onetwothree')67- expect(res).toBeNull()68- res = router.match('GET', '/post/123/123')69- expect(res).toBeNull()70- })71-72- it('/*', async () => {73- router.add('GET', '/api/*', 'auth middleware')74- router.add('GET', '/api', 'top')75- router.add('GET', '/api/posts', 'posts')76- router.add('GET', '/api/*', 'fallback')77-78- let res = router.match('GET', '/api')79- expect(res).not.toBeNull()80- expect(res?.handlers).toEqual(['auth middleware', 'top', 'fallback'])81-82- res = router.match('GET', '/api/posts')83- expect(res).not.toBeNull()84- expect(res?.handlers).toEqual(['auth middleware', 'posts', 'fallback'])85- })86-})87-88-describe('Registration order', () => {89- let router: RegExpRouter<string>90- beforeEach(() => {91- router = new RegExpRouter<string>()92- })93-94- it('abstract -> concrete', async () => {95- router.add('GET', '/:type/:action', 'foo')96- router.add('GET', '/posts/:id', 'bar')97- const res = router.match('GET', '/posts/123')98- expect(res).not.toBeNull()99- expect(res?.handlers).toEqual(['foo', 'bar'])100- })101-102- it('concrete -> abstract', async () => {103- router.add('GET', '/posts/:id', 'bar')104- router.add('GET', '/:type/:action', 'foo')105- const res = router.match('GET', '/posts/123')106- expect(res).not.toBeNull()107- expect(res?.handlers).toEqual(['bar', 'foo'])108- })109-110- it('middleware -> handler', async () => {111- router.add('GET', '*', 'bar')112- router.add('GET', '/:type/:action', 'foo')113- const res = router.match('GET', '/posts/123')114- expect(res).not.toBeNull()115- expect(res?.handlers).toEqual(['bar', 'foo'])116- })117-118- it('handler -> fallback', async () => {119- router.add('GET', '/:type/:action', 'foo')120- router.add('GET', '*', 'fallback')121- const res = router.match('GET', '/posts/123')122- expect(res).not.toBeNull()123- expect(res?.handlers).toEqual(['foo', 'fallback'])124- })125-})126-127-describe('Optimization for METHOD_NAME_OF_ALL', () => {128- let router: RegExpRouter<string>129- beforeEach(() => {130- router = new RegExpRouter<string>()131- })132-133- it('Apply to all requests', async () => {134- router.add(METHOD_NAME_ALL, '*', 'OK')135- const res = router.match('GET', '/entry/123')136- expect(res).not.toBeNull()137- expect(res?.handlers).toEqual(['OK'])138- expect(res?.params).toMatchObject({})139- })140-141- it('Apply to all requests under a specific path', async () => {142- router.add(METHOD_NAME_ALL, '/path/to/*', 'OK')143- let res = router.match('GET', '/entry/123')144- expect(res).toBeNull()145-146- res = router.match('GET', '/path/to/entry/123')147- expect(res).not.toBeNull()148- expect(res?.handlers).toEqual(['OK'])149- expect(res?.params).toMatchObject({})150- })151-})152-153-describe('Multi match', () => {154- describe('Blog', () => {155- const router = new RegExpRouter<string>()156-157- router.add('ALL', '*', 'middleware a')158- router.add('GET', '*', 'middleware b')159- router.add('GET', '/entry', 'get entries')160- router.add('POST', '/entry/*', 'middleware c')161- router.add('POST', '/entry', 'post entry')162- router.add('GET', '/entry/:id', 'get entry')163- router.add('GET', '/entry/:id/comment/:comment_id', 'get comment')164- it('GET /', async () => {165- const res = router.match('GET', '/')166- expect(res).not.toBeNull()167- expect(res?.handlers).toEqual(['middleware a', 'middleware b'])168- })169- it('GET /entry/123', async () => {170- const res = router.match('GET', '/entry/123')171- expect(res).not.toBeNull()172- expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get entry'])173- expect(res?.params['id']).toBe('123')174- })175- it('GET /entry/123/comment/456', async () => {176- const res = router.match('GET', '/entry/123/comment/456')177- expect(res).not.toBeNull()178- expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get comment'])179- expect(res?.params['id']).toBe('123')180- expect(res?.params['comment_id']).toBe('456')181- })182- it('POST /entry', async () => {183- const res = router.match('POST', '/entry')184- expect(res).not.toBeNull()185- expect(res?.handlers).toEqual(['middleware a', 'middleware c', 'post entry'])186- })187- it('DELETE /entry', async () => {188- const res = router.match('DELETE', '/entry')189- expect(res).not.toBeNull()190- expect(res?.handlers).toEqual(['middleware a'])191- })192- })193-194- describe('Ambiguous', () => {195- const router = new RegExpRouter<string>()196-197- router.add('GET', '/:user/entries', 'get user entries')198- router.add('GET', '/entry/:name', 'get entry')199- it('GET /entry/entry', async () => {200- const res = router.match('GET', '/entry/entries')201- expect(res).not.toBeNull()202- expect(res?.handlers).toEqual(['get user entries', 'get entry'])203- expect(res?.params['user']).toBe('entry')204- expect(res?.params['name']).toBe('entries')205- })206- })207-208- describe('Multiple handlers', () => {209- const router = new RegExpRouter<string>()210-211- router.add('GET', '/:type/:id', ':type')212- router.add('GET', '/:class/:id', ':class')213- router.add('GET', '/:model/:id', ':model')214- router.add('GET', '/entry/:id', 'entry')215-216- it('GET /entry/123', async () => {217- const res = router.match('GET', '/entry/123')218- expect(res).not.toBeNull()219- expect(res?.handlers).toEqual([':type', ':class', ':model', 'entry'])220- expect(res?.params['type']).toBe('entry')221- expect(res?.params['class']).toBe('entry')222- expect(res?.params['model']).toBe('entry')223- })224- })225-})226-227-describe('Check for duplicate parameter names', () => {228- it('self', () => {229- const router = new RegExpRouter<string>()230- router.add('GET', '/:id/:id', 'get')231- expect(() => {232- router.match('GET', '/') // check parameter names on the first `match` call233- }).toThrowError(/Duplicate param name/)234- })235-236- it('parent', () => {237- const router = new RegExpRouter<string>()238- router.add('GET', '/:id/:action', 'foo')239- router.add('GET', '/posts/:id', 'bar')240- expect(() => {241- router.match('GET', '/')242- }).toThrowError(/Duplicate param name/)243- })244-245- it('child', () => {246- const router = new RegExpRouter<string>()247- router.add('GET', '/posts/:id', 'foo')248- router.add('GET', '/:id/:action', 'bar')249-250- expect(() => {251- router.match('GET', '/')252- }).toThrowError(/Duplicate param name/)253- })254-255- it('hierarchy', () => {256- const router = new RegExpRouter<string>()257- router.add('GET', '/posts/:id/comments/:comment_id', 'foo')258- router.add('GET', '/posts/:id', 'bar')259- expect(() => {260- router.match('GET', '/')261- }).not.toThrow()262- })263-264- it('different regular expression', () => {265- const router = new RegExpRouter<string>()266- router.add('GET', '/:id/:action{create|update}', 'foo')267- router.add('GET', '/:id/:action{delete}', 'bar')268- expect(() => {269- router.match('GET', '/')270- }).not.toThrow()271- })272-})273-274-describe('star', () => {275- const router = new RegExpRouter<string>()276-277- router.add('GET', '/', '/')278- router.add('GET', '/*', '/*')279- router.add('GET', '*', '*')280-281- router.add('GET', '/x', '/x')282- router.add('GET', '/x/*', '/x/*')283-284- it('top', async () => {285- const res = router.match('GET', '/')286- expect(res).not.toBeNull()287- expect(res?.handlers).toEqual(['/', '/*', '*'])288- })289-290- it('Under a certain path', async () => {291- const res = router.match('GET', '/x')292- expect(res).not.toBeNull()293- expect(res?.handlers).toEqual(['/*', '*', '/x', '/x/*'])294- })295-})deleted:deno_dist/router/trie-router/node.test.ts-529 removed
1-import { Node } from './node.ts'2-3-describe('Root Node', () => {4- const node = new Node()5- node.insert('get', '/', 'get root')6- it('get /', () => {7- const res = node.search('get', '/')8- expect(res).not.toBeNull()9- expect(res?.handlers).toEqual(['get root'])10- expect(node.search('get', '/hello')).toBeNull()11- })12-})13-14-describe('Root Node is not defined', () => {15- const node = new Node()16- node.insert('get', '/hello', 'get hello')17- it('get /', () => {18- expect(node.search('get', '/')).toBeNull()19- })20-})21-22-describe('Get with *', () => {23- const node = new Node()24- node.insert('get', '*', 'get all')25- it('get /', () => {26- expect(node.search('get', '/')).not.toBeNull()27- expect(node.search('get', '/hello')).not.toBeNull()28- })29-})30-31-describe('Basic Usage', () => {32- const node = new Node()33- node.insert('get', '/hello', 'get hello')34- node.insert('post', '/hello', 'post hello')35- node.insert('get', '/hello/foo', 'get hello foo')36-37- it('get, post /hello', () => {38- expect(node.search('get', '/')).toBeNull()39- expect(node.search('post', '/')).toBeNull()40-41- expect(node.search('get', '/hello')?.handlers).toEqual(['get hello'])42- expect(node.search('post', '/hello')?.handlers).toEqual(['post hello'])43- expect(node.search('put', '/hello')).toBeNull()44- })45- it('get /nothing', () => {46- expect(node.search('get', '/nothing')).toBeNull()47- })48- it('/hello/foo, /hello/bar', () => {49- expect(node.search('get', '/hello/foo')?.handlers).toEqual(['get hello foo'])50- expect(node.search('post', '/hello/foo')).toBeNull()51- expect(node.search('get', '/hello/bar')).toBeNull()52- })53- it('/hello/foo/bar', () => {54- expect(node.search('get', '/hello/foo/bar')).toBeNull()55- })56-})57-58-describe('Name path', () => {59- const node = new Node()60- node.insert('get', '/entry/:id', 'get entry')61- node.insert('get', '/entry/:id/comment/:comment_id', 'get comment')62- node.insert('get', '/map/:location/events', 'get events')63-64- it('get /entry/123', () => {65- const res = node.search('get', '/entry/123')66- expect(res).not.toBeNull()67- expect(res?.handlers).toEqual(['get entry'])68- expect(res?.params).not.toBeNull()69- expect(res?.params['id']).toBe('123')70- expect(res?.params['id']).not.toBe('1234')71- })72-73- it('get /entry/456/comment', () => {74- const res = node.search('get', '/entry/456/comment')75- expect(res).toBeNull()76- })77-78- it('get /entry/789/comment/123', () => {79- const res = node.search('get', '/entry/789/comment/123')80- expect(res).not.toBeNull()81- expect(res?.handlers).toEqual(['get comment'])82- expect(res?.params['id']).toBe('789')83- expect(res?.params['comment_id']).toBe('123')84- })85-86- it('get /map/:location/events', () => {87- const res = node.search('get', '/map/yokohama/events')88- expect(res).not.toBeNull()89- expect(res?.handlers).toEqual(['get events'])90- expect(res?.params['location']).toBe('yokohama')91- })92-})93-94-describe('Name path - Multiple route', () => {95- const node = new Node()96-97- node.insert('get', '/:type/:id', 'common')98- node.insert('get', '/posts/:id', 'specialized')99-100- it('get /posts/123', () => {101- const res = node.search('get', '/posts/123')102- expect(res).not.toBeNull()103- expect(res?.handlers).toEqual(['common', 'specialized'])104- expect(res?.params['id']).toBe('123')105- })106-})107-108-describe('Wildcard', () => {109- const node = new Node()110- node.insert('get', '/wildcard-abc/*/wildcard-efg', 'wildcard')111- it('/wildcard-abc/xxxxxx/wildcard-efg', () => {112- const res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg')113- expect(res).not.toBeNull()114- expect(res?.handlers).toEqual(['wildcard'])115- })116- node.insert('get', '/wildcard-abc/*/wildcard-efg/hijk', 'wildcard')117- it('/wildcard-abc/xxxxxx/wildcard-efg/hijk', () => {118- const res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg/hijk')119- expect(res).not.toBeNull()120- expect(res?.handlers).toEqual(['wildcard'])121- })122-})123-124-describe('Regexp', () => {125- const node = new Node()126- node.insert('get', '/regex-abc/:id{[0-9]+}/comment/:comment_id{[a-z]+}', 'regexp')127- it('/regexp-abc/123/comment/abc', () => {128- const res = node.search('get', '/regex-abc/123/comment/abc')129- expect(res).not.toBeNull()130- expect(res?.handlers).toEqual(['regexp'])131- expect(res?.params['id']).toBe('123')132- expect(res?.params['comment_id']).toBe('abc')133- })134- it('/regexp-abc/abc', () => {135- const res = node.search('get', '/regex-abc/abc')136- expect(res).toBeNull()137- })138- it('/regexp-abc/123/comment/123', () => {139- const res = node.search('get', '/regex-abc/123/comment/123')140- expect(res).toBeNull()141- })142-})143-144-describe('All', () => {145- const node = new Node()146- node.insert('ALL', '/all-methods', 'all methods') // ALL147- it('/all-methods', () => {148- let res = node.search('get', '/all-methods')149- expect(res).not.toBeNull()150- expect(res?.handlers).toEqual(['all methods'])151- res = node.search('put', '/all-methods')152- expect(res).not.toBeNull()153- expect(res?.handlers).toEqual(['all methods'])154- })155-})156-157-describe('Special Wildcard', () => {158- const node = new Node()159- node.insert('ALL', '*', 'match all')160-161- it('/foo', () => {162- const res = node.search('get', '/foo')163- expect(res).not.toBeNull()164- expect(res?.handlers).toEqual(['match all'])165- })166- it('/hello', () => {167- const res = node.search('get', '/hello')168- expect(res).not.toBeNull()169- expect(res?.handlers).toEqual(['match all'])170- })171- it('/hello/foo', () => {172- const res = node.search('get', '/hello/foo')173- expect(res).not.toBeNull()174- expect(res?.handlers).toEqual(['match all'])175- })176-})177-178-describe('Special Wildcard deeply', () => {179- const node = new Node()180- node.insert('ALL', '/hello/*', 'match hello')181- it('/hello', () => {182- const res = node.search('get', '/hello')183- expect(res).not.toBeNull()184- expect(res?.handlers).toEqual(['match hello'])185- })186- it('/hello/foo', () => {187- const res = node.search('get', '/hello/foo')188- expect(res).not.toBeNull()189- expect(res?.handlers).toEqual(['match hello'])190- })191-})192-193-describe('Default with wildcard', () => {194- const node = new Node()195- node.insert('ALL', '/api/*', 'fallback')196- node.insert('ALL', '/api/abc', 'match api')197- it('/api/abc', () => {198- const res = node.search('get', '/api/abc')199- expect(res).not.toBeNull()200- expect(res?.handlers).toEqual(['fallback', 'match api'])201- })202- it('/api/def', () => {203- const res = node.search('get', '/api/def')204- expect(res).not.toBeNull()205- expect(res?.handlers).toEqual(['fallback'])206- })207-})208-209-describe('Multi match', () => {210- describe('Basic', () => {211- const node = new Node()212- node.insert('get', '*', 'GET *')213- node.insert('get', '/abc/*', 'GET /abc/*')214- node.insert('get', '/abc/*/edf', 'GET /abc/*/edf')215- node.insert('get', '/abc/edf', 'GET /abc/edf')216- node.insert('get', '/abc/*/ghi/jkl', 'GET /abc/*/ghi/jkl')217- it('get /abc/edf', () => {218- const res = node.search('get', '/abc/edf')219- expect(res).not.toBeNull()220- expect(res?.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/edf'])221- })222- it('get /abc/xxx/edf', () => {223- const res = node.search('get', '/abc/xxx/edf')224- expect(res).not.toBeNull()225- expect(res?.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/*/edf'])226- })227- it('get /', () => {228- const res = node.search('get', '/')229- expect(res).not.toBeNull()230- expect(res?.handlers).toEqual(['GET *'])231- })232- it('post /', () => {233- const res = node.search('post', '/')234- expect(res).toBeNull()235- })236- it('get /abc/edf/ghi', () => {237- const res = node.search('get', '/abc/edf/ghi')238- expect(res).not.toBeNull()239- expect(res?.handlers).toEqual(['GET *', 'GET /abc/*'])240- })241- })242-243- describe('Blog', () => {244- const node = new Node()245- node.insert('get', '*', 'middleware a') // 0.1246- node.insert('ALL', '*', 'middleware b') // 0.2 <===247- node.insert('get', '/entry', 'get entries') // 1.3248- node.insert('post', '/entry/*', 'middleware c') // 1.4 <===249- node.insert('post', '/entry', 'post entry') // 1.5 <===250- node.insert('get', '/entry/:id', 'get entry') // 2.6251- node.insert('get', '/entry/:id/comment/:comment_id', 'get comment') // 4.7252- it('get /entry/123', async () => {253- const res = node.search('get', '/entry/123')254- expect(res).not.toBeNull()255- expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get entry'])256- expect(res?.params['id']).toBe('123')257- })258- it('get /entry/123/comment/456', async () => {259- const res = node.search('get', '/entry/123/comment/456')260- expect(res).not.toBeNull()261- expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get comment'])262- expect(res?.params['id']).toBe('123')263- expect(res?.params['comment_id']).toBe('456')264- })265- it('post /entry', async () => {266- const res = node.search('post', '/entry')267- expect(res).not.toBeNull()268- expect(res?.handlers).toEqual(['middleware b', 'middleware c', 'post entry'])269- })270- it('delete /entry', async () => {271- const res = node.search('delete', '/entry')272- expect(res).not.toBeNull()273- expect(res?.handlers).toEqual(['middleware b'])274- })275- })276-277- describe('ALL', () => {278- const node = new Node()279- node.insert('ALL', '*', 'ALL *')280- node.insert('ALL', '/abc/*', 'ALL /abc/*')281- node.insert('ALL', '/abc/*/def', 'ALL /abc/*/def')282- it('get /', () => {283- const res = node.search('get', '/')284- expect(res).not.toBeNull()285- expect(res?.handlers).toEqual(['ALL *'])286- })287- it('post /abc', () => {288- const res = node.search('post', '/abc')289- expect(res).not.toBeNull()290- expect(res?.handlers).toEqual(['ALL *', 'ALL /abc/*'])291- })292- it('delete /abc/xxx/def', () => {293- const res = node.search('post', '/abc/xxx/def')294- expect(res).not.toBeNull()295- expect(res?.handlers).toEqual(['ALL *', 'ALL /abc/*', 'ALL /abc/*/def'])296- })297- })298-299- describe('Regexp', () => {300- const node = new Node()301- node.insert('get', '/regex-abc/:id{[0-9]+}/*', 'middleware a')302- node.insert('get', '/regex-abc/:id{[0-9]+}/def', 'regexp')303- it('/regexp-abc/123/def', () => {304- const res = node.search('get', '/regex-abc/123/def')305- expect(res).not.toBeNull()306- expect(res?.handlers).toEqual(['middleware a', 'regexp'])307- expect(res?.params['id']).toBe('123')308- })309- it('/regexp-abc/123', () => {310- const res = node.search('get', '/regex-abc/123/ghi')311- expect(res).not.toBeNull()312- expect(res?.handlers).toEqual(['middleware a'])313- })314- })315-316- describe('Trailing slash', () => {317- const node = new Node()318- node.insert('get', '/book', 'GET /book')319- node.insert('get', '/book/:id', 'GET /book/:id')320- it('get /book', () => {321- const res = node.search('get', '/book')322- expect(res).not.toBeNull()323- })324- it('get /book/', () => {325- const res = node.search('get', '/book/')326- expect(res).toBeNull()327- })328- })329-330- describe('Same path', () => {331- const node = new Node()332- node.insert('get', '/hey', 'Middleware A')333- node.insert('get', '/hey', 'Middleware B')334- it('get /hey', () => {335- const res = node.search('get', '/hey')336- expect(res).not.toBeNull()337- expect(res?.handlers).toEqual(['Middleware A', 'Middleware B'])338- })339- })340-})341-342-describe('Duplicate param name', () => {343- it('self', () => {344- const node = new Node()345- expect(() => {346- node.insert('get', '/:id/:id', 'foo')347- }).toThrowError(/Duplicate param name/)348- })349-350- it('parent', () => {351- const node = new Node()352- node.insert('get', '/:id/:action', 'foo')353- expect(() => {354- node.insert('get', '/posts/:id', 'bar')355- }).toThrowError(/Duplicate param name/)356- })357-358- it('child', () => {359- const node = new Node()360- node.insert('get', '/posts/:id', 'foo')361- expect(() => {362- node.insert('get', '/:id/:action', 'bar')363- }).toThrowError(/Duplicate param name/)364- })365-366- it('hierarchy', () => {367- const node = new Node()368- node.insert('get', '/posts/:id/comments/:comment_id', 'foo')369- expect(() => {370- node.insert('get', '/posts/:id', 'bar')371- }).not.toThrowError()372- })373-374- it('regular expression', () => {375- const node = new Node()376- node.insert('get', '/:id/:action{create|update}', 'foo')377- expect(() => {378- node.insert('get', '/:id/:action{delete}', 'bar')379- }).not.toThrowError()380- })381-})382-383-describe('Sort Order', () => {384- describe('Basic', () => {385- const node = new Node()386- node.insert('get', '*', 'a')387- node.insert('get', '/page', '/page')388- node.insert('get', '/:slug', '/:slug')389-390- it('get /page', () => {391- const res = node.search('get', '/page')392- expect(res).not.toBeNull()393- expect(res?.handlers).toEqual(['a', '/page', '/:slug'])394- })395- })396-397- describe('With Named path', () => {398- const node = new Node()399- node.insert('get', '*', 'a')400- node.insert('get', '/posts/:id', '/posts/:id')401- node.insert('get', '/:type/:id', '/:type/:id')402-403- it('get /posts/123', () => {404- const res = node.search('get', '/posts/123')405- expect(res).not.toBeNull()406- expect(res?.handlers).toEqual(['a', '/posts/:id', '/:type/:id'])407- })408- })409-410- describe('With Wildcards', () => {411- const node = new Node()412- node.insert('get', '/api/*', '1st')413- node.insert('get', '/api/*', '2nd')414- node.insert('get', '/api/posts/:id', '3rd')415- node.insert('get', '/api/*', '4th')416-417- it('get /api/posts/123', () => {418- const res = node.search('get', '/api/posts/123')419- expect(res).not.toBeNull()420- expect(res?.handlers).toEqual(['1st', '2nd', '3rd', '4th'])421- })422- })423-424- describe('With special Wildcard', () => {425- const node = new Node()426- node.insert('get', '/posts', '/posts') // 1.1427- node.insert('get', '/posts/*', '/posts/*') // 1.2428- node.insert('get', '/posts/:id', '/posts/:id') // 2.3429-430- it('get /posts', () => {431- const res = node.search('get', '/posts')432-433- expect(res).not.toBeNull()434- expect(res?.handlers).toEqual(['/posts', '/posts/*'])435- })436- })437-438- describe('Complex', () => {439- const node = new Node()440- node.insert('get', '/api', 'a') // not match441- node.insert('get', '/api/*', 'b') // match442- node.insert('get', '/api/:type', 'c') // not match443- node.insert('get', '/api/:type/:id', 'd') // match444- node.insert('get', '/api/posts/:id', 'e') // match445- node.insert('get', '/api/posts/123', 'f') // match446- node.insert('get', '/*/*/:id', 'g') // match447- node.insert('get', '/api/posts/*/comment', 'h') // not match448- node.insert('get', '*', 'i') // match449- node.insert('get', '*', 'j') // match450-451- it('get /api/posts/123', () => {452- const res = node.search('get', '/api/posts/123')453- expect(res?.handlers).toEqual(['b', 'd', 'e', 'f', 'g', 'i', 'j'])454- })455- })456-457- describe('Multi match', () => {458- const node = new Node()459- node.insert('get', '*', 'GET *') // 0.1460- node.insert('get', '/abc/*', 'GET /abc/*') // 1.2461- node.insert('get', '/abc/edf', 'GET /abc/edf') // 2.3462- node.insert('get', '/abc/*/ghi/jkl', 'GET /abc/*/ghi/jkl') // 4.4463- it('get /abc/edf', () => {464- const res = node.search('get', '/abc/edf')465- expect(res).not.toBeNull()466- expect(res?.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/edf'])467- })468- })469-470- describe('Multi match', () => {471- const node = new Node()472-473- node.insert('get', '/api/*', 'a') // 2.1 for /api/entry474- node.insert('get', '/api/entry', 'entry') // 2.2475- node.insert('ALL', '/api/*', 'b') // 2.3 for /api/entry476-477- it('get /api/entry', async () => {478- const res = node.search('get', '/api/entry')479- expect(res).not.toBeNull()480- expect(res?.handlers).toEqual(['a', 'entry', 'b'])481- })482- })483-484- describe('fallback', () => {485- describe('Blog - failed', () => {486- const node = new Node()487- node.insert('post', '/entry', 'post entry') // 1.1488- node.insert('post', '/entry/*', 'fallback') // 1.2489- node.insert('get', '/entry/:id', 'get entry') // 2.3490- it('post /entry', async () => {491- const res = node.search('post', '/entry')492- expect(res).not.toBeNull()493- expect(res?.handlers).toEqual(['post entry', 'fallback'])494- })495- })496- })497- describe('page', () => {498- const node = new Node()499- node.insert('get', '/page', 'page') // 1.1500- node.insert('ALL', '/*', 'fallback') // 1.2501- it('get /page', async () => {502- const res = node.search('get', '/page')503- expect(res).not.toBeNull()504- expect(res?.handlers).toEqual(['page', 'fallback'])505- })506- })507-})508-509-describe('star', () => {510- const node = new Node()511- node.insert('get', '/', '/')512- node.insert('get', '/*', '/*')513- node.insert('get', '*', '*')514-515- node.insert('get', '/x', '/x')516- node.insert('get', '/x/*', '/x/*')517-518- it('top', async () => {519- const res = node.search('get', '/')520- expect(res).not.toBeNull()521- expect(res?.handlers).toEqual(['/', '/*', '*']) // => failed ['*', '/*', '/']522- })523-524- it('Under a certain path', async () => {525- const res = node.search('get', '/x')526- expect(res).not.toBeNull()527- expect(res?.handlers).toEqual(['/*', '*', '/x', '/x/*'])528- })529-})deleted:deno_dist/router/trie-router/router.test.ts-131 removed
1-import { TrieRouter } from './router.ts'2-3-describe('Basic Usage', () => {4- const router = new TrieRouter<string>()5-6- router.add('GET', '/hello', 'get hello')7- router.add('POST', '/hello', 'post hello')8-9- it('get, post hello', async () => {10- let res = router.match('GET', '/hello')11- expect(res).not.toBeNull()12- expect(res?.handlers).toEqual(['get hello'])13-14- res = router.match('POST', '/hello')15- expect(res).not.toBeNull()16- expect(res?.handlers).toEqual(['post hello'])17-18- res = router.match('PUT', '/hello')19- expect(res).toBeNull()20-21- res = router.match('GET', '/')22- expect(res).toBeNull()23- })24-})25-26-describe('Complex', () => {27- const router = new TrieRouter<string>()28-29- it('Named Param', async () => {30- router.add('GET', '/entry/:id', 'get entry')31- const res = router.match('GET', '/entry/123')32- expect(res).not.toBeNull()33- expect(res?.handlers).toEqual(['get entry'])34- expect(res?.params['id']).toBe('123')35- })36-37- it('Wildcard', async () => {38- router.add('GET', '/wild/*/card', 'get wildcard')39- const res = router.match('GET', '/wild/xxx/card')40- expect(res).not.toBeNull()41- expect(res?.handlers).toEqual(['get wildcard'])42- })43-44- it('Default', async () => {45- router.add('GET', '/api/*', 'fallback')46- router.add('GET', '/api/abc', 'get api')47- let res = router.match('GET', '/api/abc')48- expect(res).not.toBeNull()49- expect(res?.handlers).toEqual(['fallback', 'get api'])50- res = router.match('GET', '/api/def')51- expect(res).not.toBeNull()52- expect(res?.handlers).toEqual(['fallback'])53- })54-55- it('Regexp', async () => {56- router.add('GET', '/post/:date{[0-9]+}/:title{[a-z]+}', 'get post')57- let res = router.match('GET', '/post/20210101/hello')58- expect(res).not.toBeNull()59- expect(res?.handlers).toEqual(['get post'])60- expect(res?.params['date']).toBe('20210101')61- expect(res?.params['title']).toBe('hello')62- res = router.match('GET', '/post/onetwothree')63- expect(res).toBeNull()64- res = router.match('GET', '/post/123/123')65- expect(res).toBeNull()66- })67-})68-69-describe('Multi match', () => {70- const router = new TrieRouter<string>()71-72- describe('Blog', () => {73- router.add('ALL', '*', 'middleware a')74- router.add('GET', '*', 'middleware b')75- router.add('GET', '/entry', 'get entries')76- router.add('POST', '/entry/*', 'middleware c')77- router.add('POST', '/entry', 'post entry')78- router.add('GET', '/entry/:id', 'get entry')79- router.add('GET', '/entry/:id/comment/:comment_id', 'get comment')80- it('GET /', async () => {81- const res = router.match('GET', '/')82- expect(res).not.toBeNull()83- expect(res?.handlers).toEqual(['middleware a', 'middleware b'])84- })85- it('GET /entry/123', async () => {86- const res = router.match('GET', '/entry/123')87- expect(res).not.toBeNull()88- expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get entry'])89- expect(res?.params['id']).toBe('123')90- })91- it('GET /entry/123/comment/456', async () => {92- const res = router.match('GET', '/entry/123/comment/456')93- expect(res).not.toBeNull()94- expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get comment'])95- expect(res?.params['id']).toBe('123')96- expect(res?.params['comment_id']).toBe('456')97- })98- it('POST /entry', async () => {99- const res = router.match('POST', '/entry')100- expect(res).not.toBeNull()101- expect(res?.handlers).toEqual(['middleware a', 'middleware c', 'post entry'])102- })103- it('DELETE /entry', async () => {104- const res = router.match('DELETE', '/entry')105- expect(res).not.toBeNull()106- expect(res?.handlers).toEqual(['middleware a'])107- })108- })109-})110-111-describe('Fallback', () => {112- const router = new TrieRouter<string>()113- router.add('POST', '/entry', 'post entry')114- router.add('POST', '/entry/*', 'fallback')115- router.add('GET', '/entry/:id', 'get entry')116- it('POST /entry', async () => {117- const res = router.match('POST', '/entry')118- expect(res).not.toBeNull()119- expect(res?.handlers).toEqual(['post entry', 'fallback'])120- })121-})122-123-describe('page', () => {124- const router = new TrieRouter<string>()125- router.add('GET', '/page', 'page')126- router.add('ALL', '*', 'fallback') // or '*'127- it('GET /page', async () => {128- const res = router.match('GET', '/page')129- expect(res?.handlers).toEqual(['page', 'fallback'])130- })131-})deleted:deno_dist/utils/jwt/jwt.test.ts-173 removed
1-/* eslint-disable @typescript-eslint/ban-ts-comment */2-import * as JWT from './jwt.ts'3-import {4- AlgorithmTypes,5- JwtTokenSignatureMismatched,6- JwtAlorithmNotImplemented,7- JwtTokenInvalid,8- JwtTokenNotBefore,9- JwtTokenExpired,10-} from './types.ts'11-12-describe('JWT', () => {13- it('JwtAlorithmNotImplemented', async () => {14- const payload = { message: 'hello world' }15- const secret = 'a-secret'16- const alg = ''17- let tok = ''18- let err: JwtAlorithmNotImplemented19- try {20- tok = await JWT.sign(payload, secret, alg as AlgorithmTypes)21- } catch (e) {22- err = e as JwtAlorithmNotImplemented23- }24- expect(tok).toBe('')25- // @ts-ignore26- expect(err).toEqual(new JwtAlorithmNotImplemented(alg))27- })28-29- it('JwtTokenInvalid', async () => {30- const tok = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ'31- const secret = 'a-secret'32- let err: JwtTokenInvalid33- let authorized = false34- try {35- authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)36- } catch (e) {37- err = e as JwtTokenInvalid38- }39- // @ts-ignore40- expect(err).toEqual(new JwtTokenInvalid(tok))41- expect(authorized).toBe(false)42- })43-44- it('JwtTokenNotBefore', async () => {45- const tok =46- 'eyJraWQiOiJFemF7bVZWbnd0TUpUNEFveFVtT0dILWJ0Y2VUVFM3djBYcEJuMm5ZZ2VjIiwiYWxnIjoiSFMyNTYifQ.eyJyb2xlIjoiYXBpX3JvbGUiLCJuYmYiOjE2NjQ1ODI0MDB9.BatadbUj5e41OZ33odEFTAndQFzX0w9aAgpQPgO-zaQ'47- const secret = 'a-secret'48- let err: JwtTokenNotBefore49- let authorized = false50- try {51- authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)52- } catch (e) {53- err = e as JwtTokenNotBefore54- }55- // @ts-ignore56- expect(err).toEqual(new JwtTokenNotBefore(tok))57- expect(authorized).toBe(false)58- })59-60- it('JwtTokenExpired', async () => {61- const tok =62- 'eyJraWQiOiJFemF6bVZWbnd0TUpUNEFveFVtT0dILWJ0Y2VUVFM3djBYcEJuMm5ZZ2VjIiwiYWxnIjoiSFMyNTYifQ.eyJyb2xlIjoiYXBpX3JvbGUiLCJleHAiOjE2MzMwNDY0MDB9.Gmq_dozOnwzqkMUMEm7uny7cMZuF1d0QkCnmRXAbTEk'63- const secret = 'a-secret'64- let err65- let authorized = false66- try {67- authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)68- } catch (e) {69- err = e70- }71- expect(err).toEqual(new JwtTokenExpired(tok))72- expect(authorized).toBe(false)73- })74-75- it('HS256 sign & verify & decode', async () => {76- const payload = { message: 'hello world' }77- const secret = 'a-secret'78- const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)79- const expected =80- 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'81- expect(tok).toEqual(expected)82-83- expect(await JWT.verify(tok, secret, AlgorithmTypes.HS256)).toBe(true)84-85- expect(JWT.decode(tok)).toEqual({86- header: {87- alg: 'HS256',88- typ: 'JWT',89- },90- payload: {91- message: 'hello world',92- },93- })94- })95-96- it('HS256 sign & verify', async () => {97- const payload = { message: 'hello world' }98- const secret = 'a-secret'99- const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)100- const expected =101- 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'102- expect(tok).toEqual(expected)103-104- let err = null105- let authorized = false106- try {107- authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)108- } catch (e) {109- err = e110- }111- expect(authorized).toBe(false)112- expect(err instanceof JwtTokenSignatureMismatched).toBe(true)113- })114-115- it('HS512 sign & verify & decode', async () => {116- const payload = { message: 'hello world' }117- const secret = 'a-secret'118- const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS512)119- const expected =120- 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.RqVLgExB_GXF1-9T-k4V4HjFmiuQKTEjVSiZd-YL0WERIlywZ7PfzAuTZSJU4gg8cscGamQa030cieEWrYcywg'121- expect(tok).toEqual(expected)122-123- expect(await JWT.verify(tok, secret, AlgorithmTypes.HS512)).toBe(true)124-125- expect(JWT.decode(tok)).toEqual({126- header: {127- alg: 'HS512',128- typ: 'JWT',129- },130- payload: {131- message: 'hello world',132- },133- })134- })135-136- it('HS512 sign & verify', async () => {137- const payload = { message: 'hello world' }138- const secret = 'a-secret'139- const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS512)140- const expected =141- 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.RqVLgExB_GXF1-9T-k4V4HjFmiuQKTEjVSiZd-YL0WERIlywZ7PfzAuTZSJU4gg8cscGamQa030cieEWrYcywg'142- expect(tok).toEqual(expected)143-144- let err = null145- let authorized = false146- try {147- authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)148- } catch (e) {149- err = e150- }151- expect(authorized).toBe(false)152- expect(err instanceof JwtTokenSignatureMismatched).toBe(true)153- })154-155- it('HS384 sign & verify', async () => {156- const payload = { message: 'hello world' }157- const secret = 'a-secret%你好'158- const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS384)159- const expected =160- 'eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.C1Br1183Oy6O7th4NDCOaI9WB75i3FMCuYlv1tCL9HggsU89T-SNutghwhJykD3r'161- expect(tok).toEqual(expected)162-163- let err = null164- let authorized = false165- try {166- authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)167- } catch (e) {168- err = e169- }170- expect(authorized).toBe(false)171- expect(err instanceof JwtTokenSignatureMismatched).toBe(true)172- })173-})deleted:deno_dist/utils/jwt/types.test.ts-13 removed
1-import { AlgorithmTypes } from './types.ts'2-3-describe('Types', () => {4- it('AlgorithmTypes', () => {5- expect('HS256' as AlgorithmTypes).toBe(AlgorithmTypes.HS256)6- expect('HS384' as AlgorithmTypes).toBe(AlgorithmTypes.HS384)7- expect('HS512' as AlgorithmTypes).toBe(AlgorithmTypes.HS512)8- // eslint-disable-next-line @typescript-eslint/ban-ts-comment9- // @ts-ignore10- expect(undefined as AlgorithmTypes).toBe(undefined)11- expect('' as AlgorithmTypes).toBe('')12- })13-})deleted:deno_dist/utils/body.test.ts-47 removed
1-import { parseBody } from './body.ts'2-3-describe('Parse Body Middleware', () => {4- it('should parse JSON', async () => {5- const payload = { message: 'hello hono' }6- const req = new Request('http://localhost/json', {7- method: 'POST',8- body: JSON.stringify(payload),9- headers: new Headers({ 'Content-Type': 'application/json' }),10- })11- expect(await parseBody(req)).toEqual(payload)12- })13-14- it('should parse Text', async () => {15- const payload = 'hello'16- const req = new Request('http://localhost/text', {17- method: 'POST',18- body: 'hello',19- headers: new Headers({ 'Content-Type': 'application/text' }),20- })21- expect(await parseBody(req)).toEqual(payload)22- })23-24- it('should parse Form', async () => {25- const formData = new URLSearchParams()26- formData.append('message', 'hello')27- const req = new Request('https://localhost/form', {28- method: 'POST',29- body: formData,30- headers: {31- 'Content-Type': 'application/x-www-form-urlencoded',32- },33- })34- expect(await parseBody(req)).toEqual({ message: 'hello' })35- })36-37- it('should parse Response body ', async () => {38- const payload = 'hello'39- const res = new Response(payload, {40- headers: {41- 'Content-Type': 'text/plain',42- },43- })44- console.log(res.headers.get('Content-Type'))45- expect(await parseBody(res)).toEqual(payload)46- })47-})deleted:deno_dist/utils/buffer.test.ts-55 removed
1-import { SHA256 as sha256CryptoJS } from 'crypto-js DENOIFY: DEPENDENCY UNMET (DEV DEPENDENCY)'2-import { timingSafeEqual, bufferToString } from './buffer.ts'3-4-describe('buffer', () => {5- it('positive', async () => {6- expect(7- await timingSafeEqual(8- '127e6fbfe24a750e72930c220a8e138275656b8e5d8f48a98c3c92df2caba935',9- '127e6fbfe24a750e72930c220a8e138275656b8e5d8f48a98c3c92df2caba935'10- )11- ).toBe(true)12- expect(await timingSafeEqual('a', 'a')).toBe(true)13- expect(await timingSafeEqual('', '')).toBe(true)14- // eslint-disable-next-line @typescript-eslint/ban-ts-comment15- // @ts-ignore16- expect(await timingSafeEqual(undefined, undefined)).toBe(true)17- expect(await timingSafeEqual(true, true)).toBe(true)18- expect(await timingSafeEqual(false, false)).toBe(true)19- expect(await timingSafeEqual(true, true, (d: string) => sha256CryptoJS(d).toString()))20- })21-22- it('negative', async () => {23- expect(await timingSafeEqual('a', 'b')).toBe(false)24- expect(25- await timingSafeEqual('a', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')26- ).toBe(false)27- expect(28- await timingSafeEqual('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'a')29- ).toBe(false)30- expect(await timingSafeEqual('alpha', 'beta')).toBe(false)31- expect(await timingSafeEqual(false, true)).toBe(false)32- // eslint-disable-next-line @typescript-eslint/ban-ts-comment33- // @ts-ignore34- expect(await timingSafeEqual(false, undefined)).toBe(false)35- expect(36- await timingSafeEqual(37- () => {},38- () => {}39- )40- ).toBe(false)41- expect(await timingSafeEqual({}, {})).toBe(false)42- expect(await timingSafeEqual({ a: 1 }, { a: 1 })).toBe(false)43- expect(await timingSafeEqual({ a: 1 }, { a: 2 })).toBe(false)44- expect(await timingSafeEqual([1, 2], [1, 2])).toBe(false)45- expect(await timingSafeEqual([1, 2], [1, 2, 3])).toBe(false)46- })47-})48-49-describe('bufferToString', () => {50- it('Should return あいうえお', () => {51- const bytes = [227, 129, 130, 227, 129, 132, 227, 129, 134, 227, 129, 136, 227, 129, 138]52- const buffer = Uint8Array.from(bytes).buffer53- expect(bufferToString(buffer)).toBe('あいうえお')54- })55-})deleted:deno_dist/utils/cloudflare.test.ts-49 removed
1-import { getContentFromKVAsset, getKVFilePath } from './cloudflare.ts'2-3-// Mock4-const store: { [key: string]: string } = {5- 'index.abcdef.html': 'This is index',6- 'assets/static/plain.abcdef.txt': 'Asset text',7-}8-const manifest = JSON.stringify({9- 'index.html': 'index.abcdef.html',10- 'assets/static/plain.txt': 'assets/static/plain.abcdef.txt',11-})12-13-Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })14-Object.assign(global, {15- __STATIC_CONTENT: {16- get: (path: string) => {17- return store[path]18- },19- },20-})21-22-describe('Utils for Cloudflare Workers', () => {23- it('getContentFromKVAsset', async () => {24- let content = await getContentFromKVAsset('not-found.txt')25- expect(content).toBeUndefined()26- content = await getContentFromKVAsset('index.html')27- expect(content).not.toBeUndefined()28- expect(content).toBe('This is index')29- content = await getContentFromKVAsset('assets/static/plain.txt')30- expect(content).not.toBeUndefined()31- expect(content).toBe('Asset text')32- })33-34- it('getKVFilePath', async () => {35- expect(getKVFilePath({ filename: 'foo' })).toBe('foo/index.html')36- expect(getKVFilePath({ filename: 'foo.txt' })).toBe('foo.txt')37-38- expect(getKVFilePath({ filename: 'foo', root: 'bar' })).toBe('bar/foo/index.html')39- expect(getKVFilePath({ filename: 'foo.txt', root: 'bar' })).toBe('bar/foo.txt')40-41- expect(getKVFilePath({ filename: 'foo', defaultDocument: 'index.txt' })).toBe('foo/index.txt')42- expect(getKVFilePath({ filename: 'foo', root: 'bar', defaultDocument: 'index.txt' })).toBe(43- 'bar/foo/index.txt'44- )45-46- expect(getKVFilePath({ filename: './foo' })).toBe('foo/index.html')47- expect(getKVFilePath({ filename: 'foo', root: './bar' })).toBe('bar/foo/index.html')48- })49-})deleted:deno_dist/utils/crypto.test.ts-25 removed
1-import { sha256, sha1, md5 } from './crypto.ts'2-3-describe('crypto', () => {4- it('sha256', async () => {5- expect(await sha256('hono')).toBe(6- '8b3dc17add91b7e8f0b5109a389927d66001139cd9b03fa7b95f83126e1b2b23'7- )8- expect(await sha256('炎')).toBe(9- '1fddc5a562ee1fbeb4fc6def7d4be4911fcdae4273b02ae3a507b170ba0ea169'10- )11- expect(await sha256('abcdedf')).not.toBe('abcdef')12- })13-14- it('sha1', async () => {15- expect(await sha1('hono')).toBe('28c7e86f5732391917876b45c06c626c04d77f39')16- expect(await sha1('炎')).toBe('d56e09ae2421b2b8a0b5ee5fdceaed663c8c9472')17- expect(await sha1('abcdedf')).not.toBe('abcdef')18- })19- 20- it('md5', async () => {21- expect(await md5('hono')).toBe('cf22a160789a91dd5f737cd3b2640cc2')22- expect(await md5('炎')).toBe('f620d89a5a782c22b4420acb39121be3')23- expect(await md5('abcdedf')).not.toBe('abcdef')24- })25-})deleted:deno_dist/utils/encode.test.ts-71 removed
1-/* eslint-disable @typescript-eslint/ban-ts-comment */2-import {3- utf8ToUint8Array,4- decodeBase64,5- encodeBase64,6- encodeBase64URL,7- decodeBase64URL,8-} from './encode.ts'9-10-describe('encode', () => {11- describe('base64', () => {12- it('encodeBase64', () => {13- expect(encodeBase64('hooooooooo')).toBe('aG9vb29vb29vbw==')14- expect(encodeBase64('炎')).toBe('54KO')15- expect(encodeBase64('abcdef')).not.toBe('abcdedf')16- expect(encodeBase64('')).toBe('')17- expect(() => {18- // @ts-ignore19- encodeBase64(null)20- }).toThrow(TypeError)21- })22-23- it('decodeBase64', async () => {24- expect(decodeBase64('aG9vb29vb29vbw==')).toBe('hooooooooo')25- expect(decodeBase64('54KO')).toBe('炎')26- expect(decodeBase64('abcdedf')).not.toBe('abcdef')27- expect(decodeBase64('')).toBe('')28- expect(() => {29- // @ts-ignore30- decodeBase64(null)31- }).toThrowError(TypeError)32- })33- })34- describe('base64url', () => {35- it('encodeBase64URL', () => {36- expect(encodeBase64URL('hooooooooo')).toBe('aG9vb29vb29vbw')37- expect(encodeBase64URL('http://github.com/honojs/hono')).toBe(38- 'aHR0cDovL2dpdGh1Yi5jb20vaG9ub2pzL2hvbm8'39- )40- expect(encodeBase64URL('炎')).toBe('54KO')41- expect(encodeBase64URL('abcdef')).not.toBe('abcdedf')42- expect(encodeBase64URL('')).toBe('')43- expect(() => {44- // @ts-ignore45- encodeBase64URL(null)46- }).toThrow(TypeError)47- })48-49- it('decodeBase64URL', async () => {50- expect(decodeBase64URL('aG9vb29vb29vbw')).toBe('hooooooooo')51- expect(decodeBase64URL('aHR0cDovL2dpdGh1Yi5jb20vaG9ub2pzL2hvbm8')).toBe(52- 'http://github.com/honojs/hono'53- )54- expect(decodeBase64URL('54KO')).toBe('炎')55- expect(decodeBase64URL('abcdedf')).not.toBe('abcdef')56- expect(decodeBase64URL('')).toBe('')57- expect(() => {58- // @ts-ignore59- decodeBase64URL(null)60- }).toThrowError(TypeError)61- })62- })63-64- describe('utf8ToUint8Array', () => {65- it('should be equal', () => {66- const k = 'a-secret-key'67- const arr = utf8ToUint8Array(k)68- expect(String(arr)).toEqual('97,45,115,101,99,114,101,116,45,107,101,121')69- })70- })71-})deleted:deno_dist/utils/html.test.ts-8 removed
1-import { escape } from './html.ts'2-3-describe('HTML escape', () => {4- it('Should escape special characters', () => {5- expect(escape('I <b>think</b> this is good.')).toBe('I <b>think</b> this is good.')6- expect(escape('John "Johnny" Smith')).toBe('John "Johnny" Smith')7- })8-})deleted:deno_dist/utils/http-status.test.ts-7 removed
1-import { getStatusText } from './http-status.ts'2-3-describe('http-status utility', () => {4- it('getStatusText', () => {5- expect(getStatusText(200)).toBe('OK')6- })7-})deleted:deno_dist/utils/mime.test.ts-12 removed
1-import { getMimeType } from './mime.ts'2-3-describe('mime', () => {4- it('getMimeType', () => {5- expect(getMimeType('hello.txt')).toBe('text/plain; charset=utf-8')6- expect(getMimeType('hello.html')).toBe('text/html; charset=utf-8')7- expect(getMimeType('hello.json')).toBe('application/json; charset=utf-8')8- expect(getMimeType('good.morning.hello.gif')).toBe('image/gif')9- expect(getMimeType('goodmorninghellogif')).toBeUndefined()10- expect(getMimeType('indexjs.abcd')).toBeUndefined()11- })12-})deleted:deno_dist/utils/url.test.ts-104 removed
1-import { splitPath, getPattern, getPathFromURL, isAbsoluteURL, mergePath } from './url.ts'2-3-describe('url', () => {4- it('splitPath', () => {5- let ps = splitPath('/')6- expect(ps).toStrictEqual([''])7-8- ps = splitPath('/hello')9- expect(ps).toStrictEqual(['hello'])10-11- ps = splitPath('*')12- expect(ps).toStrictEqual(['*'])13-14- ps = splitPath('/wildcard-abc/*/wildcard-efg')15- expect(ps).toStrictEqual(['wildcard-abc', '*', 'wildcard-efg'])16-17- ps = splitPath('/map/:location/events')18- expect(ps).toStrictEqual(['map', ':location', 'events'])19- })20-21- it('getPattern', () => {22- let res = getPattern(':id')23- expect(res).not.toBeNull()24- expect(res?.[0]).toBe(':id')25- expect(res?.[1]).toBe('id')26- expect(res?.[2]).toBe(true)27- res = getPattern(':id{[0-9]+}')28- expect(res?.[0]).toBe(':id{[0-9]+}')29- expect(res?.[1]).toBe('id')30- expect(res?.[2]).toEqual(/^[0-9]+$/)31- res = getPattern('*')32- expect(res).toBe('*')33- })34-35- describe('getPathFromURL', () => {36- it('getPathFromURL - no trailing slash', () => {37- let path = getPathFromURL('https://example.com/')38- expect(path).toBe('/')39- path = getPathFromURL('https://example.com/hello')40- expect(path).toBe('/hello')41- path = getPathFromURL('https://example.com/hello/hey')42- expect(path).toBe('/hello/hey')43- path = getPathFromURL('https://example.com/hello?name=foo')44- expect(path).toBe('/hello')45- path = getPathFromURL('https://example.com/hello/hey?name=foo&name=bar')46- expect(path).toBe('/hello/hey')47- })48-49- it('getPathFromURL - with trailing slash', () => {50- let path = getPathFromURL('https://example.com/hello/')51- expect(path).toBe('/hello/')52- path = getPathFromURL('https://example.com/hello/hey/')53- expect(path).toBe('/hello/hey/')54- })55-56- it('getPathFromURL - no strict is false', () => {57- let path = getPathFromURL('https://example.com/hello/', false)58- expect(path).toBe('/hello')59- path = getPathFromURL('https://example.com/hello/hey/', false)60- expect(path).toBe('/hello/hey')61- })62- })63-64- describe('isAbsoluteURL', () => {65- it('absolute url', () => {66- expect(isAbsoluteURL('https://example.com')).toBeTruthy()67- expect(isAbsoluteURL('https://example.com/xxx')).toBeTruthy()68- })69- it('relative url', () => {70- expect(isAbsoluteURL('/')).not.toBeTruthy()71- expect(isAbsoluteURL('/location')).not.toBeTruthy()72- expect(isAbsoluteURL('')).not.toBeTruthy()73- })74- })75-76- describe('mergePath', () => {77- it('mergePath', () => {78- expect(mergePath('/book', '/')).toBe('/book')79- expect(mergePath('/book/', '/')).toBe('/book/')80- expect(mergePath('/book', '/hey')).toBe('/book/hey')81- expect(mergePath('/book/', '/hey')).toBe('/book/hey')82- expect(mergePath('/book', '/hey/')).toBe('/book/hey/')83- expect(mergePath('/book/', '/hey/')).toBe('/book/hey/')84- expect(mergePath('/book', 'hey', 'say')).toBe('/book/hey/say')85- expect(mergePath('/book', '/hey/', '/say/')).toBe('/book/hey/say/')86- expect(mergePath('/book', '/hey/', '/say/', '/')).toBe('/book/hey/say/')87-88- expect(mergePath('book', '/')).toBe('/book')89- expect(mergePath('book/', '/')).toBe('/book/')90- expect(mergePath('book', '/hey')).toBe('/book/hey')91- expect(mergePath('book', 'hey')).toBe('/book/hey')92- expect(mergePath('book', 'hey/')).toBe('/book/hey/')93- })94- it('Should be `/book`', () => {95- expect(mergePath('/', 'book')).toBe('/book')96- })97- it('Should be `/book`', () => {98- expect(mergePath('/', '/book')).toBe('/book')99- })100- it('Should be `/`', () => {101- expect(mergePath('/', '/')).toBe('/')102- })103- })104-})deleted:deno_dist/compose.test.ts-676 removed
1-import { compose } from './compose.ts'2-import { Context } from './context.ts'3-import { extendRequestPrototype } from './request.ts'4-5-extendRequestPrototype()6-7-type C = {8- req: Record<string, string>9- res: Record<string, string>10-}11-12-describe('compose', () => {13- const middleware: Function[] = []14-15- const a = async (c: C, next: Function) => {16- c.req['log'] = 'log'17- await next()18- }19-20- const b = async (c: C, next: Function) => {21- await next()22- c.res['headers'] = 'custom-header'23- }24-25- const c = async (c: C, next: Function) => {26- c.req['xxx'] = 'yyy'27- await next()28- c.res['zzz'] = c.req['xxx']29- }30-31- const handler = async (c: C, next: Function) => {32- c.req['log'] = `${c.req.log} message`33- await next()34- c.res = { message: 'new response' }35- }36-37- middleware.push(a)38- middleware.push(b)39- middleware.push(c)40- middleware.push(handler)41-42- it('Request', async () => {43- const c: C = { req: {}, res: {} }44- const composed = compose<C>(middleware)45- const context = await composed(c)46- expect(context.req['log']).not.toBeNull()47- expect(context.req['log']).toBe('log message')48- expect(context.req['xxx']).toBe('yyy')49- })50- it('Response', async () => {51- const c: C = { req: {}, res: {} }52- const composed = compose<C>(middleware)53- const context = await composed(c)54- expect(context.res['headers']).not.toBeNull()55- expect(context.res['headers']).toBe('custom-header')56- expect(context.res['message']).toBe('new response')57- expect(context.res['zzz']).toBe('yyy')58- })59-})60-61-describe('Handler and middlewares', () => {62- const middleware: Function[] = []63-64- const req = new Request('http://localhost/')65- const c: Context = new Context(req)66-67- const mHandlerFoo = async (c: Context, next: Function) => {68- c.req.headers.append('x-header-foo', 'foo')69- await next()70- }71-72- const mHandlerBar = async (c: Context, next: Function) => {73- await next()74- c.header('x-header-bar', 'bar')75- }76-77- const handler = (c: Context) => {78- const foo = c.req.header('x-header-foo') || ''79- return c.text(foo)80- }81-82- middleware.push(mHandlerFoo)83- middleware.push(mHandlerBar)84- middleware.push(handler)85-86- it('Should return 200 Response', async () => {87- const composed = compose<Context>(middleware)88- const context = await composed(c)89- const res = context.res90- expect(res).not.toBeNull()91- expect(res.status).toBe(200)92- expect(await res.text()).toBe('foo')93- expect(res.headers.get('x-header-bar')).toBe('bar')94- })95-})96-97-describe('compose with Context - 200 success', () => {98- const middleware: Function[] = []99-100- const req = new Request('http://localhost/')101- const c: Context = new Context(req)102- const handler = (c: Context) => {103- return c.text('Hello')104- }105- const mHandler = async (_c: Context, next: Function) => {106- await next()107- }108-109- middleware.push(handler)110- middleware.push(mHandler)111-112- it('Should return 200 Response', async () => {113- const composed = compose<Context>(middleware)114- const context = await composed(c)115- expect(context.res).not.toBeNull()116- expect(context.res.status).toBe(200)117- expect(await context.res!.text()).toBe('Hello')118- })119-})120-121-describe('compose with Context - 404 not found', () => {122- const middleware: Function[] = []123-124- const req = new Request('http://localhost/')125- const c: Context = new Context(req)126- const onError = (_error: Error, c: Context) => {127- return c.text('onError', 500)128- }129- const onNotFound = (c: Context) => {130- return c.text('onNotFound', 404)131- }132- const mHandler = async (_c: Context, next: Function) => {133- await next()134- }135-136- middleware.push(mHandler)137-138- it('Should return 404 Response', async () => {139- const composed = compose<Context>(middleware, onError, onNotFound)140- const context = await composed(c)141- expect(context.res).not.toBeNull()142- expect(context.res.status).toBe(404)143- expect(await context.res.text()).toBe('onNotFound')144- expect(context.finalized).toBe(true)145- })146-})147-148-describe('compose with Context - 401 not authorized', () => {149- const middleware: Function[] = []150-151- const req = new Request('http://localhost/')152- const c: Context = new Context(req)153- const onError = (_error: Error, c: Context) => {154- return c.text('onError', 500)155- }156- const handler = (c: Context, _next: Function) => {157- return c.text('Hello')158- }159- const mHandler = async (c: Context, next: Function) => {160- await next()161- c.res = new Response('Not authorized', { status: 401 })162- }163-164- middleware.push(mHandler)165- middleware.push(handler)166-167- it('Should return 401 Response', async () => {168- const composed = compose<Context>(middleware, onError)169- const context = await composed(c)170- expect(context.res).not.toBeNull()171- expect(context.res.status).toBe(401)172- expect(await context.res.text()).toBe('Not authorized')173- expect(context.finalized).toBe(true)174- })175-})176-177-describe('compose with Context - next() below', () => {178- const middleware: Function[] = []179-180- const req = new Request('http://localhost/')181- const c: Context = new Context(req)182- const onError = (_error: Error, c: Context) => {183- return c.text('onError', 500)184- }185- const handler = (c: Context) => {186- const message = c.req.header('x-custom') || 'blank'187- return c.text(message)188- }189- const mHandler = async (c: Context, next: Function) => {190- c.req.headers.append('x-custom', 'foo')191- await next()192- }193-194- middleware.push(mHandler)195- middleware.push(handler)196-197- it('Should return 200 Response', async () => {198- const composed = compose<Context>(middleware, onError)199- const context = await composed(c)200- expect(context.res).not.toBeNull()201- expect(context.res.status).toBe(200)202- expect(await context.res.text()).toBe('foo')203- expect(context.finalized).toBe(true)204- })205-})206-207-describe('compose with Context - 500 error', () => {208- const middleware: Function[] = []209-210- const req = new Request('http://localhost/')211- const c: Context = new Context(req)212- const onError = (_error: Error, c: Context) => {213- return c.text('onError', 500)214- }215-216- it('Error on handler', async () => {217- const handler = () => {218- throw new Error()219- }220-221- const mHandler = async (_c: Context, next: Function) => {222- await next()223- }224-225- middleware.push(mHandler)226- middleware.push(handler)227-228- const composed = compose<Context>(middleware, onError)229- const context = await composed(c)230- expect(context.res).not.toBeNull()231- expect(context.res.status).toBe(500)232- expect(await context.res.text()).toBe('onError')233- expect(context.finalized).toBe(true)234- })235-236- it('Error on middleware', async () => {237- const handler = (c: Context) => {238- return c.text('OK')239- }240-241- const mHandler = async () => {242- throw new Error()243- }244-245- middleware.push(mHandler)246- middleware.push(handler)247-248- const composed = compose<Context>(middleware, onError)249- const context = await composed(c)250- expect(c.res).not.toBeNull()251- expect(c.res.status).toBe(500)252- expect(await context.res.text()).toBe('onError')253- expect(context.finalized).toBe(true)254- })255-256- it('Run all the middlewares', async () => {257- const ctx: C = { req: {}, res: {} }258- const stack: number[] = []259- const middlewares = [260- async (_ctx: C, next: Function) => {261- stack.push(0)262- await next()263- },264- async (_ctx: C, next: Function) => {265- stack.push(1)266- await next()267- },268- async (_ctx: C, next: Function) => {269- stack.push(2)270- await next()271- },272- ]273- const composed = compose(middlewares)274- await composed(ctx)275- expect(stack).toEqual([0, 1, 2])276- })277-})278-describe('compose with Context - not finalized', () => {279- const req = new Request('http://localhost/')280- const c: Context = new Context(req)281-282- const onError = (_error: Error, c: Context) => {283- return c.text('onError', 500)284- }285- const onNotFound = (c: Context) => {286- return c.text('onNotFound', 404)287- }288-289- it('Should not be finalized - lack `next()`', async () => {290- const middleware: Function[] = []291- const mHandler = async (_c: Context, next: Function) => {292- await next()293- }294- const mHandler2 = async () => {}295-296- middleware.push(mHandler)297- middleware.push(mHandler2)298- const composed = compose<Context>(middleware, onError, onNotFound)299- const context = await composed(c)300- expect(context.finalized).toBe(false)301- })302-303- it('Should not be finalized - lack `return Response`', async () => {304- const middleware2: Function[] = []305- const mHandler3 = async (_c: Context, next: Function) => {306- await next()307- }308- const handler = async () => {}309- middleware2.push(mHandler3)310- middleware2.push(handler)311-312- const composed = compose<Context>(middleware2, onError, onNotFound)313- const context = await composed(c)314- expect(context.finalized).toBe(false)315- })316-})317-318-describe('Compose', function () {319- function isPromise(x: any) {320- return x && typeof x.then === 'function'321- }322-323- it('should get executed order one by one', async () => {324- const arr: number[] = []325- const stack = []326- const called: boolean[] = []327-328- stack.push(async (_context: C, next: Function) => {329- called.push(true)330-331- arr.push(1)332- await next()333- arr.push(6)334- })335-336- stack.push(async (_context: C, next: Function) => {337- called.push(true)338-339- arr.push(2)340- await next()341- arr.push(5)342- })343-344- stack.push(async (_context: C, next: Function) => {345- called.push(true)346-347- arr.push(3)348- await next()349- arr.push(4)350- })351-352- await compose(stack)({})353- expect(called).toEqual([true, true, true])354- expect(arr).toEqual([1, 2, 3, 4, 5, 6])355- })356-357- it('should not get executed if previous next() not triggered', async () => {358- const arr: number[] = []359- const stack = []360- const called: boolean[] = []361-362- stack.push(async (_context: C, next: Function) => {363- called.push(true)364-365- arr.push(1)366- await next()367- arr.push(6)368- })369-370- stack.push(async () => {371- called.push(true)372- arr.push(2)373- })374-375- stack.push(async (_context: C, next: Function) => {376- called.push(true)377-378- arr.push(3)379- await next()380- arr.push(4)381- })382-383- await compose(stack)({})384- expect(called).toEqual([true, true])385- expect(arr).toEqual([1, 2, 6])386- })387-388- it('should be able to be called twice', () => {389- type C = {390- arr: number[]391- }392- const stack = []393-394- stack.push(async (context: C, next: Function) => {395- context.arr.push(1)396- await next()397- context.arr.push(6)398- })399-400- stack.push(async (context: C, next: Function) => {401- context.arr.push(2)402- await next()403- context.arr.push(5)404- })405-406- stack.push(async (context: C, next: Function) => {407- context.arr.push(3)408- await next()409- context.arr.push(4)410- })411-412- const fn = compose(stack)413- const ctx1 = { arr: [] as number[] }414- const ctx2 = { arr: [] as number[] }415- const out = [1, 2, 3, 4, 5, 6]416-417- return fn(ctx1)418- .then(() => {419- expect(out).toEqual(ctx1.arr)420- return fn(ctx2)421- })422- .then(() => {423- expect(out).toEqual(ctx2.arr)424- })425- })426-427- it('should create next functions that return a Promise', function () {428- const stack: any[] = []429- const arr: any[] = []430- for (let i = 0; i < 5; i++) {431- stack.push((_context: C, next: Function) => {432- arr.push(next())433- })434- }435-436- compose(stack)({})437-438- for (const next of arr) {439- expect(isPromise(next)).toBe(true)440- }441- })442-443- it('should work with 0 middleware', function () {444- return compose([])({})445- })446-447- it('should work when yielding at the end of the stack', async () => {448- const stack = []449- let called = false450-451- stack.push(async (_ctx: C, next: Function) => {452- await next()453- called = true454- })455-456- await compose(stack)({})457- expect(called).toBe(true)458- })459-460- it('should reject on errors in middleware', () => {461- const stack = []462-463- stack.push(() => {464- throw new Error()465- })466-467- return compose(stack)({}).then(468- () => {469- throw new Error('promise was not rejected')470- },471- (e) => {472- expect(e).toBeInstanceOf(Error)473- }474- )475- })476-477- it('should keep the context', () => {478- const ctx = {}479-480- const stack = []481-482- stack.push(async (ctx2: C, next: Function) => {483- await next()484- expect(ctx2).toEqual(ctx)485- })486-487- stack.push(async (ctx2: C, next: Function) => {488- await next()489- expect(ctx2).toEqual(ctx)490- })491-492- stack.push(async (ctx2: C, next: Function) => {493- await next()494- expect(ctx2).toEqual(ctx)495- })496-497- return compose(stack)(ctx)498- })499-500- it('should catch downstream errors', async () => {501- const arr: any[] = []502- const stack = []503-504- stack.push(async (_ctx: C, next: Function) => {505- arr.push(1)506- try {507- arr.push(6)508- await next()509- arr.push(7)510- } catch (err) {511- arr.push(2)512- }513- arr.push(3)514- })515-516- stack.push(async () => {517- arr.push(4)518- throw new Error()519- })520-521- await compose(stack)({})522- expect(arr).toEqual([1, 6, 4, 2, 3])523- })524-525- it('should compose w/ next', () => {526- let called = false527-528- return compose([])({}, async () => {529- called = true530- }).then(function () {531- expect(called).toBe(true)532- })533- })534-535- it('should handle errors in wrapped non-async functions', () => {536- const stack = []537-538- stack.push(function () {539- throw new Error()540- })541-542- return compose(stack)({}).then(543- () => {544- throw new Error('promise was not rejected')545- },546- (e) => {547- expect(e).toBeInstanceOf(Error)548- }549- )550- })551-552- // https://github.com/koajs/compose/pull/27#issuecomment-143109739553- it('should compose w/ other compositions', () => {554- const called: number[] = []555-556- return compose([557- compose([558- (_ctx: C, next: Function) => {559- called.push(1)560- return next()561- },562- (_ctx: C, next: Function) => {563- called.push(2)564- return next()565- },566- ]),567- (_ctx: C, next: Function) => {568- called.push(3)569- return next()570- },571- ])({}).then(() => expect(called).toEqual([1, 2, 3]))572- })573-574- it('should throw if next() is called multiple times', () => {575- return compose([576- async (_ctx: C, next: Function) => {577- await next()578- await next()579- },580- ])({}).then(581- () => {582- throw new Error('boom')583- },584- (err) => {585- expect(/multiple times/.test(err.message)).toBe(true)586- }587- )588- })589-590- it('should return a valid middleware', () => {591- let val = 0592- return compose([593- compose([594- (_ctx: C, next: Function) => {595- val++596- return next()597- },598- (_ctx: C, next: Function) => {599- val++600- return next()601- },602- ]),603- (_ctx: C, next: Function) => {604- val++605- return next()606- },607- ])({}).then(function () {608- expect(val).toEqual(3)609- })610- })611-612- it('should return last return value', async () => {613- type C = {614- val: number615- }616- const stack = []617-618- stack.push(async (ctx: C, next: Function) => {619- await next()620- expect(ctx.val).toEqual(2)621- ctx.val = 1622- })623-624- stack.push(async (ctx: C, next: Function) => {625- ctx.val = 2626- await next()627- expect(ctx.val).toEqual(2)628- })629-630- const res = await compose(stack)({ val: 0 })631- expect(res).toEqual({ val: 1 })632- })633-634- it('should not affect the original middleware array', () => {635- const middleware = []636- const fn1 = (_ctx: C, next: Function) => {637- return next()638- }639- middleware.push(fn1)640-641- for (const fn of middleware) {642- expect(fn).toEqual(fn1)643- }644-645- compose(middleware)646-647- for (const fn of middleware) {648- expect(fn).toEqual(fn1)649- }650- })651-652- it('should not get stuck on the passed in next', async () => {653- type C = {654- middleware: number655- next: number656- }657-658- const middleware = [659- (ctx: C, next: Function) => {660- ctx.middleware++661- return next()662- },663- ]664- const ctx = {665- middleware: 0,666- next: 0,667- }668-669- return compose(middleware)(ctx, (ctx: C, next: Function) => {670- ctx.next++671- return next()672- }).then(() => {673- expect(ctx).toEqual({ middleware: 1, next: 1 })674- })675- })676-})deleted:deno_dist/context.test.ts-145 removed
1-import { Context } from './context.ts'2-3-describe('Context', () => {4- const req = new Request('http://localhost/')5-6- let c: Context7- beforeEach(() => {8- c = new Context(req)9- })10-11- it('c.text()', async () => {12- const res = c.text('text in c', 201, { 'X-Custom': 'Message' })13- expect(res.status).toBe(201)14- expect(res.headers.get('Content-Type')).toBe('text/plain; charset=UTF-8')15- expect(await res.text()).toBe('text in c')16- expect(res.headers.get('X-Custom')).toBe('Message')17- })18-19- it('c.json()', async () => {20- const res = c.json({ message: 'Hello' }, 201, { 'X-Custom': 'Message' })21- expect(res.status).toBe(201)22- expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')23- const text = await res.text()24- expect(text).toBe('{"message":"Hello"}')25- expect(res.headers.get('X-Custom')).toBe('Message')26- })27-28- it('c.json() with c.pretty(true)', async () => {29- c.pretty(true)30- const res = c.json({ message: 'Hello' })31- const text = await res.text()32- expect(text).toBe(`{33- "message": "Hello"34-}`)35- })36-37- it('c.json() with c.pretty(true, 4)', async () => {38- c.pretty(true, 4)39- const res = c.json({ message: 'Hello' })40- const text = await res.text()41- expect(text).toBe(`{42- "message": "Hello"43-}`)44- })45-46- it('c.html()', async () => {47- const res = c.html('<h1>Hello! Hono!</h1>', 201, { 'X-Custom': 'Message' })48- expect(res.status).toBe(201)49- expect(res.headers.get('Content-Type')).toMatch('text/html')50- expect(await res.text()).toBe('<h1>Hello! Hono!</h1>')51- expect(res.headers.get('X-Custom')).toBe('Message')52- })53-54- it('c.redirect()', async () => {55- let res = c.redirect('/destination')56- expect(res.status).toBe(302)57- expect(res.headers.get('Location')).toMatch(/^https?:\/\/.+\/destination$/)58- res = c.redirect('https://example.com/destination')59- expect(res.status).toBe(302)60- expect(res.headers.get('Location')).toBe('https://example.com/destination')61- })62-63- it('c.header()', async () => {64- c.header('X-Foo', 'Bar')65- const res = c.body('Hi')66- const foo = res.headers.get('X-Foo')67- expect(foo).toBe('Bar')68- })69-70- it('c.status()', async () => {71- c.status(201)72- const res = c.body('Hi')73- expect(res.status).toBe(201)74- })75-76- it('Complex pattern', async () => {77- c.status(404)78- const res = c.json({ hono: 'great app' })79- expect(res.status).toBe(404)80- expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')81- const obj: { [key: string]: string } = await res.json()82- expect(obj['hono']).toBe('great app')83- })84-85- it('Has headers and status', async () => {86- c.header('x-custom1', 'Message1')87- c.header('x-custom2', 'Message2')88- c.status(200)89- const res = c.newResponse('this is body', 201, {90- 'x-custom3': 'Message3',91- 'x-custom2': 'Message2-Override',92- })93- expect(res.headers.get('x-Custom1')).toBe('Message1')94- expect(res.headers.get('x-Custom2')).toBe('Message2-Override')95- expect(res.headers.get('x-Custom3')).toBe('Message3')96- expect(res.status).toBe(201)97- expect(await res.text()).toBe('this is body')98-99- // res is already set.100- c.res = res101- c.header('X-Custom4', 'Message4')102- c.status(202)103- expect(c.res.headers.get('X-Custom4')).toBe('Message4')104- expect(c.res.status).toBe(201)105- })106-107- it('Should return 200 response', async () => {108- const res = c.text('Text')109- expect(res.status).toBe(200)110- })111-112- it('Should return 204 response', async () => {113- c.status(204)114- const res = c.body(null)115- expect(res.status).toBe(204)116- expect(await res.text()).toBe('')117- })118-119- it('Should be able read env', async () => {120- const req = new Request('http://localhost/')121- const key = 'a-secret-key'122- const ctx = new Context(req, {123- API_KEY: key,124- })125- expect(ctx.env.API_KEY).toBe(key)126- })127-128- it('set and set', async () => {129- const ctx = new Context(req)130- expect(ctx.get('k-foo')).toEqual(undefined)131- ctx.set('k-foo', 'v-foo')132- expect(ctx.get('k-foo')).toEqual('v-foo')133- expect(ctx.get('k-bar')).toEqual(undefined)134- ctx.set('k-bar', { k: 'v' })135- expect(ctx.get('k-bar')).toEqual({ k: 'v' })136- })137-138- it('has res object by default', async () => {139- c = new Context(req)140- c.res.headers.append('foo', 'bar')141- const res = c.text('foo')142- expect(res.headers.get('foo')).not.toBeNull()143- expect(res.headers.get('foo')).toBe('bar')144- })145-})deleted:deno_dist/hono.test.ts-876 removed
1-import type { Context } from './context.ts'2-import type { Next } from './hono.ts'3-import { Hono } from './hono.ts'4-import { poweredBy } from './middleware/powered-by/index.ts'5-6-describe('GET Request', () => {7- const app = new Hono()8-9- app.get('/hello', async () => {10- return new Response('hello', {11- status: 200,12- statusText: 'Hono is OK',13- })14- })15-16- app.get('/hello-with-shortcuts', (c) => {17- c.header('X-Custom', 'This is Hono')18- c.status(201)19- return c.html('<h1>Hono!!!</h1>')20- })21-22- it('GET /hello is ok', async () => {23- const res = await app.request('http://localhost/hello')24- expect(res).not.toBeNull()25- expect(res.status).toBe(200)26- expect(res.statusText).toBe('Hono is OK')27- expect(await res.text()).toBe('hello')28- })29-30- it('GET /hello-with-shortcuts is ok', async () => {31- const res = await app.request('http://localhost/hello-with-shortcuts')32- expect(res).not.toBeNull()33- expect(res.status).toBe(201)34- expect(res.headers.get('X-Custom')).toBe('This is Hono')35- expect(res.headers.get('Content-Type')).toMatch(/text\/html/)36- expect(await res.text()).toBe('<h1>Hono!!!</h1>')37- })38-39- it('GET / is not found', async () => {40- const res = await app.request('http://localhost/')41- expect(res).not.toBeNull()42- expect(res.status).toBe(404)43- })44-})45-46-describe('strict parameter', () => {47- describe('strict is true with not slash', () => {48- const app = new Hono()49-50- app.get('/hello', (c) => {51- return c.text('/hello')52- })53-54- it('/hello/ is not found', async () => {55- let res = await app.request('http://localhost/hello')56- expect(res).not.toBeNull()57- expect(res.status).toBe(200)58- res = await app.request('http://localhost/hello/')59- expect(res).not.toBeNull()60- expect(res.status).toBe(404)61- })62- })63-64- describe('strict is true with slash', () => {65- const app = new Hono()66-67- app.get('/hello/', (c) => {68- return c.text('/hello/')69- })70-71- it('/hello is not found', async () => {72- let res = await app.request('http://localhost/hello/')73- expect(res).not.toBeNull()74- expect(res.status).toBe(200)75- res = await app.request('http://localhost/hello')76- expect(res).not.toBeNull()77- expect(res.status).toBe(404)78- })79- })80-81- describe('strict is false', () => {82- const app = new Hono({ strict: false })83-84- app.get('/hello', (c) => {85- return c.text('/hello')86- })87-88- it('/hello and /hello/ are treated as the same', async () => {89- let res = await app.request('http://localhost/hello')90- expect(res).not.toBeNull()91- expect(res.status).toBe(200)92- res = await app.request('http://localhost/hello/')93- expect(res).not.toBeNull()94- expect(res.status).toBe(200)95- })96- })97-})98-99-describe('Routing', () => {100- const app = new Hono()101-102- it('Return it self', async () => {103- const app2 = app.get('/', () => new Response('get /'))104- expect(app2).not.toBeUndefined()105- app2.delete('/', () => new Response('delete /'))106-107- let res = await app2.request('http://localhost/', { method: 'GET' })108- expect(res).not.toBeNull()109- expect(res.status).toBe(200)110- expect(await res.text()).toBe('get /')111-112- res = await app2.request('http://localhost/', { method: 'DELETE' })113- expect(res).not.toBeNull()114- expect(res.status).toBe(200)115- expect(await res.text()).toBe('delete /')116- })117-118- it('Nested route', async () => {119- const book = app.route('/book')120- book.get('/', (c) => c.text('get /book'))121- book.get('/:id', (c) => {122- return c.text('get /book/' + c.req.param('id'))123- })124- book.post('/', (c) => c.text('post /book'))125-126- const user = app.route('/user')127- user.get('/login', (c) => c.text('get /user/login'))128- user.post('/register', (c) => c.text('post /user/register'))129-130- let res = await app.request('http://localhost/book', { method: 'GET' })131- expect(res.status).toBe(200)132- expect(await res.text()).toBe('get /book')133-134- res = await app.request('http://localhost/book/123', { method: 'GET' })135- expect(res.status).toBe(200)136- expect(await res.text()).toBe('get /book/123')137-138- res = await app.request('http://localhost/book', { method: 'POST' })139- expect(res.status).toBe(200)140- expect(await res.text()).toBe('post /book')141-142- res = await app.request('http://localhost/book/', { method: 'GET' })143- expect(res.status).toBe(404)144-145- res = await app.request('http://localhost/user/login', { method: 'GET' })146- expect(res.status).toBe(200)147- expect(await res.text()).toBe('get /user/login')148-149- res = await app.request('http://localhost/user/register', { method: 'POST' })150- expect(res.status).toBe(200)151- expect(await res.text()).toBe('post /user/register')152- })153-154- describe('Chained route', () => {155- app156- .get('/chained/:abc', (c) => {157- const abc = c.req.param('abc')158- return c.text(`GET for ${abc}`)159- })160- .post((c) => {161- const abc = c.req.param('abc')162- return c.text(`POST for ${abc}`)163- })164- it('Should return 200 response from GET request', async () => {165- const res = await app.request('http://localhost/chained/abc', { method: 'GET' })166- expect(res.status).toBe(200)167- expect(await res.text()).toBe('GET for abc')168- })169- it('Should return 200 response from POST request', async () => {170- const res = await app.request('http://localhost/chained/abc', { method: 'POST' })171- expect(res.status).toBe(200)172- expect(await res.text()).toBe('POST for abc')173- })174- it('Should return 404 response from PUT request', async () => {175- const res = await app.request('http://localhost/chained/abc', { method: 'PUT' })176- expect(res.status).toBe(404)177- })178- })179-})180-181-describe('param and query', () => {182- const apps: Record<string, Hono> = {}183- apps['get by name'] = (() => {184- const app = new Hono()185-186- app.get('/entry/:id', (c) => {187- const id = c.req.param('id')188- return c.text(`id is ${id}`)189- })190-191- app.get('/date/:date{[0-9]+}', (c) => {192- const date = c.req.param('date')193- return c.text(`date is ${date}`)194- })195-196- app.get('/search', (c) => {197- const name = c.req.query('name')198- return c.text(`name is ${name}`)199- })200-201- app.get('/multiple-values', (c) => {202- const queries = c.req.queries('q')203- const limit = c.req.queries('limit')204- return c.text(`q is ${queries[0]} and ${queries[1]}, limit is ${limit[0]}`)205- })206-207- app.get('/add-header', (c) => {208- const bar = c.req.header('X-Foo')209- return c.text(`foo is ${bar}`)210- })211-212- return app213- })()214-215- apps['get all as an object'] = (() => {216- const app = new Hono()217-218- app.get('/entry/:id', (c) => {219- const { id } = c.req.param()220- return c.text(`id is ${id}`)221- })222-223- app.get('/date/:date{[0-9]+}', (c) => {224- const { date } = c.req.param()225- return c.text(`date is ${date}`)226- })227-228- app.get('/search', (c) => {229- const { name } = c.req.query()230- return c.text(`name is ${name}`)231- })232-233- app.get('/multiple-values', (c) => {234- const { q, limit } = c.req.queries()235- return c.text(`q is ${q[0]} and ${q[1]}, limit is ${limit[0]}`)236- })237-238- app.get('/add-header', (c) => {239- const { 'x-foo': bar } = c.req.header()240- return c.text(`foo is ${bar}`)241- })242-243- return app244- })()245-246- describe.each(Object.keys(apps))('%s', (name) => {247- const app = apps[name]248-249- it('param of /entry/:id is found', async () => {250- const res = await app.request('http://localhost/entry/123')251- expect(res.status).toBe(200)252- expect(await res.text()).toBe('id is 123')253- })254-255- it('param of /date/:date is found', async () => {256- const res = await app.request('http://localhost/date/0401')257- expect(res.status).toBe(200)258- expect(await res.text()).toBe('date is 0401')259- })260-261- it('query of /search?name=sam is found', async () => {262- const res = await app.request('http://localhost/search?name=sam')263- expect(res.status).toBe(200)264- expect(await res.text()).toBe('name is sam')265- })266-267- it('query of /search?name=sam&name=tom is found', async () => {268- const res = await app.request('http://localhost/search?name=sam&name=tom')269- expect(res.status).toBe(200)270- expect(await res.text()).toBe('name is sam')271- })272-273- it('query of /multiple-values?q=foo&q=bar&limit=10 is found', async () => {274- const res = await app.request('http://localhost/multiple-values?q=foo&q=bar&limit=10')275- expect(res.status).toBe(200)276- expect(await res.text()).toBe('q is foo and bar, limit is 10')277- })278-279- it('/add-header header - X-Foo is Bar', async () => {280- const req = new Request('http://localhost/add-header')281- req.headers.append('X-Foo', 'Bar')282- const res = await app.request(req)283- expect(res.status).toBe(200)284- expect(await res.text()).toBe('foo is Bar')285- })286- })287-})288-289-describe('Middleware', () => {290- describe('Basic', () => {291- const app = new Hono()292-293- // Custom Logger294- app.use('*', async (c, next) => {295- console.log(`${c.req.method} : ${c.req.url}`)296- await next()297- })298-299- // Append Custom Header300- app.use('*', async (c, next) => {301- await next()302- c.res.headers.append('x-custom', 'root')303- })304-305- app.use('/hello', async (c, next) => {306- await next()307- c.res.headers.append('x-message', 'custom-header')308- })309-310- app.use('/hello/*', async (c, next) => {311- await next()312- c.res.headers.append('x-message-2', 'custom-header-2')313- })314-315- app.get('/hello', (c) => {316- return c.text('hello')317- })318-319- app.get('/hello/:message', (c) => {320- const message = c.req.param('message')321- return c.text(`${message}`)322- })323-324- app.get('/error', () => {325- throw new Error('Error!')326- })327-328- app.notFound((c) => {329- return c.text('Not Found Foo', 404)330- })331-332- it('logging and custom header', async () => {333- const res = await app.request('http://localhost/hello')334- expect(res.status).toBe(200)335- expect(await res.text()).toBe('hello')336- expect(res.headers.get('x-custom')).toBe('root')337- expect(res.headers.get('x-message')).toBe('custom-header')338- expect(res.headers.get('x-message-2')).toBe('custom-header-2')339- })340-341- it('logging and custom header with named param', async () => {342- const res = await app.request('http://localhost/hello/message')343- expect(res.status).toBe(200)344- expect(await res.text()).toBe('message')345- expect(res.headers.get('x-custom')).toBe('root')346- expect(res.headers.get('x-message-2')).toBe('custom-header-2')347- })348-349- it('not found', async () => {350- const res = await app.request('http://localhost/foo')351- expect(res.status).toBe(404)352- expect(await res.text()).toBe('Not Found Foo')353- })354-355- it('internal server error', async () => {356- const res = await app.request('http://localhost/error')357- expect(res.status).toBe(500)358- console.log(await res.text())359- })360- })361-362- describe('Chained route', () => {363- const app = new Hono()364- app365- .use('/chained/*', async (c, next) => {366- c.req.headers.append('x-before', 'abc')367- await next()368- })369- .use(async (c, next) => {370- await next()371- c.header('x-after', c.req.header('x-before'))372- })373- .get('/chained/abc', (c) => {374- return c.text('GET chained')375- })376- it('GET /chained/abc', async () => {377- const res = await app.request('http://localhost/chained/abc')378- expect(res.status).toBe(200)379- expect(await res.text()).toBe('GET chained')380- expect(res.headers.get('x-after')).toBe('abc')381- })382- })383-384- describe('Multiple handler', () => {385- const app = new Hono()386- app387- .use(388- '/multiple/*',389- async (c, next) => {390- c.req.headers.append('x-before', 'abc')391- await next()392- },393- async (c, next) => {394- await next()395- c.header('x-after', c.req.header('x-before'))396- }397- )398- .get('/multiple/abc', (c) => {399- return c.text('GET multiple')400- })401- it('GET /multiple/abc', async () => {402- const res = await app.request('http://localhost/multiple/abc')403- expect(res.status).toBe(200)404- expect(await res.text()).toBe('GET multiple')405- expect(res.headers.get('x-after')).toBe('abc')406- })407- })408-})409-410-describe('Builtin Middleware', () => {411- const app = new Hono()412- app.use('/abc', poweredBy())413- app.use('/def', async (c, next) => {414- const middleware = poweredBy()415- await middleware(c, next)416- })417- app.get('/abc', () => new Response())418- app.get('/def', () => new Response())419-420- it('"powered-by" middleware', async () => {421- const res = await app.request('http://localhost/abc')422- expect(res.headers.get('x-powered-by')).toBe('Hono')423- })424-425- it('"powered-by" middleware in a handler', async () => {426- const res = await app.request('http://localhost/def')427- expect(res.headers.get('x-powered-by')).toBe('Hono')428- })429-})430-431-describe('Middleware with app.HTTP_METHOD', () => {432- describe('Basic', () => {433- const app = new Hono()434-435- app.all('*', async (c, next) => {436- c.header('x-before-dispatch', 'foo')437- await next()438- c.header('x-custom-message', 'hello')439- })440-441- const customHeader = async (c: Context, next: Next) => {442- c.req.headers.append('x-custom-foo', 'bar')443- await next()444- }445-446- const customHeader2 = async (c: Context, next: Next) => {447- await next()448- c.header('x-custom-foo-2', 'bar-2')449- }450-451- app452- .get('/abc', customHeader, (c) => {453- const foo = c.req.header('x-custom-foo') || ''454- return c.text(foo)455- })456- .post(customHeader2, (c) => {457- return c.text('POST /abc')458- })459-460- it('GET /abc', async () => {461- const res = await app.request('http://localhost/abc')462- expect(res.status).toBe(200)463- expect(res.headers.get('x-custom-message')).toBe('hello')464- expect(res.headers.get('x-before-dispatch')).toBe('foo')465- expect(await res.text()).toBe('bar')466- })467- it('POST /abc', async () => {468- const res = await app.request('http://localhost/abc', { method: 'POST' })469- expect(res.status).toBe(200)470- expect(await res.text()).toBe('POST /abc')471- expect(res.headers.get('x-custom-foo-2')).toBe('bar-2')472- })473- })474-475- describe('With builtin middleware', () => {476- const app = new Hono()477- app.get('/abc', poweredBy(), (c) => {478- return c.text('GET /abc')479- })480- it('GET /abc', async () => {481- const res = await app.request('http://localhost/abc')482- expect(res.status).toBe(200)483- expect(await res.text()).toBe('GET /abc')484- expect(res.headers.get('x-powered-by')).toBe('Hono')485- })486- })487-})488-489-describe('Not Found', () => {490- const app = new Hono()491-492- app.notFound((c) => {493- return c.text('Custom 404 Not Found', 404)494- })495-496- app.get('/hello', (c) => {497- return c.text('hello')498- })499-500- app.get('/notfound', (c) => {501- return c.notFound()502- })503-504- it('Custom 404 Not Found', async () => {505- let res = await app.request('http://localhost/hello')506- expect(res.status).toBe(200)507- res = await app.request('http://localhost/notfound')508- expect(res.status).toBe(404)509- res = await app.request('http://localhost/foo')510- expect(res.status).toBe(404)511- expect(await res.text()).toBe('Custom 404 Not Found')512- })513-})514-515-describe('Redirect', () => {516- const app = new Hono()517- app.get('/redirect', (c) => {518- return c.redirect('/')519- })520-521- it('Absolute URL', async () => {522- const res = await app.request('https://example.com/redirect')523- expect(res.status).toBe(302)524- expect(res.headers.get('Location')).toBe('https://example.com/')525- })526-})527-528-describe('Error handle', () => {529- const app = new Hono()530-531- app.get('/error', () => {532- throw new Error('This is Error')533- })534-535- app.use('/error-middleware', async () => {536- throw new Error('This is Middleware Error')537- })538-539- app.onError((err, c) => {540- c.header('x-debug', err.message)541- return c.text('Custom Error Message', 500)542- })543-544- it('Custom Error Message', async () => {545- let res = await app.request('https://example.com/error')546- expect(res.status).toBe(500)547- expect(await res.text()).toBe('Custom Error Message')548- expect(res.headers.get('x-debug')).toBe('This is Error')549-550- res = await app.request('https://example.com/error-middleware')551- expect(res.status).toBe(500)552- expect(await res.text()).toBe('Custom Error Message')553- expect(res.headers.get('x-debug')).toBe('This is Middleware Error')554- })555-})556-557-describe('Request methods with custom middleware', () => {558- const app = new Hono()559-560- app.use('*', async (c, next) => {561- const query = c.req.query('foo')562- const param = c.req.param('foo')563- const header = c.req.header('User-Agent')564- await next()565- c.header('X-Query-2', query)566- c.header('X-Param-2', param)567- c.header('X-Header-2', header)568- })569-570- app.get('/:foo', (c) => {571- const query = c.req.query('foo')572- const param = c.req.param('foo')573- const header = c.req.header('User-Agent')574- c.header('X-Query', query)575- c.header('X-Param', param)576- c.header('X-Header', header)577- return c.body('Hono')578- })579-580- it('query', async () => {581- const url = new URL('http://localhost/bar')582- url.searchParams.append('foo', 'bar')583- const req = new Request(url.toString())584- req.headers.append('User-Agent', 'bar')585- const res = await app.request(req)586-587- expect(res.status).toBe(200)588- expect(res.headers.get('X-Query')).toBe('bar')589- expect(res.headers.get('X-Param')).toBe('bar')590- expect(res.headers.get('X-Header')).toBe('bar')591-592- expect(res.headers.get('X-Query-2')).toBe('bar')593- expect(res.headers.get('X-Param-2')).toBe('bar')594- expect(res.headers.get('X-Header-2')).toBe('bar')595- })596-})597-598-describe('Hono with `app.route`', () => {599- describe('Basic', () => {600- const app = new Hono()601- const api = new Hono()602- const middleware = new Hono()603-604- api.use('*', async (c, next) => {605- await next()606- c.res.headers.append('x-custom-a', 'a')607- })608-609- api.get('/posts', (c) => c.text('List'))610- api.post('/posts', (c) => c.text('Create'))611- api.get('/posts/:id', (c) => c.text(`GET ${c.req.param('id')}`))612-613- middleware.use('*', async (c, next) => {614- await next()615- c.res.headers.append('x-custom-b', 'b')616- })617-618- app.route('/api', middleware)619- app.route('/api', api)620-621- app.get('/foo', (c) => c.text('bar'))622-623- it('Should return not found response', async () => {624- const res = await app.request('http://localhost/')625- expect(res.status).toBe(404)626- })627-628- it('Should return not found response', async () => {629- const res = await app.request('http://localhost/posts')630- expect(res.status).toBe(404)631- })632-633- test('GET /api/posts', async () => {634- const res = await app.request('http://localhost/api/posts')635- expect(res.status).toBe(200)636- expect(await res.text()).toBe('List')637- })638-639- test('Custom header by middleware', async () => {640- const res = await app.request('http://localhost/api/posts')641- expect(res.status).toBe(200)642- expect(res.headers.get('x-custom-a')).toBe('a')643- expect(res.headers.get('x-custom-b')).toBe('b')644- })645-646- test('POST /api/posts', async () => {647- const res = await app.request('http://localhost/api/posts', { method: 'POST' })648- expect(res.status).toBe(200)649- expect(await res.text()).toBe('Create')650- })651-652- test('GET /api/posts/123', async () => {653- const res = await app.request('http://localhost/api/posts/123')654- expect(res.status).toBe(200)655- expect(await res.text()).toBe('GET 123')656- })657-658- test('GET /foo', async () => {659- const res = await app.request('http://localhost/foo')660- expect(res.status).toBe(200)661- expect(await res.text()).toBe('bar')662- })663- })664-665- describe('Chaining', () => {666- const app = new Hono()667- const route = new Hono()668- route.get('/post', (c) => c.text('GET /POST v2')).post((c) => c.text('POST /POST v2'))669- app.route('/v2', route)670-671- it('Should return 200 response - GET /v2/post', async () => {672- const res = await app.request('http://localhost/v2/post')673- expect(res.status).toBe(200)674- expect(await res.text()).toBe('GET /POST v2')675- })676-677- it('Should return 200 response - POST /v2/post', async () => {678- const res = await app.request('http://localhost/v2/post', { method: 'POST' })679- expect(res.status).toBe(200)680- expect(await res.text()).toBe('POST /POST v2')681- })682-683- it('Should return 404 response - DELETE /v2/post', async () => {684- const res = await app.request('http://localhost/v2/post', { method: 'DELETE' })685- expect(res.status).toBe(404)686- })687- })688-689- describe('Nested', () => {690- const app = new Hono()691- const api = new Hono()692- const book = new Hono()693-694- book.get('/', (c) => c.text('list books'))695- book.get('/:id', (c) => c.text(`book ${c.req.param('id')}`))696-697- api.get('/', (c) => c.text('this is API'))698- api.route('/book', book)699-700- app.get('/', (c) => c.text('root'))701- app.route('/v2', api)702-703- it('Should return 200 response - GET /', async () => {704- const res = await app.request('http://localhost/')705- expect(res.status).toBe(200)706- expect(await res.text()).toBe('root')707- })708-709- it('Should return 200 response - GET /v2', async () => {710- const res = await app.request('http://localhost/v2')711- expect(res.status).toBe(200)712- expect(await res.text()).toBe('this is API')713- })714-715- it('Should return 200 response - GET /v2/book', async () => {716- const res = await app.request('http://localhost/v2/book')717- expect(res.status).toBe(200)718- expect(await res.text()).toBe('list books')719- })720-721- it('Should return 200 response - GET /v2/book/123', async () => {722- const res = await app.request('http://localhost/v2/book/123')723- expect(res.status).toBe(200)724- expect(await res.text()).toBe('book 123')725- })726- })727-})728-729-describe('Multiple handler', () => {730- describe('handler + handler', () => {731- const app = new Hono()732-733- app.get('/posts/:id', (c) => {734- const id = c.req.param('id')735- c.header('foo', 'bar')736- return c.text(`id is ${id}`)737- })738-739- app.get('/:type/:id', (c) => {740- c.status(404)741- c.header('foo2', 'bar2')742- return c.text('foo')743- })744- it('Should return response from `specialized` route', async () => {745- const res = await app.request('http://localhost/posts/123')746- expect(res.status).toBe(200)747- expect(await res.text()).toBe('id is 123')748- expect(res.headers.get('foo')).toBe('bar')749- expect(res.headers.get('foo2')).toBeNull()750- })751- })752-753- describe('Duplicate param name', () => {754- it('self', () => {755- const app = new Hono()756- expect(() => {757- app.get('/:id/:id', (c) => {758- const id = c.req.param('id')759- return c.text(`id is ${id}`)760- })761- }).toThrowError(/Duplicate param name/)762- })763-764- it('parent', () => {765- const app = new Hono()766- app.get('/:id/:action', (c) => {767- return c.text('foo')768- })769- expect(() => {770- app.get('/posts/:id', (c) => {771- const id = c.req.param('id')772- return c.text(`id is ${id}`)773- })774- }).toThrowError(/Duplicate param name/)775- })776-777- it('child', () => {778- const app = new Hono()779- app.get('/posts/:id', (c) => {780- return c.text('foo')781- })782- expect(() => {783- app.get('/:id/:action', (c) => {784- const id = c.req.param('id')785- return c.text(`id is ${id}`)786- })787- }).toThrowError(/Duplicate param name/)788- })789-790- it('hierarchy', () => {791- const app = new Hono()792- app.get('/posts/:id/comments/:comment_id', (c) => {793- return c.text('foo')794- })795- expect(() => {796- app.get('/posts/:id', (c) => {797- const id = c.req.param('id')798- return c.text(`id is ${id}`)799- })800- }).not.toThrow()801- })802-803- it('different regular expression', () => {804- const app = new Hono()805- app.get('/:id/:action{create|update}', (c) => {806- return c.text('foo')807- })808- expect(() => {809- app.get('/:id/:action{delete}', (c) => {810- const id = c.req.param('id')811- return c.text(`id is ${id}`)812- })813- }).not.toThrow()814- })815- })816-})817-818-describe('Multiple handler - async', () => {819- describe('handler + handler', () => {820- const app = new Hono()821- app.get('/posts/:id', async (c) => {822- await new Promise((resolve) => setTimeout(resolve, 1))823- c.header('foo2', 'bar2')824- const id = c.req.param('id')825- return c.text(`id is ${id}`)826- })827- app.get('/:type/:id', async (c) => {828- await new Promise((resolve) => setTimeout(resolve, 1))829- c.header('foo', 'bar')830- c.status(404)831- return c.text('foo')832- })833-834- it('Should return response from `specialized` route', async () => {835- const res = await app.request('http://localhost/posts/123')836- expect(res.status).toBe(200)837- expect(await res.text()).toBe('id is 123')838- expect(res.headers.get('foo')).toBeNull()839- expect(res.headers.get('foo2')).toBe('bar2')840- })841- })842-})843-844-describe('Context is not finalized', () => {845- it('should throw error - lack `await next()`', async () => {846- const app = new Hono()847- // eslint-disable-next-line @typescript-eslint/ban-ts-comment848- // @ts-ignore849- app.use('*', () => {})850- app.get('/foo', (c) => {851- return c.text('foo')852- })853- app.onError((err, c) => {854- return c.text(err.message, 500)855- })856- const res = await app.request('http://localhost/foo')857- expect(res.status).toBe(500)858- expect(await res.text()).toMatch(/^Context is not finalized/)859- })860-861- it('should throw error - lack `returning Response`', async () => {862- const app = new Hono()863- app.use('*', async (_c, next) => {864- await next()865- })866- // eslint-disable-next-line @typescript-eslint/ban-ts-comment867- // @ts-ignore868- app.get('/foo', () => {})869- app.onError((err, c) => {870- return c.text(err.message, 500)871- })872- const res = await app.request('http://localhost/foo')873- expect(res.status).toBe(500)874- expect(await res.text()).toMatch(/^Context is not finalized/)875- })876-})modified:deno_dist/README.md+4 added-4 removed
11 unmodified lines12 [](https://www.npmjs.com/package/hono)13 [](https://www.npmjs.com/package/hono)14 [](https://github.com/honojs/hono/pulse)15 [](https://github.com/honojs/hono/commits/master)16+[](https://doc.deno.land/https/deno.land/x/hono/mod.ts)17 17-Hono - _**[炎] means flame🔥 in Japanese**_ - is a small, simple, and ultrafast web framework for Cloudflare Workers or Service Worker based serverless such as Fastly Compute@Edge.18+Hono - _**[炎] means flame🔥 in Japanese**_ - is a small, simple, and ultrafast web framework for Cloudflare Workers, Deno, and others.19 20 ```ts21 import { Hono } from 'hono'22 const app = new Hono()8 unmodified lines31 - **Ultrafast** - the router does not use linear loops.32 - **Zero-dependencies** - using only Service Worker and Web Standard API.33 - **Middleware** - built-in middleware and ability to extend with your own middleware.34 - **TypeScript** - first-class TypeScript support.34-- **Optimized** - for Cloudflare Workers.35-- **Deno** - support for Deno (Experimental).35+- **Multi-platform** - works on Cloudflare Workers, Fastly Compute@Edge, or Deno.36 37 ## Benchmarks38 39 ### Cloudflare Workers731 unmodified lines771 app.get(772 '/auth/*',773 basicAuth({774 username: 'deno',775- password: 'isacool',775+ password: 'iscool',776 })777 )778 779 app.get('/', (c) => {40 unmodified linesmodified:package.json+2 added-2 removed
9 unmodified lines10 "scripts": {11 "test": "jest",12 "lint": "eslint --ext js,ts src .eslintrc.js",13 "lint:fix": "eslint --ext js,ts src .eslintrc.js --fix",14- "denoify": "rimraf deno_dist && denoify",14+ "denoify": "rimraf deno_dist && denoify && rimraf 'deno_dist/**/*.test.ts'",15 "build": "rimraf dist && tsc --project tsconfig.build.esm.json && tsc --project tsconfig.build.json",16 "watch": "tsc --project tsconfig.build.json -w",17 "prerelease": "yarn denoify && yarn build",18 "release": "np"143 unmodified lines162 },163 "engines": {164 "node": ">=11.0.0"165 }166-}166+}