WMS_MAIN/test/app/service/openapi/callback.test.js
liufumingren d725e7e457 feat(openapi): 出站回调命名与报文改奇门同层级
- 回调 method 由 snake_case 事件名改为 模块.动作:entryorder.confirm / entryorder.match / deliveryorder.confirm / stockout.confirm / deliveryorder.cancel(原 order.cancel 与入站方法同名,改名避免 callback_url 误指向 /openapi 时被路由到取消单据接口)。

- 时间戳统一为秒级(String(Math.floor(Date.now()/1000))),与 /openapi 入站 ±600 秒时效校验及回调调试页一致。

- 报文体由 { event, data, metadata } 改为奇门同层级 { request: {...} }(移除 metadata,事件标识只靠 query 的 method);入库类回调与奇门侧共用同一份报文组装。

- deliveryorder.confirm 改为逐单发送(仅同步成功的订单);stockout.confirm 直接复用 buildStockoutConfirmDataInternal 结果。

- 修复 entryorder.match 死代码:绑定成功且本次新建绑定时回传,重复触发不重复通知,回传失败不影响绑定。

- 调试页 /docs/api/openapi/callback-test 按真实报文预填;新增出站回调文档页 /docs/api/openapi_callback 及入口链接。

- script/update-api-doc.cjs 支持 spec.newDoc 新建文档与 docMeta.description(附单测)。

- 文档:methods/openapi_callback.json、AI_METHOD_ROUTING.md 5.6 节、docs/openapi-callback-events.md、docs/api-doc-update-workflow.md 等。
2026-09-13 02:24:37 +08:00

