文件
OmniCard/backend/test/modules/nfc/security.test.ts
wikiboss eec259a3a7 feat: 完成全系统30个功能点开发与E2E全链路验收 (8轮调度32个子代理闭环)
- 模块一: 出海案例作品集、博客动态发布、人名发音语音条、RTL阿语多语言切换
- 模块二: AI顾问人设配置、行业术语库润色、RAG切片沙盒调试、流式会话与意向留资卡片
- 模块三: 全球访客雷达大屏、多维加权意向算分、外部CRM对接推送、团队公海池流转
- 模块四: 移动端NFC安全挂失、NFC动态路由规则配置、动态防伪验签、展会制卡Zip批量导出
- 模块五: 组织架构与名片分配、移动端个人中心设置、离职交接与历史线索迁移、安全审计日志
- 模块六: Stripe国际信用卡订阅Webhook、独立二级域名与SSL检测、坐席配额预警、多币种发票
- 模块七: 纸质名片OCR解析入库、国际商务日程RFC 5545 ICS日历、微官网离线SWR预加载、展会实时排行榜大屏
- 模块八: 全球出海SEO OpenGraph元标签注入与社交爬虫探测、30点端到端全链路业务流集成测试套件
2026-09-20 23:47:47 +08:00

280 行
8.4 KiB
TypeScript

