Files
ftb-project-management/apps/web/lib/api.test.ts
2e595c7e72
Some checks failed
Deploy Production / Build, push, deploy, verify (push) Has been cancelled
refactor(data): 收口关系表运行时数据源
- 移除已迁移业务 AppData 运行时 fallback,改走领域 API 和关系表快读
- 补齐需求产品负责人、版本计划任务 JSON 和成员 username 回填迁移
- 统一治理字典入口,并补充 AI provider、数据源契约和领域服务测试

Co-Authored-By: Codex GPT-5 <codex@openai.com>
2026-07-09 14:59:49 +08:00

132 lines
4.4 KiB
TypeScript

import assert from 'node:assert/strict';
import test from 'node:test';
import { __resetApiAvailabilityForTests, api, resolveApiBase } from './api';
test('API base defaults to same-origin in production and localhost in development', () => {
assert.equal(resolveApiBase({ NODE_ENV: 'production' }), '/api/v1');
assert.equal(resolveApiBase({ NODE_ENV: 'development' }), 'http://localhost:3001/api/v1');
assert.equal(
resolveApiBase({ NODE_ENV: 'production', NEXT_PUBLIC_API_URL: 'https://api.example.com/api/v1/' }),
'https://api.example.com/api/v1',
);
});
test('API base ignores local-only absolute URLs in production', () => {
for (const localApiUrl of [
'http://localhost:3001/api/v1',
'http://127.0.0.1:3001/api/v1',
'http://0.0.0.0:3001/api/v1',
]) {
assert.equal(
resolveApiBase({ NODE_ENV: 'production', NEXT_PUBLIC_API_URL: localApiUrl }),
'/api/v1',
);
}
});
test('API requests use the resolved base path', async () => {
const originalFetch = globalThis.fetch;
const apiBase = resolveApiBase();
const urls: string[] = [];
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
urls.push(String(input));
return new Response(JSON.stringify(init?.method === 'POST' ? { ok: true } : {}), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}) as typeof fetch;
try {
__resetApiAvailabilityForTests();
await api.post('/config/ai/test', { id: 'provider-1' });
assert.deepEqual(urls, [`${apiBase}/config/ai`, `${apiBase}/config/ai/test`]);
} finally {
globalThis.fetch = originalFetch;
}
});
test('API requests include current auth user headers when a session exists', async () => {
const originalFetch = globalThis.fetch;
const originalSessionStorage = Object.getOwnPropertyDescriptor(globalThis, 'sessionStorage');
const headers: HeadersInit[] = [];
Object.defineProperty(globalThis, 'sessionStorage', {
configurable: true,
value: {
getItem: (key: string) => key === 'ftb_auth_session'
? JSON.stringify({ id: 'm-8', name: '超级管理员', username: 'admin', roleId: 'role-admin', email: 'admin@example.com' })
: null,
},
});
globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
headers.push(init?.headers ?? {});
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}) as typeof fetch;
try {
__resetApiAvailabilityForTests();
await api.post('/products', { name: 'FTB' });
assert.equal((headers[1] as Record<string, string>)['x-ftb-user-id'], 'm-8');
assert.equal((headers[1] as Record<string, string>)['x-ftb-user-role-id'], 'role-admin');
assert.equal((headers[1] as Record<string, string>)['x-ftb-user-name'], encodeURIComponent('超级管理员'));
} finally {
globalThis.fetch = originalFetch;
if (originalSessionStorage) {
Object.defineProperty(globalThis, 'sessionStorage', originalSessionStorage);
} else {
delete (globalThis as any).sessionStorage;
}
}
});
test('API availability probe retries after a transient failure', async () => {
const originalFetch = globalThis.fetch;
const apiBase = resolveApiBase();
const calls: string[] = [];
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
calls.push(String(input));
if (calls.length === 1) throw new Error('temporary network failure');
return new Response(JSON.stringify(init?.method === 'POST' ? { ok: true } : {}), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}) as typeof fetch;
try {
__resetApiAvailabilityForTests();
await assert.rejects(() => api.post('/config/ai/test', { id: 'provider-1' }), /API 不可用/);
await api.post('/config/ai/test', { id: 'provider-1' });
assert.deepEqual(calls, [
`${apiBase}/config/ai`,
`${apiBase}/config/ai`,
`${apiBase}/config/ai/test`,
]);
} finally {
globalThis.fetch = originalFetch;
}
});
test('raw API requests map abort errors to a readable timeout message', async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = (async () => {
throw new Error('signal is aborted without reason');
}) as typeof fetch;
try {
await assert.rejects(
() => api.postRaw('/ai/decompose', {}, 1),
/请求超时/,
);
} finally {
globalThis.fetch = originalFetch;
}
});