503 lines
18 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const assert = require('node:assert/strict');
const OpenapiCallbackService = require('../../../../app/service/openapi/callback');
/**
* 创建 OpenAPI 回调服务纯桩测试实例。
* @param {Object} [options] 桩配置。
* @param {Function} [options.curlImpl] ctx.curl 桩实现。
* @param {Object} [options.loggerImpl] ctx.logger 桩实现。
* @param {Function} [options.apiAppFindOne] ctx.model.ApiApp.findOne 桩实现。
* @return {Object} 服务实例。
*/
function createService({ curlImpl, loggerImpl, apiAppFindOne } = {}) {
const ctx = {
async curl(url, options) {
if (curlImpl) {
return await curlImpl(url, options);
}
return { status: 200, data: {} };
},
logger: loggerImpl || {
info() {},
warn() {},
error() {},
},
model: {
ApiApp: {
async findOne() {
if (typeof apiAppFindOne === 'function') {
return await apiAppFindOne();
}
return null;
},
},
},
};
const service = Object.create(OpenapiCallbackService.prototype);
service.ctx = ctx;
service.app = {};
return service;
}
/**
* 临时替换 console.log 并收集输出,执行完后恢复。
* @param {Function} fn 执行体,入参为收集到的日志数组。
* @return {*} fn 的返回值。
*/
async function captureConsoleLog(fn) {
const logs = [];
const original = console.log;
console.log = (...args) => {
logs.push(args.map(String).join(' '));
};
try {
return await fn(logs);
} finally {
console.log = original;
}
}
/**
* 临时将全局 setTimeout 降为 0 延迟,避免测试等待重试间隔。
* @param {Function} fn 执行体。
* @return {*} fn 的返回值。
*/
async function withFastRetryDelay(fn) {
const originalSetTimeout = global.setTimeout;
global.setTimeout = (callback, ...args) => originalSetTimeout(callback, 0, ...args);
try {
return await fn();
} finally {
global.setTimeout = originalSetTimeout;
}
}
/** 默认回调入参 */
const DEFAULT_OPTIONS = {
callbackUrl: 'http://callback.example.com/openapi',
appKey: 'WMS-TEST-APP-KEY',
selfAppSecret: 'test-secret',
event: 'entryorder.confirm',
request: { entryOrderId: 543 },
};
describe('test/app/service/openapi/callback.test.js', () => {
describe('sendWithRetry 成功分支', () => {
it('2xx 时应打印成功日志且返回结构与重试次数不变', async () => {
await captureConsoleLog(async collected => {
const curlCalls = [];
const service = createService({
curlImpl: async () => {
curlCalls.push(1);
return { status: 200, data: { code: 'OK', data: { accepted: true } } };
},
});
const result = await withFastRetryDelay(() => service.sendWithRetry(DEFAULT_OPTIONS));
assert.equal(curlCalls.length, 1);
assert.deepEqual(result, {
success: true,
retryCount: 0,
response: { code: 'OK', data: { accepted: true } },
error: null,
});
const successLine = collected.find(line => line.includes('success=true'));
assert.ok(successLine, '应存在成功日志行');
assert.match(successLine, /event=entryorder\.confirm/);
assert.match(successLine, /appKey=WMS-TEST-APP-KEY/);
assert.match(successLine, /retry=0/);
assert.match(successLine, /status=200/);
assert.match(successLine, /response=\{/);
});
});
});
describe('sendWithRetry 非 2xx 分支', () => {
it('400 且响应为 JSON 对象时应打印可解析的报文内容', async () => {
await captureConsoleLog(async collected => {
let curlCalls = 0;
const service = createService({
curlImpl: async () => {
curlCalls += 1;
return { status: 400, data: { code: 400, message: '参数错误', field: 'entryOrderId' } };
},
});
const result = await withFastRetryDelay(() => service.sendWithRetry(DEFAULT_OPTIONS));
assert.equal(result.success, false);
assert.equal(result.retryCount, 3);
assert.equal(curlCalls, 4);
assert.deepEqual(result.response, { code: 400, message: '参数错误', field: 'entryOrderId' });
assert.equal(result.error, '回调返回非 2xx 状态码: 400');
const failLine = collected.find(line => line.includes('status=400'));
assert.ok(failLine, '应存在非 2xx 日志行');
assert.match(failLine, /success=false/);
// 提取 response= 之后的内容并确认是合法 JSON
const payloadText = failLine.slice(failLine.indexOf('response=') + 'response='.length);
const parsed = JSON.parse(payloadText);
assert.deepEqual(parsed, { code: 400, message: '参数错误', field: 'entryOrderId' });
});
});
it('400 且响应为纯字符串时应原样打印报文', async () => {
await captureConsoleLog(async collected => {
let curlCalls = 0;
const service = createService({
curlImpl: async () => {
curlCalls += 1;
return { status: 400, data: 'plain text error body' };
},
});
const result = await withFastRetryDelay(() => service.sendWithRetry(DEFAULT_OPTIONS));
assert.equal(result.success, false);
assert.equal(result.retryCount, 3);
assert.equal(curlCalls, 4);
const failLine = collected.find(line => line.includes('status=400'));
assert.ok(failLine, '应存在非 2xx 日志行');
assert.ok(failLine.includes('response=plain text error body'), `日志应原样包含纯字符串报文,实际: ${failLine}`);
});
});
});
describe('sendWithRetry 异常分支', () => {
it('curl 抛异常时应打印 url 与 error.message', async () => {
await captureConsoleLog(async collected => {
let curlCalls = 0;
const service = createService({
curlImpl: async () => {
curlCalls += 1;
throw new Error('connect ECONNREFUSED 127.0.0.1:9999');
},
});
const result = await withFastRetryDelay(() => service.sendWithRetry(DEFAULT_OPTIONS));
assert.equal(result.success, false);
assert.equal(result.retryCount, 3);
assert.equal(curlCalls, 4);
assert.equal(result.error, 'connect ECONNREFUSED 127.0.0.1:9999');
assert.equal(result.response, null);
const failLine = collected.find(line => line.includes('connect ECONNREFUSED'));
assert.ok(failLine, '应存在异常日志行');
assert.match(failLine, /url=http:\/\/callback\.example\.com\/openapi/);
assert.match(failLine, /success=false/);
assert.ok(failLine.includes('response=null'));
});
});
});
describe('_formatResponsePayload 类型兼容', () => {
it('对象 / 字符串 / null 均不抛异常且输出符合预期', () => {
const service = createService();
assert.equal(service._formatResponsePayload({ a: 1 }), '{"a":1}');
assert.equal(service._formatResponsePayload('hello'), 'hello');
assert.equal(service._formatResponsePayload(null), 'null');
assert.equal(service._formatResponsePayload(undefined), 'null');
assert.equal(service._formatResponsePayload(123), '123');
});
it('Buffer / ArrayBuffer / TypedArray 应按 utf8 转换', () => {
const service = createService();
assert.equal(service._formatResponsePayload(Buffer.from('buf-body')), 'buf-body');
assert.equal(service._formatResponsePayload(Uint8Array.from(Buffer.from('typed-body'))), 'typed-body');
const arrayBuffer = Uint8Array.from(Buffer.from('ab-body')).buffer;
assert.equal(service._formatResponsePayload(arrayBuffer), 'ab-body');
});
it('循环引用对象应降级为 String 而不抛异常', () => {
const service = createService();
const circular = {};
circular.self = circular;
assert.doesNotThrow(() => service._formatResponsePayload(circular));
assert.equal(service._formatResponsePayload(circular), '[object Object]');
});
it('超长字符串应截断并追加标记', () => {
const service = createService();
const longText = 'x'.repeat(800);
const formatted = service._formatResponsePayload(longText);
assert.equal(formatted.length, 500 + '...(truncated)'.length);
assert.ok(formatted.startsWith('x'.repeat(500)));
assert.ok(formatted.endsWith('...(truncated)'));
assert.ok(!formatted.includes('x'.repeat(501)));
});
});
describe('sendWithRetry 回调 URL 拼装', () => {
it('URL 中 method 应带 . 且 sign 基于新 query 重算', async () => {
await captureConsoleLog(async () => {
let capturedUrl = null;
let capturedBody = null;
const service = createService({
curlImpl: async (url, options) => {
capturedUrl = url;
capturedBody = options.data;
return { status: 200, data: {} };
},
});
const result = await withFastRetryDelay(() => service.sendWithRetry(DEFAULT_OPTIONS));
assert.equal(result.success, true);
assert.ok(capturedUrl, '应捕获到回调 URL');
assert.ok(capturedUrl.includes('method=entryorder.confirm'), `URL 的 method 应为新名并包含 .,实际: ${capturedUrl}`);
const parsedUrl = new URL(capturedUrl);
const sign = parsedUrl.searchParams.get('sign');
assert.ok(sign, 'URL 应包含 sign 参数');
// 不硬编码 sign:按 signCallback 对 { request } 新报文体重算并比对
const { sign: expectedSign } = service.signCallback({
event: DEFAULT_OPTIONS.event,
appKey: DEFAULT_OPTIONS.appKey,
selfAppSecret: DEFAULT_OPTIONS.selfAppSecret,
body: capturedBody,
timestamp: parsedUrl.searchParams.get('timestamp'),
});
assert.equal(sign, expectedSign);
});
});
});
describe('sendWithRetry 报文体', () => {
it('发出的报文体恰为 { request: {...} },且不含 event/data/metadata 顶层键', async () => {
await captureConsoleLog(async () => {
let capturedBody = null;
const service = createService({
curlImpl: async (url, options) => {
capturedBody = options.data;
return { status: 200, data: {} };
},
});
const result = await withFastRetryDelay(() => service.sendWithRetry(DEFAULT_OPTIONS));
assert.equal(result.success, true);
assert.deepEqual(capturedBody, { request: { entryOrderId: 543 } });
assert.ok(Object.prototype.hasOwnProperty.call(capturedBody, 'request'));
assert.equal(Object.prototype.hasOwnProperty.call(capturedBody, 'event'), false);
assert.equal(Object.prototype.hasOwnProperty.call(capturedBody, 'data'), false);
assert.equal(Object.prototype.hasOwnProperty.call(capturedBody, 'metadata'), false);
});
});
it('request 缺省时报文体应为 { request: {} }', async () => {
await captureConsoleLog(async () => {
let capturedBody = null;
const service = createService({
curlImpl: async (url, options) => {
capturedBody = options.data;
return { status: 200, data: {} };
},
});
await withFastRetryDelay(() => service.sendWithRetry({
callbackUrl: DEFAULT_OPTIONS.callbackUrl,
appKey: DEFAULT_OPTIONS.appKey,
selfAppSecret: DEFAULT_OPTIONS.selfAppSecret,
event: DEFAULT_OPTIONS.event,
}));
assert.deepEqual(capturedBody, { request: {} });
});
});
it('遗留的 data/metadata 入参应被忽略,不做兼容', async () => {
await captureConsoleLog(async () => {
let capturedBody = null;
const service = createService({
curlImpl: async (url, options) => {
capturedBody = options.data;
return { status: 200, data: {} };
},
});
await withFastRetryDelay(() => service.sendWithRetry({
...DEFAULT_OPTIONS,
data: { legacy: true },
metadata: { legacy: true },
}));
assert.deepEqual(capturedBody, { request: { entryOrderId: 543 } });
assert.equal(Object.prototype.hasOwnProperty.call(capturedBody, 'data'), false);
assert.equal(Object.prototype.hasOwnProperty.call(capturedBody, 'metadata'), false);
});
});
});
describe('sendByAppKey 报文体', () => {
it('经 ApiApp 解析后发出的报文体恰为 { request: {...} },sign 基于新 body 实时重算', async () => {
await captureConsoleLog(async () => {
let capturedUrl = null;
let capturedBody = null;
const service = createService({
apiAppFindOne: async () => ({
self_app_key: 'WMS-TEST-APP-KEY',
self_app_secret: 'test-secret',
callback_url: 'http://callback.example.com/openapi',
}),
curlImpl: async (url, options) => {
capturedUrl = url;
capturedBody = options.data;
return { status: 200, data: {} };
},
});
const result = await withFastRetryDelay(() => service.sendByAppKey({
appKey: 'WMS-TEST-APP-KEY',
event: 'deliveryorder.confirm',
request: { deliveryOrder: { deliveryOrderCode: 'DO-1', status: 'DELIVERED' } },
}));
assert.equal(result.success, true);
assert.deepEqual(capturedBody, {
request: { deliveryOrder: { deliveryOrderCode: 'DO-1', status: 'DELIVERED' } },
});
assert.equal(Object.prototype.hasOwnProperty.call(capturedBody, 'event'), false);
assert.equal(Object.prototype.hasOwnProperty.call(capturedBody, 'data'), false);
assert.equal(Object.prototype.hasOwnProperty.call(capturedBody, 'metadata'), false);
const parsedUrl = new URL(capturedUrl);
assert.ok(parsedUrl.searchParams.get('method') === 'deliveryorder.confirm');
const { sign: expectedSign } = service.signCallback({
event: 'deliveryorder.confirm',
appKey: 'WMS-TEST-APP-KEY',
selfAppSecret: 'test-secret',
body: capturedBody,
timestamp: parsedUrl.searchParams.get('timestamp'),
});
assert.equal(parsedUrl.searchParams.get('sign'), expectedSign);
});
});
it('缺少 appKey 时应返回失败且不访问模型', async () => {
const service = createService();
const result = await service.sendByAppKey({
appKey: ' ',
event: 'deliveryorder.confirm',
request: {},
});
assert.equal(result.success, false);
assert.equal(result.error, '缺少 appKey');
assert.equal(result.retryCount, 0);
assert.equal(result.response, null);
});
it('未找到有效回调配置时应返回失败', async () => {
const service = createService({
apiAppFindOne: async () => null,
});
const result = await service.sendByAppKey({
appKey: 'WMS-TEST-APP-KEY',
event: 'deliveryorder.confirm',
request: {},
});
assert.equal(result.success, false);
assert.equal(result.error, '未找到有效的回调配置');
assert.equal(result.retryCount, 0);
});
});
describe('sendWithRetry 时间戳', () => {
it('timestamp 应为 10 位秒级字符串且与当前服务器秒数一致', async () => {
await captureConsoleLog(async () => {
let capturedUrl = null;
const service = createService({
curlImpl: async url => {
capturedUrl = url;
return { status: 200, data: {} };
},
});
const beforeSeconds = Math.floor(Date.now() / 1000);
await withFastRetryDelay(() => service.sendWithRetry(DEFAULT_OPTIONS));
const afterSeconds = Math.floor(Date.now() / 1000);
assert.ok(capturedUrl, '应捕获到回调 URL');
const timestamp = new URL(capturedUrl).searchParams.get('timestamp');
assert.match(timestamp, /^\d{10}$/, 'timestamp 应为 10 位数字字符串');
const ts = Number(timestamp);
assert.ok(
ts >= beforeSeconds && ts <= afterSeconds,
`timestamp=${ts} 应落在 [${beforeSeconds}, ${afterSeconds}] 区间内(秒级)`
);
});
});
});
describe('logCallback 报文输出', () => {
it('成功分支应输出响应报文', async () => {
const records = [];
const service = createService({
loggerImpl: {
info(line) { records.push({ level: 'info', line }); },
warn() {},
error() {},
},
});
await service.logCallback({
appKey: 'WMS-TEST-APP-KEY',
event: 'deliveryorder.confirm',
callbackUrl: 'http://callback.example.com/openapi',
success: true,
retryCount: 0,
response: { ok: true },
});
assert.equal(records.length, 1);
assert.equal(records[0].level, 'info');
assert.match(records[0].line, /response=\{"ok":true\}/);
});
it('末次重试失败分支应输出报文与错误信息', async () => {
const records = [];
const service = createService({
loggerImpl: {
info() {},
warn() {},
error(line) { records.push({ level: 'error', line }); },
},
});
await service.logCallback({
appKey: 'WMS-TEST-APP-KEY',
event: 'deliveryorder.confirm',
callbackUrl: 'http://callback.example.com/openapi',
success: false,
retryCount: 3,
response: 'error body',
error: '回调返回非 2xx 状态码: 400',
});
assert.equal(records.length, 1);
assert.equal(records[0].level, 'error');
assert.match(records[0].line, /response=error body/);
assert.match(records[0].line, /error=回调返回非 2xx 状态码: 400/);
});
});
});