import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * 主系统**主动解绑**接口封装层契约守卫(`server/src/services/mainSystem/api/bindings.ts`)。 * * 为什么值得单独钉(2026-11-06 联调,主系统 `2aba8809`): * · 解绑成功后**原 Token 访问其它供应商接口一律 401**,但**同一 unbind 接口**允许原 Token 幂等重试 * ⇒ 网络/超时/5xx 重试是安全的(最坏拿回 `noop`),而 400/401/403/404 重试只是白打; * · 主系统对 `subsystem_code` / `supplier_code` / `main_branch_code` 都有格式校验, * 客户端先挡掉非法的(不白发请求),`*` 通配必须**不下发**(主系统正则不认 `*`); * · 2xx 但回执缺 `ok:true` **不能当成功**(上层会据此停用本地绑定并报成功)。 * * 本文件用 mock fetch + mock token/config 覆盖:ok / noop / 重试 / 4xx 不重试 / 未配置 / 回执不可识别。 */ const enabled = vi.hoisted(() => ({ value: true })); vi.mock('../src/services/mainSystem/config', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, isMainSystemIntegrationEnabled: () => enabled.value, mainSystemBaseUrl: () => 'http://main-system.example', }; }); const getMainSystemToken = vi.hoisted(() => vi.fn()); vi.mock('../src/services/mainSystem/token', () => ({ getMainSystemToken: (...args: unknown[]) => getMainSystemToken(...args), })); const fetchMock = vi.hoisted(() => vi.fn()); vi.stubGlobal('fetch', fetchMock); import { MAIN_SYSTEM_DEFAULT_PATHS } from '../src/services/mainSystem/config'; import { defaultUnbindPath, UNBIND_RETRY_DELAYS_MS, unbindMainSystemBinding, } from '../src/services/mainSystem/api/bindings'; function jsonResponse(status: number, body: unknown) { return { ok: status >= 200 && status < 300, status, json: async () => body, }; } const OK_UNBOUND = { ok: true, action: 'unbound', affected: 1, bindings: [{ branch_code: 'BR002', supplier_code: 'SUP37831443', subsystem_code: 'SCQEM2X7B6P5' }], }; const OK_NOOP = { ok: true, action: 'noop', affected: 0, bindings: [] }; const sleepMock = vi.fn(async () => undefined); function okToken(token = 'tok-1') { return { kind: 'ok', token, branchCode: 'BR002', expiresAt: Date.now() + 60_000 }; } function call(overrides: Record = {}) { return unbindMainSystemBinding({ supplierCode: 'SUP37831443', subsystemCode: 'SCQEM2X7B6P5', mainBranchCode: 'BR002', reason: '联调:主动解绑', sleepImpl: sleepMock, ...overrides, } as Parameters[0]); } beforeEach(() => { fetchMock.mockReset(); getMainSystemToken.mockReset(); sleepMock.mockReset(); sleepMock.mockResolvedValue(undefined); enabled.value = true; delete process.env.MAIN_SYSTEM_UNBIND_PATH; getMainSystemToken.mockResolvedValue(okToken()); }); describe('① 请求:端点表唯一拼装 + Token + 契约字段', () => { it('默认路径 = /api/supplier/integration-bindings/unbind,POST + Bearer + snake_case body', async () => { fetchMock.mockResolvedValue(jsonResponse(200, OK_UNBOUND)); const result = await call(); expect(defaultUnbindPath()).toBe('/api/supplier/integration-bindings/unbind'); expect(MAIN_SYSTEM_DEFAULT_PATHS.integrationBindingUnbind).toBe( '/api/supplier/integration-bindings/unbind' ); expect(getMainSystemToken).toHaveBeenCalledWith('SUP37831443', expect.anything()); expect(fetchMock).toHaveBeenCalledTimes(1); const [url, init] = fetchMock.mock.calls[0] as [string, any]; expect(url).toBe('http://main-system.example/api/supplier/integration-bindings/unbind'); expect(init.method).toBe('POST'); expect(init.headers.Authorization).toBe('Bearer tok-1'); expect(JSON.parse(init.body)).toEqual({ subsystem_code: 'SCQEM2X7B6P5', supplier_code: 'SUP37831443', main_branch_code: 'BR002', reason: '联调:主动解绑', }); }); it('`MAIN_SYSTEM_UNBIND_PATH` 可覆盖路径(业务层不硬编码 URL)', async () => { process.env.MAIN_SYSTEM_UNBIND_PATH = '/custom/unbind'; fetchMock.mockResolvedValue(jsonResponse(200, OK_UNBOUND)); await call(); expect((fetchMock.mock.calls[0] as [string])[0]).toBe('http://main-system.example/custom/unbind'); }); it('通配主系统分公司(`*`/空)**不下发** main_branch_code(主系统正则不认 `*`,会 400)', async () => { fetchMock.mockResolvedValue(jsonResponse(200, OK_UNBOUND)); await call({ mainBranchCode: '*', reason: '' }); expect(JSON.parse((fetchMock.mock.calls[0] as [string, any])[1].body)).toEqual({ subsystem_code: 'SCQEM2X7B6P5', supplier_code: 'SUP37831443', }); }); }); describe('② 结果映射:ok / noop / 不可识别', () => { it('action=unbound ⇒ kind=ok + affected + bindings(原样带回,供审计对账)', async () => { fetchMock.mockResolvedValue(jsonResponse(200, OK_UNBOUND)); await expect(call()).resolves.toMatchObject({ kind: 'ok', httpStatus: 200, action: 'unbound', affected: 1, attempts: 1, reason: '', bindings: [{ branch_code: 'BR002', supplier_code: 'SUP37831443', subsystem_code: 'SCQEM2X7B6P5' }], }); }); it('action=noop ⇒ kind=noop(幂等重试/重复点击不是失败)', async () => { fetchMock.mockResolvedValue(jsonResponse(200, OK_NOOP)); await expect(call()).resolves.toMatchObject({ kind: 'noop', action: 'noop', affected: 0, attempts: 1, }); }); it('2xx 但回执缺 ok:true ⇒ unavailable(绝不把"没解掉"当成功)', async () => { fetchMock.mockResolvedValue(jsonResponse(200, { action: 'unbound' })); const result = await call(); expect(result.kind).toBe('unavailable'); expect(result.reason).toContain('回执不可识别'); expect(result.action).toBeNull(); }); }); describe('③ 重试口径:只有 unavailable 才重试(退避 300/800ms)', () => { it('5xx 连打 3 次失败 ⇒ 共 3 次请求 + 300/800 两次退避', async () => { fetchMock.mockResolvedValue(jsonResponse(502, { error: 'bad_gateway' })); const result = await call(); expect(fetchMock).toHaveBeenCalledTimes(3); expect(sleepMock.mock.calls.map((c) => c[0])).toEqual([...UNBIND_RETRY_DELAYS_MS]); expect(result).toMatchObject({ kind: 'unavailable', httpStatus: 502, attempts: 3 }); }); it('第 2 次成功 ⇒ 停止重试(attempts=2,只退避一次)', async () => { fetchMock .mockResolvedValueOnce(jsonResponse(500, { error: 'server_error' })) .mockResolvedValueOnce(jsonResponse(200, OK_UNBOUND)); const result = await call(); expect(fetchMock).toHaveBeenCalledTimes(2); expect(sleepMock.mock.calls.map((c) => c[0])).toEqual([300]); expect(result).toMatchObject({ kind: 'ok', attempts: 2 }); }); it('408 / 429 属暂态 ⇒ 重试', async () => { for (const status of [408, 429]) { fetchMock.mockReset(); sleepMock.mockClear(); fetchMock.mockResolvedValue(jsonResponse(status, { error: 'later' })); const result = await call(); expect(fetchMock, `status=${status}`).toHaveBeenCalledTimes(3); expect(result).toMatchObject({ kind: 'unavailable', httpStatus: status, attempts: 3 }); } }); it('网络错误 ⇒ unavailable 并重试', async () => { fetchMock.mockRejectedValue(new Error('ECONNRESET')); const result = await call(); expect(fetchMock).toHaveBeenCalledTimes(3); expect(result).toMatchObject({ kind: 'unavailable', httpStatus: 0, attempts: 3 }); expect(result.reason).toContain('ECONNRESET'); }); it('超时(AbortError)⇒ unavailable 并重试', async () => { fetchMock.mockRejectedValue(Object.assign(new Error('aborted'), { name: 'AbortError' })); const result = await call(); expect(fetchMock).toHaveBeenCalledTimes(3); expect(result).toMatchObject({ kind: 'unavailable', httpStatus: 0, attempts: 3 }); expect(result.reason).toBe('主系统主动解绑超时'); }); for (const status of [400, 401, 403, 404]) { it(`${status} ⇒ rejected,**只打 1 次**(语义拒绝,重试无用)`, async () => { fetchMock.mockResolvedValue( jsonResponse(status, { error: 'forbidden', error_description: `HTTP ${status} 说明` }) ); const result = await call(); expect(fetchMock).toHaveBeenCalledTimes(1); expect(sleepMock).not.toHaveBeenCalled(); expect(result).toMatchObject({ kind: 'rejected', httpStatus: status, action: null, affected: 0, attempts: 1, }); expect(result.reason).toContain('说明'); }); } }); describe('④ 未配置 / Token 失败 / 本地先挡', () => { it('Token 换不到(not_configured)⇒ not_configured,不发解绑请求', async () => { getMainSystemToken.mockResolvedValue({ kind: 'not_configured', reason: '未配置 client' }); const result = await call(); expect(fetchMock).not.toHaveBeenCalled(); expect(result).toMatchObject({ kind: 'not_configured', httpStatus: 0, attempts: 1 }); expect(result.reason).toContain('未配置 client'); }); it('Token 换不到(unavailable,如 403 被撤权)⇒ unavailable', async () => { getMainSystemToken.mockResolvedValue({ kind: 'unavailable', reason: '换取对接 Token 失败(403)' }); const result = await call(); expect(fetchMock).not.toHaveBeenCalled(); expect(result.kind).toBe('unavailable'); expect(result.reason).toContain('403'); }); it('缺 subsystem_code / supplier_code ⇒ rejected 400,且**一次请求都不发**', async () => { const noSubsystem = await call({ subsystemCode: '' }); expect(noSubsystem).toMatchObject({ kind: 'rejected', httpStatus: 400, attempts: 1 }); expect(noSubsystem.reason).toContain('subsystem_code'); const noSupplier = await call({ supplierCode: '' }); expect(noSupplier).toMatchObject({ kind: 'rejected', httpStatus: 400, attempts: 1 }); expect(noSupplier.reason).toContain('supplier_code'); expect(fetchMock).not.toHaveBeenCalled(); expect(getMainSystemToken).not.toHaveBeenCalled(); }); it('主系统整体未配置(域名/凭据缺失)⇒ not_configured,不发请求', async () => { enabled.value = false; // token 层在未配置时返回 not_configured(这里用真实 token 模块的实现口径) getMainSystemToken.mockResolvedValue({ kind: 'not_configured', reason: '未配置 MAIN_SYSTEM_BASE_URL / MAIN_SYSTEM_INTEGRATION_CLIENT_ID / _SECRET', }); const result = await call(); expect(fetchMock).not.toHaveBeenCalled(); expect(result.kind).toBe('not_configured'); }); });