- 回调 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 等。
454 lines
18 KiB
JavaScript
454 lines
18 KiB
JavaScript
'use strict';
|
||
|
||
/**
|
||
* 回归测试:script/update-api-doc.cjs 新建文档(spec.newDoc)与变更文件自动创建能力。
|
||
*
|
||
* 覆盖:
|
||
* 1. 目标文档不存在 + 未提供 spec.newDoc → 报错文案含 spec.newDoc;
|
||
* 2. 目标文档不存在 + spec.newDoc → 生成骨架(module/description/version/updatedAt/http/headers/methods.groups)
|
||
* 并正确写入 group/methods,changes 自动创建为仅含本次 change 的数组;
|
||
* 3. 目标文档已存在 + spec.newDoc → newDoc 被忽略,结果与不传 newDoc 逐字节一致;
|
||
* 4. changes 文件缺失(文档已存在)→ 自动创建;--doc-only 不创建 changes;
|
||
* 5. --dry-run 不写任何文件(含新建场景),结尾输出 dry-run 提示;
|
||
* 6. --help 输出含 newDoc 说明与示例命令;
|
||
* 7. 新建文件为 2 空格缩进 + LF;未知字段透传;docMeta.version 覆盖骨架 version(缺省 0.0.0)。
|
||
* 8. doc 已存在时 docMeta.description 覆盖根 description(仅字符串生效)。
|
||
*
|
||
* 目录隔离:通过环境变量 WMS_API_DOC_METHODS_DIR / WMS_API_DOC_CHANGES_DIR 注入临时目录,
|
||
* 脚本在模块加载时读取这两个变量(默认值不变,仍为 methods/ 与 methods/changes/)。
|
||
*
|
||
* 运行:node test/scripts/update_api_doc.test.cjs
|
||
*/
|
||
const fs = require('node:fs');
|
||
const os = require('node:os');
|
||
const path = require('node:path');
|
||
const { spawnSync } = require('node:child_process');
|
||
|
||
const { assert, suite, run } = require('../support/mini_test_framework.cjs');
|
||
|
||
const PROJECT_ROOT = path.resolve(__dirname, '..', '..');
|
||
const SCRIPT_PATH = path.join(PROJECT_ROOT, 'script', 'update-api-doc.cjs');
|
||
|
||
// 临时目录 + 环境注入:必须在 require 脚本前设置(脚本在模块加载时读取目录常量)
|
||
const TMP_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), 'wms-update-api-doc-'));
|
||
const TMP_METHODS_DIR = path.join(TMP_ROOT, 'methods');
|
||
const TMP_CHANGES_DIR = path.join(TMP_METHODS_DIR, 'changes');
|
||
fs.mkdirSync(TMP_CHANGES_DIR, { recursive: true });
|
||
|
||
process.env.WMS_API_DOC_METHODS_DIR = TMP_METHODS_DIR;
|
||
process.env.WMS_API_DOC_CHANGES_DIR = TMP_CHANGES_DIR;
|
||
|
||
const { buildNewDoc, validateNewDoc, validateSpec } = require('../../script/update-api-doc.cjs');
|
||
|
||
/**
|
||
* 生成一份最小合法 spec(doc 不存在场景可再传 newDoc)
|
||
* @param {object} options 配置项
|
||
* @param {string} [options.docName] 文档名,默认 sample
|
||
* @param {object} [options.newDoc] 新建骨架配置(默认不传)
|
||
* @param {object} [options.docMeta] 文档元信息(默认 {})
|
||
* @param {object} [options.change] 变更记录(默认内置示例)
|
||
* @return {object} 更新 spec 对象
|
||
*/
|
||
function buildSpec({ docName = 'sample', newDoc = null, docMeta = {}, change = null } = {}) {
|
||
const spec = {
|
||
docName,
|
||
docMeta,
|
||
group: { groupName: '示例分组', module: 'sample' },
|
||
methods: [
|
||
{
|
||
method: 'sample.echo',
|
||
description: '示例方法',
|
||
isNeedAuth: true,
|
||
isNeedLogin: true,
|
||
headers: [],
|
||
params: [
|
||
{ name: 'name', type: 'string', required: true, source: 'body', description: '名称' },
|
||
],
|
||
response: [
|
||
{ name: 'ok', type: 'boolean', required: true, description: '是否成功' },
|
||
],
|
||
errors: [
|
||
{ code: 400, message: '参数错误' },
|
||
],
|
||
},
|
||
],
|
||
change: change || {
|
||
version: '2026.09.12-sample',
|
||
date: '2026-09-12',
|
||
summary: '示例变更',
|
||
methods: [ 'sample.echo' ],
|
||
notes: [ '示例说明' ],
|
||
},
|
||
};
|
||
if (newDoc) spec.newDoc = newDoc;
|
||
return spec;
|
||
}
|
||
|
||
/**
|
||
* 生成一份最小合法既有文档内容(methods/<docName>.json 形状)
|
||
* @return {object} 既有文档对象
|
||
*/
|
||
function buildExistingDoc() {
|
||
return {
|
||
module: 'existing',
|
||
description: '已存在文档',
|
||
version: '3.0.0',
|
||
updatedAt: '2026-01-01',
|
||
http: { path: '/exist', method: 'POST' },
|
||
headers: [],
|
||
methods: { groups: [] },
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 生成一份最小合法既有变更文件内容(methods/changes/<docName>.json 形状)
|
||
* @return {object[]} 既有变更记录数组
|
||
*/
|
||
function buildExistingChanges() {
|
||
return [
|
||
{
|
||
version: '2026.01.01-old',
|
||
date: '2026-01-01',
|
||
summary: '旧记录',
|
||
methods: [],
|
||
notes: [ '旧说明' ],
|
||
},
|
||
];
|
||
}
|
||
|
||
/**
|
||
* 将 spec 写入临时 spec 文件并返回绝对路径
|
||
* @param {string} fileName spec 文件名(写入临时根目录)
|
||
* @param {object} spec spec 对象
|
||
* @return {string} spec 文件绝对路径
|
||
*/
|
||
function writeSpecFile(fileName, spec) {
|
||
const specPath = path.join(TMP_ROOT, fileName);
|
||
fs.writeFileSync(specPath, JSON.stringify(spec, null, 2), 'utf8');
|
||
return specPath;
|
||
}
|
||
|
||
/**
|
||
* 以子进程方式运行脚本(环境变量指向临时目录,工作目录为项目根目录)
|
||
* @param {string[]} args 脚本参数(如 --dry-run)
|
||
* @param {object} options 配置项
|
||
* @param {string} [options.specPath] spec 文件绝对路径(默认不传)
|
||
* @return {object} spawnSync 结果
|
||
*/
|
||
function runCli(args, { specPath } = {}) {
|
||
const argv = [ SCRIPT_PATH, ...args ];
|
||
if (specPath) argv.push(`--spec=${specPath}`);
|
||
return spawnSync(process.execPath, argv, {
|
||
cwd: PROJECT_ROOT,
|
||
env: {
|
||
...process.env,
|
||
WMS_API_DOC_METHODS_DIR: TMP_METHODS_DIR,
|
||
WMS_API_DOC_CHANGES_DIR: TMP_CHANGES_DIR,
|
||
},
|
||
encoding: 'utf8',
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 计算临时目录中目标 doc 文件的绝对路径
|
||
* @param {string} docName 文档名
|
||
* @return {string} doc 文件绝对路径
|
||
*/
|
||
function docPathOf(docName) {
|
||
return path.join(TMP_METHODS_DIR, `${docName}.json`);
|
||
}
|
||
|
||
/**
|
||
* 计算临时目录中目标 change 文件的绝对路径
|
||
* @param {string} docName 文档名
|
||
* @return {string} change 文件绝对路径
|
||
*/
|
||
function changePathOf(docName) {
|
||
return path.join(TMP_CHANGES_DIR, `${docName}.json`);
|
||
}
|
||
|
||
/**
|
||
* 以 2 空格缩进 + LF 写入既有文档文件
|
||
* @param {string} docName 文档名
|
||
* @param {object} doc 文档对象
|
||
*/
|
||
function seedExistingDoc(docName, doc) {
|
||
fs.writeFileSync(docPathOf(docName), JSON.stringify(doc, null, ' '), 'utf8');
|
||
}
|
||
|
||
/**
|
||
* 以 2 空格缩进 + LF 写入既有变更文件
|
||
* @param {string} docName 文档名
|
||
* @param {object[]} changes 变更记录数组
|
||
*/
|
||
function seedExistingChanges(docName, changes) {
|
||
fs.writeFileSync(changePathOf(docName), JSON.stringify(changes, null, ' '), 'utf8');
|
||
}
|
||
|
||
const suites = [];
|
||
|
||
// ==================== 1. validateSpec 与骨架构建(纯函数) ====================
|
||
suites.push(suite('validateSpec / validateNewDoc / buildNewDoc 纯函数', t => {
|
||
t('doc 不存在且未提供 spec.newDoc → 报错文案含 spec.newDoc', () => {
|
||
assert.throws(
|
||
() => validateSpec(buildSpec({ docName: 'missing_newdoc' }), { dryRun: false, docOnly: false }),
|
||
error => error.message.includes('spec.newDoc') && error.message.includes('create it')
|
||
);
|
||
});
|
||
|
||
t('doc 不存在 + spec.newDoc → 校验通过并返回 docExists=false / changeExists=false / newDoc', () => {
|
||
const normalized = validateSpec(
|
||
buildSpec({ docName: 'newdoc_ok', newDoc: { module: 'demo' } }),
|
||
{ dryRun: false, docOnly: false }
|
||
);
|
||
assert.equal(normalized.docExists, false);
|
||
assert.equal(normalized.changeExists, false);
|
||
assert.equal(normalized.newDoc.module, 'demo');
|
||
});
|
||
|
||
t('newDoc 字段校验:module 缺失/空白、http 非对象、headers 非数组、未知字段非 plain JSON 均报错', () => {
|
||
assert.throws(
|
||
() => validateNewDoc({}, 'spec.newDoc'),
|
||
error => error.message.includes('spec.newDoc.module')
|
||
);
|
||
assert.throws(
|
||
() => validateNewDoc({ module: ' ' }, 'spec.newDoc'),
|
||
error => error.message.includes('spec.newDoc.module')
|
||
);
|
||
assert.throws(
|
||
() => validateNewDoc({ module: 'm', http: 'x' }, 'spec.newDoc'),
|
||
error => error.message.includes('spec.newDoc.http')
|
||
);
|
||
assert.throws(
|
||
() => validateNewDoc({ module: 'm', headers: {} }, 'spec.newDoc'),
|
||
error => error.message.includes('spec.newDoc.headers')
|
||
);
|
||
assert.throws(
|
||
() => validateNewDoc({ module: 'm', custom: () => {} }, 'spec.newDoc'),
|
||
error => error.message.includes('spec.newDoc.custom')
|
||
);
|
||
});
|
||
|
||
t('buildNewDoc:仅提供 module 时骨架默认值正确(version 0.0.0 / updatedAt 今天 / http 与 headers 默认)', () => {
|
||
const doc = buildNewDoc({ module: 'demo' }, {});
|
||
assert.equal(doc.module, 'demo');
|
||
assert.equal(doc.description, '');
|
||
assert.equal(doc.version, '0.0.0');
|
||
assert.match(doc.updatedAt, /^\d{4}-\d{2}-\d{2}$/);
|
||
assert.deepEqual(doc.http, { path: '', method: 'POST' });
|
||
assert.deepEqual(doc.headers, []);
|
||
assert.deepEqual(doc.methods, { groups: [] });
|
||
});
|
||
|
||
t('buildNewDoc:docMeta.version/updatedAt 覆盖、未知字段透传、保留键(version/methods)不透传', () => {
|
||
const doc = buildNewDoc(
|
||
{
|
||
module: 'demo',
|
||
description: '描述',
|
||
http: { path: '/x' },
|
||
headers: [{ name: 'Content-Type', type: 'string', required: true, description: 'application/json' }],
|
||
custom: { a: [ 1, null, true ] },
|
||
version: '9.9.9',
|
||
methods: {},
|
||
},
|
||
{ version: '2.0.0', updatedAt: '2026-09-01' }
|
||
);
|
||
assert.equal(doc.version, '2.0.0');
|
||
assert.equal(doc.updatedAt, '2026-09-01');
|
||
assert.equal(doc.description, '描述');
|
||
assert.deepEqual(doc.http, { path: '/x' });
|
||
assert.deepEqual(doc.custom, { a: [ 1, null, true ] });
|
||
assert.deepEqual(doc.methods, { groups: [] });
|
||
});
|
||
}));
|
||
|
||
// ==================== 2. 新建文档与变更文件(子进程正式写入) ====================
|
||
suites.push(suite('新建文档与变更文件(正式写入)', t => {
|
||
t('doc 不存在 + newDoc → 骨架字段与 group/methods 全部正确写入,changes 自动创建', () => {
|
||
const docName = 'created_doc1';
|
||
const specPath = writeSpecFile(`spec-${docName}.json`, buildSpec({
|
||
docName,
|
||
newDoc: {
|
||
module: 'demo_mod',
|
||
description: 'demo desc',
|
||
http: { path: '/demo' },
|
||
headers: [],
|
||
customField: { note: '透传' },
|
||
},
|
||
docMeta: { version: '1.2.3', updatedAt: '2026-09-11' },
|
||
}));
|
||
const result = runCli([], { specPath });
|
||
assert.equal(result.status, 0, result.stderr);
|
||
|
||
assert.ok(fs.existsSync(docPathOf(docName)), result.stdout);
|
||
assert.ok(fs.existsSync(changePathOf(docName)), result.stdout);
|
||
assert.ok(result.stdout.includes('created:'), result.stdout);
|
||
|
||
const rawDoc = fs.readFileSync(docPathOf(docName), 'utf8');
|
||
const doc = JSON.parse(rawDoc);
|
||
assert.equal(doc.module, 'demo_mod');
|
||
assert.equal(doc.description, 'demo desc');
|
||
assert.equal(doc.version, '1.2.3');
|
||
assert.equal(doc.updatedAt, '2026-09-11');
|
||
assert.deepEqual(doc.http, { path: '/demo' });
|
||
assert.deepEqual(doc.customField, { note: '透传' });
|
||
assert.equal(doc.methods.groups.length, 1);
|
||
assert.equal(doc.methods.groups[0].groupName, '示例分组');
|
||
assert.equal(doc.methods.groups[0].module, 'sample');
|
||
assert.equal(doc.methods.groups[0].list.length, 1);
|
||
assert.equal(doc.methods.groups[0].list[0].method, 'sample.echo');
|
||
|
||
const changes = JSON.parse(fs.readFileSync(changePathOf(docName), 'utf8'));
|
||
assert.ok(Array.isArray(changes));
|
||
assert.equal(changes.length, 1);
|
||
assert.equal(changes[0].version, '2026.09.12-sample');
|
||
|
||
// 格式约定:2 空格缩进 + LF(无 CRLF、无 tab)
|
||
assert.ok(!rawDoc.includes('\r\n'), 'doc 应为 LF');
|
||
assert.ok(!rawDoc.includes('\t'), 'doc 缩进不应含 tab');
|
||
assert.match(rawDoc, /\n {2}"module": "demo_mod",/);
|
||
});
|
||
|
||
t('doc 不存在 + newDoc 且无 docMeta → 骨架 version 保持 0.0.0,updatedAt 为今天', () => {
|
||
const docName = 'created_doc2';
|
||
const specPath = writeSpecFile(`spec-${docName}.json`, buildSpec({
|
||
docName,
|
||
newDoc: { module: 'demo_default' },
|
||
}));
|
||
const result = runCli([], { specPath });
|
||
assert.equal(result.status, 0, result.stderr);
|
||
|
||
const doc = JSON.parse(fs.readFileSync(docPathOf(docName), 'utf8'));
|
||
assert.equal(doc.version, '0.0.0');
|
||
assert.match(doc.updatedAt, /^\d{4}-\d{2}-\d{2}$/);
|
||
});
|
||
|
||
t('doc 已存在 + spec.newDoc → newDoc 被忽略,结果与不传 newDoc 逐字节一致', () => {
|
||
const docName = 'existing_doc1';
|
||
seedExistingDoc(docName, buildExistingDoc());
|
||
seedExistingChanges(docName, buildExistingChanges());
|
||
|
||
const specA = buildSpec({ docName });
|
||
const specB = buildSpec({
|
||
docName,
|
||
newDoc: { module: 'IGNORED', description: '不应生效', http: { path: '/x' } },
|
||
});
|
||
const specPathA = writeSpecFile(`spec-${docName}-a.json`, specA);
|
||
const specPathB = writeSpecFile(`spec-${docName}-b.json`, specB);
|
||
|
||
const resultA = runCli([], { specPath: specPathA });
|
||
assert.equal(resultA.status, 0, resultA.stderr);
|
||
const docBytesA = fs.readFileSync(docPathOf(docName));
|
||
const changeBytesA = fs.readFileSync(changePathOf(docName));
|
||
|
||
// 恢复原文件后以带 newDoc 的 spec 再跑一遍
|
||
seedExistingDoc(docName, buildExistingDoc());
|
||
seedExistingChanges(docName, buildExistingChanges());
|
||
const resultB = runCli([], { specPath: specPathB });
|
||
assert.equal(resultB.status, 0, resultB.stderr);
|
||
assert.ok(!resultB.stdout.includes('created:'), resultB.stdout);
|
||
|
||
assert.ok(docBytesA.equals(fs.readFileSync(docPathOf(docName))), 'doc 落盘内容应逐字节一致');
|
||
assert.ok(changeBytesA.equals(fs.readFileSync(changePathOf(docName))), 'changes 落盘内容应逐字节一致');
|
||
assert.equal(JSON.parse(docBytesA.toString()).module, 'existing');
|
||
});
|
||
|
||
t('doc 已存在 + changes 缺失 → changes 自动创建为数组且仅含本次 change', () => {
|
||
const docName = 'existing_doc2';
|
||
seedExistingDoc(docName, buildExistingDoc());
|
||
assert.ok(!fs.existsSync(changePathOf(docName)));
|
||
|
||
const specPath = writeSpecFile(`spec-${docName}.json`, buildSpec({ docName }));
|
||
const result = runCli([], { specPath });
|
||
assert.equal(result.status, 0, result.stderr);
|
||
|
||
assert.ok(fs.existsSync(changePathOf(docName)));
|
||
const changes = JSON.parse(fs.readFileSync(changePathOf(docName), 'utf8'));
|
||
assert.ok(Array.isArray(changes));
|
||
assert.equal(changes.length, 1);
|
||
assert.equal(changes[0].version, '2026.09.12-sample');
|
||
});
|
||
|
||
t('--doc-only + doc 不存在 + newDoc → 只创建 doc,不创建 changes', () => {
|
||
const docName = 'doc_only1';
|
||
const specPath = writeSpecFile(`spec-${docName}.json`, buildSpec({
|
||
docName,
|
||
newDoc: { module: 'demo_only' },
|
||
}));
|
||
const result = runCli([ '--doc-only' ], { specPath });
|
||
assert.equal(result.status, 0, result.stderr);
|
||
|
||
assert.ok(fs.existsSync(docPathOf(docName)));
|
||
assert.ok(!fs.existsSync(changePathOf(docName)));
|
||
});
|
||
|
||
t('doc 已存在 + docMeta.description → 根 description 被覆盖,其余字段不受影响', () => {
|
||
const docName = 'existing_doc3';
|
||
seedExistingDoc(docName, buildExistingDoc());
|
||
seedExistingChanges(docName, buildExistingChanges());
|
||
|
||
const specPath = writeSpecFile(`spec-${docName}.json`, buildSpec({
|
||
docName,
|
||
docMeta: { version: '3.1.0', updatedAt: '2026-09-13', description: '新根描述' },
|
||
}));
|
||
const result = runCli([], { specPath });
|
||
assert.equal(result.status, 0, result.stderr);
|
||
|
||
const doc = JSON.parse(fs.readFileSync(docPathOf(docName), 'utf8'));
|
||
assert.equal(doc.description, '新根描述');
|
||
assert.equal(doc.version, '3.1.0');
|
||
assert.equal(doc.updatedAt, '2026-09-13');
|
||
assert.equal(doc.module, 'existing');
|
||
assert.equal(doc.methods.groups.length, 1);
|
||
});
|
||
}));
|
||
|
||
// ==================== 3. dry-run 与 help ====================
|
||
suites.push(suite('dry-run 与 --help', t => {
|
||
t('--dry-run + 新建场景 → 不写任何文件,输出 created 行与 dry-run 结尾提示', () => {
|
||
const docName = 'dry_new1';
|
||
const specPath = writeSpecFile(`spec-${docName}.json`, buildSpec({
|
||
docName,
|
||
newDoc: { module: 'demo_dry' },
|
||
}));
|
||
const result = runCli([ '--dry-run' ], { specPath });
|
||
assert.equal(result.status, 0, result.stderr);
|
||
assert.ok(result.stdout.includes('created:'), result.stdout);
|
||
assert.ok(
|
||
result.stdout.includes('dry-run: validated successfully, no files were written.'),
|
||
result.stdout
|
||
);
|
||
assert.ok(!fs.existsSync(docPathOf(docName)));
|
||
assert.ok(!fs.existsSync(changePathOf(docName)));
|
||
});
|
||
|
||
t('--dry-run + doc 已存在 → 不修改任何文件', () => {
|
||
const docName = 'dry_exist1';
|
||
seedExistingDoc(docName, buildExistingDoc());
|
||
seedExistingChanges(docName, buildExistingChanges());
|
||
const docBytesBefore = fs.readFileSync(docPathOf(docName));
|
||
const changeBytesBefore = fs.readFileSync(changePathOf(docName));
|
||
|
||
const specPath = writeSpecFile(`spec-${docName}.json`, buildSpec({ docName }));
|
||
const result = runCli([ '--dry-run' ], { specPath });
|
||
assert.equal(result.status, 0, result.stderr);
|
||
assert.ok(!result.stdout.includes('created:'), result.stdout);
|
||
assert.ok(docBytesBefore.equals(fs.readFileSync(docPathOf(docName))));
|
||
assert.ok(changeBytesBefore.equals(fs.readFileSync(changePathOf(docName))));
|
||
});
|
||
|
||
t('--help 输出含 newDoc 字段说明与新建文档示例命令', () => {
|
||
const result = runCli([ '--help' ]);
|
||
assert.equal(result.status, 0, result.stderr);
|
||
assert.ok(result.stdout.includes('spec.newDoc'), result.stdout);
|
||
assert.ok(result.stdout.includes('module'), result.stdout);
|
||
assert.ok(result.stdout.includes('Examples:'), result.stdout);
|
||
assert.ok(result.stdout.includes('api-doc-create.json'), result.stdout);
|
||
});
|
||
}));
|
||
|
||
// 跑完后清理临时目录(测试数据非业务数据,允许删除)
|
||
run(suites).then(() => {
|
||
fs.rmSync(TMP_ROOT, { recursive: true, force: true });
|
||
});
|