Files
dacli/tests/unit/defhttp_shim_envelope.test.ts
sushub f403a7e80e import: ssw/dacli@eea0ebc (2026-08-12) 起点版本
本仓 2026-08-12 从 ssw main (192.168.1.18:13300/ssw/ssw-mvp) 的
dacli/ subpath 抽取,作为独立仓托管到 gitea:3000/ssw/dacli.git。

- 工作树为 ssw main dacli subpath 最新版 (110 commit, 08-12)
- 历史未带 ssw main 整体历史(避免大仓污染)
- 此为新仓基线 commit,未来以本仓历史为主
2026-08-12 15:58:06 +08:00

296 lines
12 KiB
TypeScript

/**
* defhttp_shim_envelope.test.ts — _defhttp_shim.unwrap + parseJson 信封处理单测
*
* 目的: 验证 webapi/_defhttp_shim.ts 的 unwrap() 和 core/client.ts 的 parseJson() 在
* 各种 HTTP / 信封 / 非信封场景下抛出**有诊断价值**的错误, 而不是
* 当前 "API code=undefined: " 这种无语义信息 (大屏 D0720 实测踩坑 2026-07-20).
*
* 8 类场景:
* 1. JNPF 信封 200 + code=200 → 返回 unwrapped data
* 2. JNPF 信封 200 + code=400 → throw 含 code + msg (现状保留)
* 3. JNPF 信封 200 + data=null → 返回 stub (B-1 修复保留)
* 4. HTTP 5xx + Spring Boot 错误 JSON → throw 含 HTTP status + path + error
* 5. HTTP 502 + HTML 错误页 → throw 含 HTTP status + body 摘要
* 6. HTTP 200 + 非 JNPF 信封 JSON ({foo:"bar"}) → throw "non-Jnpf envelope"
* 7. HTTP 200 + 部分 JNPF 信封 (缺 code) → throw "non-Jnpf envelope"
* 8. fetch 网络错误 (fetch throws) → 透传 throw (保持)
*
* 触发模式: vi.stubGlobal('fetch', stub) 拦截实际请求, stub 返回的 Response.text()
* 是手写 JSON / HTML / 错误字符串, 模拟上游真实异常.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { JnpfClient } from '../../src/core/client.ts'
import { initDefHttpShim, defHttp } from '../../src/webapi/_defhttp_shim.ts'
interface CapturedCall {
url: string
method: string
body: unknown
headers: Record<string, string>
}
let lastCall: CapturedCall | null = null
let stubbed: ReturnType<typeof vi.fn> | null = null
// 用 mock 客户端 initDefHttpShim (不实际去打 JNPF)
function makeClient(): JnpfClient {
const c = new JnpfClient({
baseUrl: 'http://127.0.0.1:30000/api',
appCode: 'jxcj',
account: 'admin',
password: 'x',
})
c.token = 'mock-token-xxx'
return c
}
// 用 vi.fn 替换 fetch, 每次 stub 行为的 httpStatus / body
function installFetchStub(httpStatus: number, bodyText: string, headers?: Record<string, string>): ReturnType<typeof vi.fn> {
return vi.fn(async (url: string, init?: RequestInit) => {
const method = init?.method || 'GET'
let body: unknown = null
if (typeof init?.body === 'string') {
try { body = JSON.parse(init.body) } catch { body = init.body }
}
const capturedHeaders: Record<string, string> = {}
if (init?.headers) {
for (const [k, v] of Object.entries(init.headers as Record<string, string>)) capturedHeaders[k] = v
}
lastCall = { url, method, body, headers: capturedHeaders }
const respHeaders: Record<string, string> = {}
if (headers) {
if (headers instanceof Headers) {
headers.forEach((v, k) => (respHeaders[k] = v))
} else if (Array.isArray(headers)) {
for (const [k, v] of headers) respHeaders[k] = String(v)
} else {
Object.assign(respHeaders, headers as Record<string, string>)
}
}
return {
status: httpStatus,
ok: httpStatus >= 200 && httpStatus < 300,
text: async () => bodyText,
headers: new Headers(respHeaders),
json: async () => JSON.parse(bodyText),
} as unknown as Response
})
}
beforeEach(() => {
lastCall = null
initDefHttpShim(makeClient())
})
afterEach(() => {
vi.unstubAllGlobals()
})
// ----------------------------------------------------------------------------
// 场景 1: JNPF 信封 200, code=200 → 返回 unwrapped data
// ----------------------------------------------------------------------------
describe('场景 1: 正常 JNPF 信封 200', () => {
it('POST 拿到 {code:200, msg, data} → 返回 data (unwrapped)', async () => {
stubbed = installFetchStub(200, JSON.stringify({ code: 200, msg: 'ok', data: { id: '99' } }))
vi.stubGlobal('fetch', stubbed)
const result = await defHttp.post<{ id: string }>({
url: '/api/blade-visual/visual/save',
data: { visual: { title: 'foo' } },
})
// unwrap 返回 unwrapped data, 不是 envelope (B-1 stub 仅用于 data=null 场景)
expect(result).toEqual({ id: '99' })
})
it('GET 拿到 {code:200, msg, data:[]} → 返回 data 数组', async () => {
stubbed = installFetchStub(200, JSON.stringify({ code: 200, msg: 'ok', data: [1, 2, 3] }))
vi.stubGlobal('fetch', stubbed)
const result = await defHttp.get({ url: '/api/blade-visual/visual/list' })
expect(Array.isArray(result)).toBe(true)
})
})
// ----------------------------------------------------------------------------
// 场景 2: JNPF 信封 200, code != 200 → throw 含 code + msg (现状保留)
// ----------------------------------------------------------------------------
describe('场景 2: JNPF 信封业务错 (code != 200)', () => {
it('POST {code:400, msg:"EXIST002/编码不能重复"} → throw 含 code + msg', async () => {
stubbed = installFetchStub(200, JSON.stringify({ code: 400, msg: 'EXIST002 编码不能重复', data: null }))
vi.stubGlobal('fetch', stubbed)
await expect(
defHttp.post({ url: '/api/system/DictionaryType', data: { enCode: 'x' } })
).rejects.toThrow(/API code=400.*EXIST002 编码不能重复/)
})
it('POST {code:600, msg:"Login expired"} → throw 含 code=600', async () => {
stubbed = installFetchStub(200, JSON.stringify({ code: 600, msg: 'Login expired', data: null }))
vi.stubGlobal('fetch', stubbed)
await expect(
defHttp.post({ url: '/api/oauth/CurrentUser', data: {} })
).rejects.toThrow(/API code=600.*Login expired/)
})
})
// ----------------------------------------------------------------------------
// 场景 3: JNPF 信封 200 + data=null → 返 B-1 stub (现状保留)
// ----------------------------------------------------------------------------
describe('场景 3: JNPF 信封 data=null (B-1 已修)', () => {
it('POST {code:200, msg:"New created successfully", data:null} → 返 stub 不 throw', async () => {
stubbed = installFetchStub(200, JSON.stringify({ code: 200, msg: 'New created successfully', data: null }))
vi.stubGlobal('fetch', stubbed)
// 不应 throw, 应返回 stub {code:200, msg, id:undefined}
const result = await defHttp.post({ url: '/api/system/DictionaryType', data: {} })
expect(result).toEqual({ code: 200, msg: 'New created successfully', id: undefined })
})
})
// ----------------------------------------------------------------------------
// 场景 4 [P2 改进目标]: HTTP 5xx + Spring Boot 错误 JSON
// - 现在的 bug: 返回 "API code=undefined: "
// - 改进期望: throw 含 HTTP 503 + path + error
// ----------------------------------------------------------------------------
describe('场景 4: HTTP 5xx + Spring Boot 错误 JSON [BS-新\datascreen]', () => {
it('POST /api/blade-visual/visual/save 返 500 + Spring Boot JSON → throw 含 HTTP 500 + path + error', async () => {
const springBootErr = JSON.stringify({
timestamp: 1784554759213,
status: 500,
error: 'Internal Server Error',
message: '',
path: '/api/blade-visual/visual/save',
})
stubbed = installFetchStub(500, springBootErr, { 'Content-Type': 'application/json' })
vi.stubGlobal('fetch', stubbed)
await expect(
defHttp.post({ url: '/api/blade-visual/visual/save', data: { visual: { title: 'foo' } } })
).rejects.toThrow(
// 期望: 错误信息能让开发者立刻查 nginx log / jnpf-admin log,
// 而不是误判"微服务缺失"或"nginx 路由缺失"
/HTTP 500.*POST.*\/api\/blade-visual\/visual\/save.*Internal Server Error/
)
})
it('POST 返 503 + Spring Boot JSON → throw 含 status + error 字段', async () => {
const body = JSON.stringify({
timestamp: 1784555000000,
status: 503,
error: 'Service Unavailable',
message: '',
path: '/api/blade-visual/visual/list',
})
stubbed = installFetchStub(503, body)
vi.stubGlobal('fetch', stubbed)
// Spring Boot 错误 body 优先用 sb.error (msg 优先但这里空, falls back to error)
await expect(
defHttp.post({ url: '/api/blade-visual/visual/list', data: {} })
).rejects.toThrow(/HTTP 503 from POST .*visual\/list.*Service Unavailable/)
})
})
// ----------------------------------------------------------------------------
// 场景 5 [P2 改进目标]: HTTP 502 + HTML 错误页 (nginx upstream down)
// ----------------------------------------------------------------------------
describe('场景 5: HTTP 5xx + HTML 错误页 (nginx upstream 502) [BS-新\datascreen]', () => {
it('POST 返 502 + HTML → throw 含 HTTP 502 + body 摘要 (≤200 chars)', async () => {
const html = '<html><body><h1>502 Bad Gateway</h1><p>nginx/1.27.1</p></body></html>'
stubbed = installFetchStub(502, html, { 'Content-Type': 'text/html' })
vi.stubGlobal('fetch', stubbed)
let err: unknown
try {
await defHttp.post({ url: '/api/blade-visual/visual/save', data: {} })
} catch (e) {
err = e
}
expect(err).toBeInstanceOf(Error)
// 期望: throw 含 HTTP 502 + path (经过 _defhttp_shim stripApiPrefix, /api 被剥) + body 摘要
const msg = (err as Error).message
expect(msg).toContain('HTTP 502')
expect(msg).toContain('blade-visual/visual/save') // 去 /api 前缀的 path
expect(msg).toContain('502 Bad Gateway') // body 摘要
})
it('POST 返 504 + HTML → throw 含 HTTP 504', async () => {
const html = '<html><body><h1>504 Gateway Timeout</h1></body></html>'
stubbed = installFetchStub(504, html)
vi.stubGlobal('fetch', stubbed)
await expect(
defHttp.post({ url: '/api/blade-visual/visual/save', data: {} })
).rejects.toThrow(/HTTP 504/)
})
})
// ----------------------------------------------------------------------------
// 场景 6 [P2 改进目标]: HTTP 200 + 非 JNPF 信封 JSON
// - 现在的 bug: 静默 cast 成 JnpfResp<T>, 后续 .code === undefined → "API code=undefined:"
// - 改进期望: throw "non-Jnpf envelope, body[..]" 含 path
// ----------------------------------------------------------------------------
describe('场景 6: HTTP 200 + 非 JNPF 信封 JSON (大屏 D0720 实测) [BS-新\datascreen]', () => {
it('POST 返 200 + {foo:"bar"} → throw "non-Jnpf envelope" 含 path', async () => {
stubbed = installFetchStub(200, JSON.stringify({ foo: 'bar', baz: 123 }))
vi.stubGlobal('fetch', stubbed)
await expect(
defHttp.post({ url: '/api/blade-visual/visual/save', data: {} })
).rejects.toThrow(
/non-Jnpf envelope|unexpected response shape.*\/api\/blade-visual\/visual\/save/
)
})
it('POST 返 200 + [] → throw "non-Jnpf envelope"', async () => {
stubbed = installFetchStub(200, JSON.stringify([1, 2, 3]))
vi.stubGlobal('fetch', stubbed)
await expect(
defHttp.post({ url: '/api/blade-visual/visual/list', data: {} })
).rejects.toThrow(/non-Jnpf envelope|unexpected response shape/)
})
})
// ----------------------------------------------------------------------------
// 场景 7 [P2 改进目标]: HTTP 200 + 部分 JNPF 信封 (缺 code)
// ----------------------------------------------------------------------------
describe('场景 7: HTTP 200 + 部分 JNPF 信封 (缺 code) [BS-新\datascreen]', () => {
it('POST 返 200 + {msg:"x", data:{}} (无 code) → throw "non-Jnpf envelope"', async () => {
stubbed = installFetchStub(200, JSON.stringify({ msg: 'x', data: {} }))
vi.stubGlobal('fetch', stubbed)
await expect(
defHttp.post({ url: '/api/foo', data: {} })
).rejects.toThrow(/non-Jnpf envelope|unexpected response shape/)
})
it('POST 返 200 + {data:{}, code:200} (有 code 但缺 msg) → 仍按 envelope 处理 (B-1)', async () => {
// 现状: code=200 + data 不为 null → 返回 data (即使 msg 缺失)
stubbed = installFetchStub(200, JSON.stringify({ code: 200, data: { id: '42' } }))
vi.stubGlobal('fetch', stubbed)
const result = await defHttp.post({ url: '/api/foo', data: {} })
expect(result).toEqual({ id: '42' })
})
})
// ----------------------------------------------------------------------------
// 场景 8: fetch 网络错误 → 透传 throw (保持现状)
// ----------------------------------------------------------------------------
describe('场景 8: fetch 网络错误 (保持)', () => {
it('fetch throws TypeError → 透传抛给调用方', async () => {
stubbed = vi.fn(async () => {
throw new TypeError('fetch failed: ECONNREFUSED')
})
vi.stubGlobal('fetch', stubbed)
await expect(
defHttp.post({ url: '/api/blade-visual/visual/save', data: {} })
).rejects.toThrow(/fetch failed.*ECONNREFUSED/)
})
})