rop.test.mjs
11.2 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/**
* @file ROP-router 客户端的钉值对照:落点 URL、凭据解析(缺省 / secretKey 覆盖 / dj)、
* 签名触发(入参含 method/v/format/locale/source/appKey/sessionId)、响应拦截
* (code 0 解包、20/21 触发 onLoginRequired、其它码 toast+reject)、loading 并发计数。
* 用注入假 sender + 假 ui 验证,不依赖真机 wx。
*/
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import test from 'node:test';
const require = createRequire(import.meta.url);
const { createLegacyRopClient, createSigner } = require('../dist/index.cjs');
const HOSTS = { scrm: 'https://scrm.test.glsx.com.cn', dj: 'https://dj.test.glsx.com.cn' };
const PATH_ENUM = { shopmall: '/rop-scrm-shopmall/' };
const DEFAULT_CRED = { appKey: '48e5e13229b82c1b4e6e8c96151f0637', secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b' };
const DJ_CRED = { appKey: 'dj-appkey', secret: 'dj-secret' };
const SCrm_SHOPMALL_CRED = { appKey: 'shopmall-appkey', secret: 'shopmall-secret' };
const signer = createSigner({ kind: 'rop', id: 'test-sha1' });
const flatten = (obj) => {
const out = {};
for (const [k, v] of Object.entries(obj)) {
if (v === null || v === undefined) continue;
out[k] = typeof v === 'string' ? v : typeof v === 'object' ? JSON.stringify(v) : String(v);
}
return out;
};
const sign = async (params, secret, noSignAttr = []) => {
const flat = flatten(params);
const signed = await signer.fields({
method: flat.method,
appKey: flat.appKey,
secret,
version: flat.v,
format: flat.format,
params: flat,
exclude: noSignAttr,
});
return { ...flat, sign: signed.sign };
};
const makeHarness = (overrides = {}) => {
const calls = { sends: [], toasts: [], loginRequired: [], errors: [], showLoading: 0, hideLoading: 0 };
const sender = {
async send(req) {
calls.sends.push(req);
return overrides.send?.(req) ?? { status: 200, data: { code: '0', message: 'ok', data: { ok: 1 } } };
},
};
const ui = {
showNavigationBarLoading: () => {},
hideNavigationBarLoading: () => {},
stopPullDownRefresh: () => {},
showLoading: () => { calls.showLoading++; },
hideLoading: () => { calls.hideLoading++; },
toast: (m) => { calls.toasts.push(m); },
};
const events = {
onLoginRequired: (code, ctx) => calls.loginRequired.push({ code, ctx }),
onError: (m, ctx) => { calls.errors.push({ m, ctx }); },
};
const client = createLegacyRopClient({
hosts: HOSTS,
pathEnum: PATH_ENUM,
defaultCredential: DEFAULT_CRED,
secretKey: { shopmall: SCrm_SHOPMALL_CRED },
djSecretKey: DJ_CRED,
sign,
resolveSessionId: () => 'sess-123',
getMerchantId: overrides.getMerchantId,
sender,
ui,
events,
beforeRequest: overrides.beforeRequest,
onTransportError: overrides.onTransportError,
defaultPath: overrides.defaultPath,
resolveOnOther: overrides.resolveOnOther,
toastOnOtherCodes: overrides.toastOnOtherCodes,
logoutCodes: overrides.logoutCodes,
successCodes: overrides.successCodes,
});
return { client, calls };
};
test('IT-ROP-URL-001 落点 = host + pathEnum[projectName] + router?method=,projectName 从 method[2] 推断', async () => {
const { client, calls } = makeHarness();
await client.request('scrm.api.shopmall.integral.all', { a: 1 });
const req = calls.sends[0];
assert.equal(req.url, 'https://scrm.test.glsx.com.cn/rop-scrm-shopmall/router?method=scrm.api.shopmall.integral.all');
assert.equal(req.method, 'POST');
assert.equal(req.headers['content-type'], 'application/x-www-form-urlencoded');
});
test('IT-ROP-CRED-002 凭据解析:缺省 / secretKey 覆盖 scrm / dj 分别用不同密钥', async () => {
const { client, calls } = makeHarness();
await client.request('scrm.api.other.x', { a: 1 }); // 无覆盖 -> 缺省
assert.equal(calls.sends[0].data.appKey, DEFAULT_CRED.appKey);
await client.request('scrm.api.shopmall.x', { a: 1 }); // secretKey 覆盖
assert.equal(calls.sends[1].data.appKey, SCrm_SHOPMALL_CRED.appKey);
await client.request('scrm.api.shopmall.x', { a: 1 }, { hostType: 'dj' }); // dj
assert.equal(calls.sends[2].data.appKey, DJ_CRED.appKey);
});
test('IT-ROP-SIGN-003 sign 入参含 method/v/format/locale/source/appKey/sessionId,并产出 sign', async () => {
const { client, calls } = makeHarness();
await client.request('scrm.api.shopmall.x', { biz: 'v' });
const data = calls.sends[0].data;
assert.equal(data.method, 'scrm.api.shopmall.x');
assert.equal(data.v, '1.0.0');
assert.equal(data.format, 'json');
assert.equal(data.locale, 'zh_CN');
assert.equal(data.source, 'dj-wechat');
assert.equal(data.appKey, SCrm_SHOPMALL_CRED.appKey);
assert.equal(data.sessionId, 'sess-123');
assert.match(String(data.sign), /^[0-9A-F]+$/); // SHA1 大写 hex
});
test('IT-ROP-MERCHANT-004 merchantId 头随 getMerchantId 上送', async () => {
const { client, calls } = makeHarness({ getMerchantId: () => 'mid-9' });
await client.request('scrm.api.shopmall.x', {});
assert.equal(calls.sends[0].headers.merchantId, 'mid-9');
});
test('IT-ROP-RESP-005 code 0 解包 data.data;非 0 触发 onError + toast + reject', async () => {
const { client, calls } = makeHarness({
send: () => ({ status: 200, data: { code: '100', message: '参数错误', data: null } }),
});
await assert.rejects(() => client.request('scrm.api.shopmall.x', {}), /参数错误/);
assert.equal(calls.errors.length, 1);
assert.deepEqual(calls.toasts, ['参数错误']);
});
test('IT-ROP-LOGOUT-006 code 20/21 触发 onLoginRequired 且不 settle(登录后由页面重发)', async () => {
const { client, calls } = makeHarness({
send: () => ({ status: 200, data: { code: 20, message: '登录失效', data: null } }),
});
const p = client.request('scrm.api.shopmall.x', {});
await new Promise((r) => setTimeout(r, 20)); // 等微任务跑完 onLoginRequired
assert.equal(calls.loginRequired.length, 1);
assert.equal(calls.loginRequired[0].code, 20);
// 不 settle:短延时后仍未决议
let settled = false;
p.then(() => (settled = true), () => (settled = true));
await new Promise((r) => setTimeout(r, 30));
assert.equal(settled, false);
});
test('IT-ROP-LOADING-007 showLoading 每次都弹,hide 按计数合并:并发两次共享一次 hide', async () => {
const pending = [];
const { client, calls } = makeHarness({
send: () => new Promise((res) => pending.push(res)),
});
const p1 = client.request('scrm.api.shopmall.a', {}, { showLoading: true });
const p2 = client.request('scrm.api.shopmall.b', {}, { showLoading: true });
await new Promise((r) => setTimeout(r, 0)); // 等微任务累加 showLoading
assert.equal(calls.showLoading, 2); // 每次请求都弹一次(与 legacy 一致)
pending[0]({ status: 200, data: { code: '0', data: 1 } });
await p1;
assert.equal(calls.hideLoading, 0); // p1 完成但 p2 未完成 -> 仍不隐藏
pending[1]({ status: 200, data: { code: '0', data: 2 } });
await p2;
assert.equal(calls.hideLoading, 1); // 两个都完成才隐藏一次
});
test('IT-ROP-RETURNALL-008 returnAll 返回完整信封', async () => {
const { client } = makeHarness({
send: () => ({ status: 200, data: { code: '0', message: 'ok', data: { inner: 1 } } }),
});
const env = await client.request('scrm.api.shopmall.x', {}, { returnAll: true });
assert.equal(env.code, '0');
assert.deepEqual(env.data, { inner: 1 });
});
test('IT-ROP-BEFORE-009 beforeRequest 返回 {abort} 时不发请求且按 value 返回(store 无网络静默返回)', async () => {
const { client, calls } = makeHarness({
beforeRequest: async () => ({ abort: true, value: undefined }),
});
const r = await client.request('scrm.api.shopmall.x', {});
assert.equal(calls.sends.length, 0);
assert.equal(r, undefined);
});
test('IT-ROP-BEFORE-010 beforeRequest 抛错按传输失败处理(usedcar 无网络 reject)', async () => {
const { client, calls } = makeHarness({
beforeRequest: async () => { throw new Error('网络异常'); },
onTransportError: () => ({ message: '网络异常' }),
});
await assert.rejects(() => client.request('scrm.api.shopmall.x', {}), /网络异常/);
assert.equal(calls.sends.length, 0);
});
test('IT-ROP-RESP-011 resolveOnOther:非 20/21 其它码直接 resolve(data)(usedcar 旧壳语义)', async () => {
const { client } = makeHarness({
send: () => ({ status: 200, data: { code: '100', message: '其它', data: { ok: 2 } } }),
resolveOnOther: true,
});
const r = await client.request('scrm.api.shopmall.x', {});
assert.deepEqual(r, { ok: 2 });
});
test('IT-ROP-RESP-012 toastOnOtherCodes:命中码仍 resolve 但附带 toast(usedcar code -1)', async () => {
const { client, calls } = makeHarness({
send: () => ({ status: 200, data: { code: '-1', message: '提示', data: { ok: 3 } } }),
resolveOnOther: true,
toastOnOtherCodes: ['-1'],
});
const r = await client.request('scrm.api.shopmall.x', {});
assert.deepEqual(r, { ok: 3 });
assert.deepEqual(calls.toasts, ['提示']);
});
test('IT-ROP-RESP-013 silent:抑制全部默认 toast(usedcar failTips=false)', async () => {
const { client, calls } = makeHarness({
send: () => ({ status: 200, data: { code: '-1', message: '提示', data: { ok: 3 } } }),
resolveOnOther: true,
toastOnOtherCodes: ['-1'],
});
await client.request('scrm.api.shopmall.x', {}, { silent: true });
assert.equal(calls.toasts.length, 0);
});
test('IT-ROP-PATH-014 defaultPath 兜底(usedcar 固定前缀 /rop-dj-car-boutique/)', async () => {
const { client, calls } = makeHarness({ defaultPath: '/rop-dj-car-boutique/' });
await client.request('dj.api.smartcarlife.x', {});
assert.equal(calls.sends[0].url, 'https://scrm.test.glsx.com.cn/rop-dj-car-boutique/router?method=dj.api.smartcarlife.x');
});
test('IT-ROP-PATH-015 opts.path 为完整路径段(含 router)时原样使用,不重复追加 router', async () => {
const { client, calls } = makeHarness();
await client.request('dj.api.x', {}, { path: '/rop-dj-pe-analysis/router' });
assert.equal(calls.sends[0].url, 'https://scrm.test.glsx.com.cn/rop-dj-pe-analysis/router?method=dj.api.x');
});
test('IT-ROP-PROJECT-016 getProjectName 自定义(usedcar split(.api)[0])驱动凭据选择', async () => {
const creds = [];
const client = createLegacyRopClient({
hosts: HOSTS,
defaultPath: '/rop-dj-car-boutique/',
getProjectName: (m) => m.split('.api')[0].split('.')[0],
resolveCredential: (pn) => {
creds.push(pn);
return { appKey: `k-${pn}`, secret: 's' };
},
sign,
sender: { async send() { return { status: 200, data: { code: '0', data: {} } }; } },
});
await client.request('dj.api.smartcarlife.login.x', {});
await client.request('scrm.api.clue.x', {});
assert.deepEqual(creds, ['dj', 'scrm']);
});
test('IT-ROP-TRANSPORT-017 onTransportError 改写提示文案用于 toast,并仍 reject 原始 error', async () => {
const { client, calls } = makeHarness({
send: () => { throw Object.assign(new Error('timeout'), { errMsg: 'request:fail timeout' }); },
onTransportError: () => ({ message: '请求超时,请重试' }),
});
await assert.rejects(() => client.request('scrm.api.shopmall.x', {}));
assert.deepEqual(calls.toasts, ['请求超时,请重试']);
});