dsh-sansheng-liubu/sansheng/test/route.test.js

77 lines
2.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import assert from 'node:assert/strict'
import test from 'node:test'
import { installRoute } from '../src/route.js'
function fakeCtx(web) {
return {
get: (name, fallback) => (name === 'webServer' ? web : fallback),
effect: fn => fn(),
}
}
function fakeStore() {
return {
peek: () => ({ version: 2, projects: {}, reviews: [], dispatches: [], reworks: [], events: [] }),
unknownDispatches: () => [],
dispatchesFor: () => [],
reviewsFor: () => [],
}
}
function fakeRes() {
const headers = {}
return {
statusCode: 0,
headers,
body: '',
setHeader(name, value) { headers[name.toLowerCase()] = value },
end(body) { this.body = body ?? '' },
}
}
test('注册 GET /sansheng/state 并返回 JSON', async () => {
const routes = []
const web = { register: options => { routes.push(options); return () => {} } }
installRoute({ ctx: fakeCtx(web), store: fakeStore(), dsbot: { botOf: () => undefined, roomOf: () => undefined } })
assert.equal(routes.length, 1)
assert.equal(routes[0].kind, 'exact')
assert.equal(routes[0].path, '/sansheng/state')
const res = fakeRes()
await routes[0].handler({ method: 'GET' }, res)
assert.equal(res.statusCode, 200)
assert.match(res.headers['content-type'], /application\/json/)
assert.equal(res.headers['cache-control'], 'no-store')
assert.deepEqual(JSON.parse(res.body).projects, [])
})
test('非 GET 请求返回 405', async () => {
const routes = []
const web = { register: options => { routes.push(options); return () => {} } }
installRoute({ ctx: fakeCtx(web), store: fakeStore(), dsbot: { botOf: () => undefined, roomOf: () => undefined } })
const res = fakeRes()
await routes[0].handler({ method: 'POST' }, res)
assert.equal(res.statusCode, 405)
})
test('状态读取抛错时返回 500,而不是击穿宿主', async () => {
const routes = []
const web = { register: options => { routes.push(options); return () => {} } }
const broken = {
peek: () => { throw new Error('磁盘坏了') },
unknownDispatches: () => [],
dispatchesFor: () => [],
reviewsFor: () => [],
}
installRoute({ ctx: fakeCtx(web), store: broken, dsbot: { botOf: () => undefined, roomOf: () => undefined } })
const res = fakeRes()
await routes[0].handler({ method: 'GET' }, res)
assert.equal(res.statusCode, 500)
assert.match(JSON.parse(res.body).error, /磁盘坏了/)
})
test('宿主没有 webServer 时安静跳过,不抛错', () => {
const ctx = { get: (name, fallback) => fallback, effect: fn => fn() }
assert.doesNotThrow(() => installRoute({ ctx, store: fakeStore(), dsbot: {} }))
})