import * as fs from 'fs';
import * as path from 'path';
import { CONTROLLER_KEY, getClassMetadata } from '@midwayjs/core';
import { BaseController, CoolCommException, CurdOption } from '@cool-midway/core';
import { NfcDeviceEntity } from '../../../src/modules/nfc/entity/device';
import { NfcSecurityService } from '../../../src/modules/nfc/service/security';
import {
AdminNfcSecurityController,
adminNfcSecurityCurdOption,
} from '../../../src/modules/nfc/controller/admin/security';
/**
* CoolController 元数据(脚本路径解析为异步)
*/
interface CoolControllerMeta {
prefix?: string;
curdOption?: CurdOption;
}
/**
* 等待 CoolController 将 CRUD 配置写入类元数据
*/
async function waitCoolMeta(
target: new (...args: never[]) => unknown
): Promise<CoolControllerMeta> {
const started = Date.now();
while (Date.now() - started < 2000) {
const meta = getClassMetadata(CONTROLLER_KEY, target) as
| CoolControllerMeta
| undefined;
if (meta?.curdOption) {
return meta;
}
await new Promise<void>(resolve => setImmediate(resolve));
}
throw new Error(`${target.name} 的 CoolController 元数据未就绪`);
}
function serviceApiMethods(apis: CurdOption['serviceApis'] = []): string[] {
return apis.map(api => (typeof api === 'string' ? api : api.method));
}
interface DeviceFindWhere {
id?: number;
uid?: string;
}
/**
* 内存 Repository,覆盖 findOneBy / save
*/
class MemoryNfcDeviceRepo {
private data: NfcDeviceEntity[] = [];
private currentId = 1;
constructor(initialData: Array<Partial<NfcDeviceEntity>> = []) {
this.data = initialData.map(item => this.createEntity(item));
if (this.data.length > 0) {
this.currentId = Math.max(...this.data.map(d => Number(d.id) || 0)) + 1;
}
}
private createEntity(item: Partial<NfcDeviceEntity>): NfcDeviceEntity {
const entity = new NfcDeviceEntity();
Object.assign(entity, {
id: item.id || this.currentId++,
createTime: item.createTime || new Date(),
updateTime: new Date(),
...item,
});
return entity;
}
async findOneBy(where: DeviceFindWhere): Promise<NfcDeviceEntity | null> {
const found = this.data.find(item => {
const keys = Object.keys(where) as Array<keyof DeviceFindWhere>;
return keys.every(key => {
const expected = where[key];
return expected === undefined || item[key] === expected;
});
});
return found ? ({ ...found } as NfcDeviceEntity) : null;
}
async save(
entityOrEntities:
| Partial<NfcDeviceEntity>
| Array<Partial<NfcDeviceEntity>>
): Promise<NfcDeviceEntity | NfcDeviceEntity[]> {
if (Array.isArray(entityOrEntities)) {
const savedList: NfcDeviceEntity[] = [];
for (const item of entityOrEntities) {
savedList.push((await this.save(item)) as NfcDeviceEntity);
}
return savedList;
}
const item = entityOrEntities;
if (item.id) {
const index = this.data.findIndex(d => d.id === item.id);
if (index !== -1) {
this.data[index] = {
...this.data[index],
...item,
updateTime: new Date(),
} as NfcDeviceEntity;
return { ...this.data[index] } as NfcDeviceEntity;
}
}
const newEntity = this.createEntity(item);
this.data.push(newEntity);
return { ...newEntity } as NfcDeviceEntity;
}
}
function createService(
seed: Array<Partial<NfcDeviceEntity>> = []
): NfcSecurityService {
const service = new NfcSecurityService();
service.nfcDeviceEntity = new MemoryNfcDeviceRepo(
seed
) as unknown as NfcSecurityService['nfcDeviceEntity'];
return service;
}
function seedDevices(): Array<Partial<NfcDeviceEntity>> {
return [
{
id: 1,
uid: '04:7A:B2:8F:1C:6D:80',
cardId: 1001,
batchNo: 'B2026-01',
material: 'metal',
status: 'active',
sceneMode: 'social',
},
{
id: 2,
uid: '04:11:22:33:44:55:66',
cardId: 2002,
batchNo: 'B2026-01',
material: 'pvc',
status: 'suspended',
sceneMode: 'business',
},
{
id: 3,
uid: '04:AA:BB:CC:DD:EE:FF',
cardId: null,
batchNo: 'B2026-02',
material: 'wood',
status: 'suspended',
sceneMode: 'social',
},
{
id: 4,
uid: '04:00:00:00:00:00:01',
cardId: 4004,
batchNo: 'B2026-03',
material: 'pvc',
status: 'active',
sceneMode: 'business',
},
];
}
describe('T24 NFC 挂失冻结 API (nfc/security)', () => {
describe('1. freeze / unfreeze / reset', () => {
it('active freeze 后 status 为 suspended 且 cardId 不变', async () => {
const service = createService(seedDevices());
const frozen = await service.freeze({ uid: '04:7A:B2:8F:1C:6D:80' });
expect(frozen.status).toBe('suspended');
expect(frozen.cardId).toBe(1001);
expect(frozen.uid).toBe('04:7A:B2:8F:1C:6D:80');
});
it('已是 suspended 的 freeze 应幂等且仍保留 cardId', async () => {
const service = createService(seedDevices());
const frozen = await service.freeze({ id: 2 });
expect(frozen.status).toBe('suspended');
expect(frozen.cardId).toBe(2002);
});
it('unfreeze 有 cardId 时应回到 active', async () => {
const service = createService(seedDevices());
const restored = await service.unfreeze({ uid: '04:11:22:33:44:55:66' });
expect(restored.status).toBe('active');
expect(restored.cardId).toBe(2002);
});
it('unfreeze 无 cardId 时应回到 unbound', async () => {
const service = createService(seedDevices());
const restored = await service.unfreeze({ id: 3 });
expect(restored.status).toBe('unbound');
expect(restored.cardId == null).toBe(true);
});
it('unfreeze 非 suspended 应抛 CoolCommException', async () => {
const service = createService(seedDevices());
await expect(
service.unfreeze({ uid: '04:7A:B2:8F:1C:6D:80' })
).rejects.toThrow(CoolCommException);
});
it('reset 应清空 cardId、status 为 unbound 且 sceneMode 回 business', async () => {
const service = createService(seedDevices());
const reset = await service.reset({ uid: '04:7A:B2:8F:1C:6D:80' });
expect(reset.cardId == null).toBe(true);
expect(reset.status).toBe('unbound');
expect(reset.sceneMode).toBe('business');
});
it('按数字 id 查不到设备时应抛 CoolCommException', async () => {
const service = createService(seedDevices());
await expect(service.freeze({ id: 9999 })).rejects.toThrow(
CoolCommException
);
await expect(service.unfreeze({ id: 9999 })).rejects.toThrow(
CoolCommException
);
await expect(service.reset({ uid: 'not-exist' })).rejects.toThrow(
CoolCommException
);
});
});
describe('2. 后台控制器 /admin/nfc/security', () => {
const controllerFile = path.join(
__dirname,
'../../../src/modules/nfc/controller/admin/security.ts'
);
let meta: CoolControllerMeta;
let option: CurdOption;
beforeAll(async () => {
meta = await waitCoolMeta(AdminNfcSecurityController);
option = meta.curdOption as CurdOption;
});
it('文件路径应符合 /admin/nfc/security 自动路由约定', () => {
expect(fs.existsSync(controllerFile)).toBe(true);
expect(controllerFile.replace(/\\/g, '/')).toMatch(
/modules\/nfc\/controller\/admin\/security\.ts$/
);
});
it('路由前缀应为 /admin/nfc/security', () => {
expect(meta.prefix).toBe('/admin/nfc/security');
});
it('控制器应继承 BaseController,不开标准 CRUD,并绑定实体与服务', () => {
expect(AdminNfcSecurityController.prototype).toBeInstanceOf(
BaseController
);
expect(option.api).toEqual([]);
expect(option.entity).toBe(NfcDeviceEntity);
expect(option.service).toBe(NfcSecurityService);
expect(adminNfcSecurityCurdOption.api).toEqual([]);
expect(adminNfcSecurityCurdOption.entity).toBe(NfcDeviceEntity);
expect(adminNfcSecurityCurdOption.service).toBe(NfcSecurityService);
});
it('应将 freeze / unfreeze / reset 注册为 serviceApis', () => {
const methods = serviceApiMethods(option.serviceApis);
expect(methods).toEqual(['freeze', 'unfreeze', 'reset']);
expect(serviceApiMethods(adminNfcSecurityCurdOption.serviceApis)).toEqual([
'freeze',
'unfreeze',
'reset',
]);
});
});
});