protocol.test.mjs
7.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/**
* @file 请求 / 签名协议模式钉值测试。
*
* 覆盖四件事:
* 1. 默认协议只做简单 REST:URL 拼得出来、body 不被塞签名产物;
* 2. 业务 prepare 决定 URL / headers;
* 3. 业务 sign.body / sign.headers 真正接管签名;
* 4. 防重复提交、取消等共性能力仍在内核门面,不随协议转移。
*
* 这里手工构造 ResolvedProtocols(与 defineProtocols 的输出同形),
* 因为 contracts 是 type-only 工作区包、没有可供 node require 的产物。
*/
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import test from 'node:test';
const require = createRequire(import.meta.url);
const { createClient, createStrategy, cancelRequests, activeRequestCount } = require('../dist/index.cjs');
const tick = () => new Promise((r) => setTimeout(r, 0));
function fakeSender(body = { code: '0', data: { ok: true } }) {
const calls = [];
return {
calls,
sender: {
async send(req) {
calls.push(req);
return { status: 200, data: body, headers: {} };
},
},
};
}
function resolved(overrides = {}) {
const deps = {
defaultPrepare(spec) {
const params = { ...(spec.params ?? {}) };
const query = Object.keys(params)
.filter((k) => params[k] !== undefined && params[k] !== null)
.sort()
.map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(String(params[k]))}`)
.join('&');
const pathOnly = spec.resource ?? '';
const ctx = spec.contextPath ?? '';
const path = ctx && !pathOnly.startsWith(`${ctx}/`)
? `${ctx.replace(/\/+$/, '')}/${pathOnly.replace(/^\//, '')}`
: pathOnly;
const base = `${spec.baseURL ?? ''}${path.startsWith('/') || /^https?:/.test(path) ? path : `/${path}`}`;
return {
url: query ? `${base}${base.includes('?') ? '&' : '?'}${query}` : base,
method: spec.method,
data: spec.data,
headers: { ...spec.headers },
resource: spec.resource,
timeout: spec.timeout,
};
},
defaultNormalize: (raw) => raw,
unsignedBody: (p) => p,
unsignedHeaders: () => ({}),
};
return {
auth: {},
access: {},
menu: {},
request: {
id: 'rest-fetch',
defaults: {},
prepare: (spec, d) => d.defaultPrepare(spec),
normalize: (raw) => raw,
...(overrides.request ?? {}),
},
sign: { ...(overrides.sign ?? {}) },
deps,
};
}
test('PT-001 默认协议 = 简单 REST:URL 与 query 正确,body 不带签名产物', async () => {
const { calls, sender } = fakeSender();
const api = createClient({ protocols: resolved(), sender, baseURL: 'https://api.test' });
const data = await api.post('/user/list', { page: 1 }, { params: { b: 2, a: 1 } });
assert.deepEqual(data, { ok: true });
assert.equal(calls[0].url, 'https://api.test/user/list?a=1&b=2');
assert.deepEqual(calls[0].data, { page: 1 });
assert.equal(calls[0].headers['X-Sign'], undefined);
});
test('PT-002 业务 prepare 决定 URL 与请求头', async () => {
const { calls, sender } = fakeSender();
const protocols = resolved({
request: {
prepare: (spec, deps) => {
const wire = deps.defaultPrepare(spec);
return {
...wire,
url: `https://biz.example${wire.url}`,
headers: { ...wire.headers, 'X-Biz-Gateway': 'yes' },
};
},
},
});
const api = createClient({ protocols, sender });
await api.get('/thing');
assert.equal(calls[0].url, 'https://biz.example/thing');
assert.equal(calls[0].headers['X-Biz-Gateway'], 'yes');
});
test('PT-003 签名协议接管 body / headers,内核不持有算法', async () => {
const { calls, sender } = fakeSender();
const protocols = resolved({
sign: {
headers: (input) => ({ 'X-Biz-Sign': `${input.method}:${input.path}:${input.query}` }),
body: (params) => ({ ...params, signed: true }),
},
});
const api = createClient({ protocols, sender, baseURL: 'https://api.test' });
await api.post('/order', { id: 7 });
assert.equal(calls[0].headers['X-Biz-Sign'], 'POST:/order:');
assert.equal(calls[0].data.signed, true);
assert.equal(calls[0].data.id, 7);
});
test('PT-004 防重复提交是内核共性,协议模式照样生效', async () => {
let release;
const gate = new Promise((r) => { release = r; });
let sent = 0;
const sender = {
async send() {
sent++;
await gate;
return { status: 200, data: { code: '0', data: true }, headers: {} };
},
};
const api = createClient({ protocols: resolved(), sender, duplicatePrevention: true, scope: 'pt4' });
const first = api.post('/submit', { a: 1 });
await tick();
await assert.rejects(api.post('/submit', { a: 1 }), /请勿重复提交/);
release();
assert.equal(await first, true);
assert.equal(sent, 1);
cancelRequests('pt4');
assert.equal(activeRequestCount(), 0);
});
test('PT-005 不传 protocols 直接报错——预设已移除,协议是唯一入口', () => {
assert.throws(() => createClient({}), (err) => err.code === 'PROTOCOLS_REQUIRED');
assert.throws(() => createStrategy({}), (err) => err.code === 'PROTOCOLS_REQUIRED');
});
test('PT-006 协议 defaults 合入请求:web 主壳信封语义不再写在内核预设里', async () => {
const { calls, sender } = fakeSender({ code: 200, message: 'ok', data: { id: 1 } });
const webDefaults = {
timeout: 20000,
contentType: false,
response: {
codeKey: 'code',
successCodes: [200],
logoutCodes: [401, 10002],
dataMode: 'envelope',
messageKey: 'message',
toastOnError: false,
binaryHeaders: true,
},
};
const api = createClient({ protocols: resolved({ request: { defaults: webDefaults } }), sender });
const out = await api.post('/order/list', { page: 1 });
// 关键证明:200 被判成功(默认 successCodes 是 ['0'],defaults 没合入这里会抛业务错误)
// 且调用真实发生、timeout 来自协议 defaults。返回形态由 binaryHeaders 决定,不在本测试钉死。
assert.ok(out, '200 判成功,未抛业务错误');
assert.equal(calls.length, 1);
assert.equal(calls[0].timeout, 20000, 'timeout 来自协议 defaults');
assert.equal(calls[0].headers['Content-Type'], undefined, 'contentType:false 不预置头');
});
test('PT-006b 登出码 401 来自协议 defaults:默认 [20,21] 不会命中', async () => {
let logout = 0;
const { sender } = fakeSender({ code: 401, message: 'expired' });
const api = createClient({
protocols: resolved({ request: { defaults: { response: { logoutCodes: [401, 10002] } } } }),
sender,
onLoginRequired: () => { logout++; },
});
await assert.rejects(api.post('/whoami', {})); // 未设 logoutPending 时登出按 throwOnError 抛出
assert.equal(logout, 1, '401 命中协议声明的登出码(默认 [20,21] 不会)');
});
test('PT-007 签名协议拿到与线上同源的 canonical 输入(path/query/mediaType/bodyString)', async () => {
let captured = null;
const { sender } = fakeSender();
const api = createClient({
protocols: resolved({
request: { defaults: { contentType: false } },
sign: {
headers(input) {
captured = input;
return { 'X-Sign': 'signed' };
},
},
}),
sender,
baseURL: 'https://api.test',
contextPath: '/api',
});
await api.post('/system/auth/login', { password: 'p' }, { params: { account: 'u' }, contentType: false });
assert.ok(captured, '签名协议应被调用');
assert.equal(captured.method, 'POST');
assert.equal(captured.path, '/api/system/auth/login', 'path 含 context-path,与线上一致');
assert.match(captured.query, /account=u/, 'query 与线上同源');
assert.equal(captured.mediaType, 'application/json', '有 body 时媒体类型按 JSON');
assert.equal(captured.bodyString, '{"password":"p"}', 'bodyString 与实际发送字节一致');
assert.equal(captured.timestamp > 0, true);
});