WMS_MAIN/test/app/model/order_items_factory.test.js
2026-04-17 19:21:57 +08:00

252 lines
8.0 KiB
JavaScript

'use strict';
const assert = require('node:assert/strict');
const { mm } = require('egg-mock/bootstrap');
const createOrderItemsFactory = require('../../../app/model/order_items_factory');
/**
* 构造最小 Sequelize 类型集合。
* @return {Object} Sequelize 类型集合。
*/
function createSequelizeTypes() {
const makeType = sql => ({
toSql() {
return sql;
},
});
const unsignedBigInt = length => {
const type = makeType(`BIGINT(${length})`);
type.UNSIGNED = makeType(`BIGINT(${length}) UNSIGNED`);
return type;
};
return {
STRING: length => makeType(`VARCHAR(${length})`),
BIGINT: unsignedBigInt,
DECIMAL: (precision, scale) => makeType(`DECIMAL(${precision},${scale})`),
TEXT: makeType('TEXT'),
ENUM: (...values) => makeType(`ENUM('${values.join("','")}')`),
DATE: makeType('DATETIME'),
INTEGER: length => makeType(`INT(${length})`),
CHAR: length => makeType(`CHAR(${length})`),
SMALLINT: length => makeType(`SMALLINT(${length})`),
JSON: makeType('JSON'),
literal(value) {
return {
toSql() {
return value;
},
};
},
};
}
/**
* 构造工厂测试所需的最小 OrderItems 模型。
* @return {Object} OrderItems 模型。
*/
function createOrderItemsModel() {
const Sequelize = createSequelizeTypes();
const fakeApp = {
Sequelize,
model: {
define(name, attributes, options) {
return {
name,
tableName: options.tableName,
rawAttributes: attributes,
};
},
},
};
return require('../../../app/model/order_items')(fakeApp);
}
/**
* 构造工厂测试所需的最小应用对象。
* @param {Object} [queryInterfaceOverrides={}] 查询接口覆盖项。
* @return {Object} 最小应用对象。
*/
function createFactoryApp(queryInterfaceOverrides = {}) {
const orderItemsModel = createOrderItemsModel();
return {
Sequelize: createSequelizeTypes(),
model: {
OrderItems: orderItemsModel,
define(name, attributes, options) {
return {
name,
tableName: options.tableName,
rawAttributes: attributes,
sync: async () => {},
hasMany() {},
belongsTo() {},
};
},
getQueryInterface() {
return {
describeTable: async () => ({}),
showIndex: async () => [],
...queryInterfaceOverrides,
};
},
query: async () => [[]],
},
logger: {
info() {},
warn() {},
error() {},
},
_shardWarehouseIdsValidated: new Set(),
};
}
/**
* 将属性定义转换为 describeTable 兼容结果。
* @param {Object} attributes 属性定义。
* @return {Object} describeTable 兼容结果。
*/
function buildDescribeTableResult(attributes) {
return Object.entries(attributes).reduce((result, [ columnName, attribute ]) => {
result[columnName] = {
type: attribute.type && typeof attribute.type.toSql === 'function'
? attribute.type.toSql()
: String(attribute.type || ''),
allowNull: attribute.allowNull !== false,
};
if (Object.prototype.hasOwnProperty.call(attribute, 'defaultValue')) {
result[columnName].defaultValue = attribute.defaultValue;
}
return result;
}, {});
}
/**
* 将索引定义转换为 showIndex 兼容结果。
* @param {Array<Object>} indexes 索引定义。
* @return {Array<Object>} showIndex 兼容结果。
*/
function buildShowIndexResult(indexes) {
return indexes.map(index => ({
Key_name: index.name,
unique: Boolean(index.unique),
nonUnique: index.unique ? 0 : 1,
fields: Array.isArray(index.fields)
? index.fields.map(field => {
if (typeof field === 'string') {
return {
attribute: field,
};
}
return {
attribute: field.attribute || field.name || field.field || field.columnName,
length: field.length,
};
})
: [],
}));
}
describe('test/app/model/order_items_factory.test.js', () => {
afterEach(() => {
mm.restore();
});
it('should keep schema in sync when current table matches the model', async () => {
const factory = createOrderItemsFactory(createFactoryApp());
const tableAttributes = factory.getTableAttributes('current');
const describeTableResult = buildDescribeTableResult(tableAttributes);
const showIndexResult = buildShowIndexResult(factory.generateIndexes(100000));
mm(factory, 'checkTableExists', async () => true);
mm(factory.app.model, 'getQueryInterface', () => ({
describeTable: async () => describeTableResult,
showIndex: async () => showIndexResult,
}));
assert.equal(await factory.needsTableSchemaSync('wms_order_items_100000', 'current', 100000, true), false);
});
it('should sync and cache dynamic model when schema is inconsistent', async () => {
const factory = createOrderItemsFactory(createFactoryApp());
const tableName = factory.generateTableName(100000, 'current');
const describeTableResult = buildDescribeTableResult(factory.getTableAttributes('current'));
const showIndexResult = buildShowIndexResult(factory.generateIndexes(100000));
delete describeTableResult.item_code;
let syncCalls = 0;
mm(factory, 'checkTableExists', async () => true);
mm(factory.app.model, 'getQueryInterface', () => ({
describeTable: async () => describeTableResult,
showIndex: async () => showIndexResult,
}));
mm(factory.app.model, 'define', (name, attributes, options) => ({
name,
tableName: options.tableName,
rawAttributes: attributes,
sync: async () => {
syncCalls += 1;
},
hasMany() {},
belongsTo() {},
}));
const model = await factory.getOrCreateModel(100000, 'current');
assert.equal(model.tableName, tableName);
assert.equal(syncCalls, 1);
assert.strictEqual(await factory.getOrCreateModel(100000, 'current'), model);
assert.equal(syncCalls, 1);
});
it('should clear model cache and shard validation cache together', () => {
const factory = createOrderItemsFactory(createFactoryApp());
factory.modelCache.set('100000_current', {});
factory.creatingTables.set('100000_current', Promise.resolve());
factory.app._shardWarehouseIdsValidated.add('100000');
factory.clearCache(100000, 'current');
assert.equal(factory.modelCache.has('100000_current'), false);
assert.equal(factory.creatingTables.has('100000_current'), false);
assert.equal(factory.app._shardWarehouseIdsValidated.size, 0);
});
it('should add archive_time to history attributes', () => {
const factory = createOrderItemsFactory(createFactoryApp());
const historyAttributes = factory.getTableAttributes('history');
assert.ok(historyAttributes.archive_time);
assert.equal(typeof historyAttributes.archive_time.type.toSql, 'function');
});
it('should expose new order item snapshot fields in table attributes and indexes', () => {
const factory = createOrderItemsFactory(createFactoryApp());
const currentAttributes = factory.getTableAttributes('current');
const indexes = factory.generateIndexes(100000);
assert.ok(currentAttributes.item_snapshot, '应包含 item_snapshot 字段');
assert.equal(currentAttributes.storage_id, undefined, '不应包含 storage_id 字段');
assert.equal(currentAttributes.space_id, undefined, '不应包含 space_id 字段');
assert.equal(currentAttributes.stock_snapshot, undefined, '不应包含 stock_snapshot 字段');
assert.equal(indexes.some(index => index.name === 'idx_100000_storage_id'), false);
assert.equal(indexes.some(index => index.name === 'idx_100000_space_id'), false);
});
it('should create and cache dispatch model with dispatch table name', async () => {
const factory = createOrderItemsFactory(createFactoryApp());
const model = await factory.getOrCreateModel(100000, 'dispatch');
assert.equal(model.tableName, 'wms_order_items_100000_dispatch');
assert.strictEqual(await factory.getOrCreateModel(100000, 'dispatch'), model);
});
});