'use strict'; const { app, assert } = require('egg-mock/bootstrap'); /** * NVR 唯一性只约束「本主体」 * * 现场问题:A 仓库添加过 `192.168.8.242:8000`,B 仓库再加同一个内网地址时被拒绝 * (`NVR 192.168.8.242:8000 已被其他主体添加`)。内网地址在不同仓库之间撞车是正常的, * 唯一键必须是 `(subject_id, host, port, username)`,查重也只能查本主体。 */ describe('test/app/service/nvr-subject-scope.test.js', () => { const SUBJECT_A = 11; const SUBJECT_B = 22; const ADDRESS = { host: '192.168.8.242', port: 8000, username: 'admin' }; function instance(data) { const row = { ...data }; row.toJSON = () => ({ ...row }); row.update = async patch => Object.assign(row, patch); row.restore = async () => { row.deletedAt = null; }; return row; } /** 极简 NVR 表:findOne 按 where 里的 subject_id + host/port/username 过滤,模拟真实唯一键的范围 */ function fakeNvrModel(rows) { const calls = []; return { calls, async findOne({ where }) { calls.push(where); return rows.find(row => Number(row.subjectId) === Number(where.subjectId) && row.host === where.host && Number(row.port) === Number(where.port) && row.username === where.username) || null; }, async findByPk(id) { return rows.find(row => String(row.id) === String(id)) || null; }, async create(values) { const row = instance({ id: rows.length + 101, deletedAt: null, ...values }); rows.push(row); return row; }, }; } function serviceWith(rows) { const service = app.createAnonymousContext().service.nvr; Object.defineProperty(service, 'Nvr', { value: fakeNvrModel(rows), configurable: true }); return service; } it('别的仓库已经用同一个内网地址,本仓库仍然能添加', async () => { const rows = [ instance({ id: 7, subjectId: SUBJECT_A, deletedAt: null, name: 'A仓录像机', ...ADDRESS }) ]; const service = serviceWith(rows); const created = await service.create({ subjectId: SUBJECT_B, userId: 9, password: 'p@ss', ...ADDRESS }); assert(created.subjectId === SUBJECT_B, JSON.stringify(created)); assert(rows.length === 2, '不同主体各存一条,不能被判成冲突'); assert(rows[1].host === ADDRESS.host); }); it('查重只看本主体:where 里必须带 subjectId', async () => { const rows = []; const service = serviceWith(rows); await service.create({ subjectId: SUBJECT_B, userId: 9, password: 'p@ss', ...ADDRESS }); const where = service.Nvr.calls[0]; assert(Number(where.subjectId) === SUBJECT_B, `查重条件必须限定主体:${JSON.stringify(where)}`); }); it('同一个主体重复添加同一台 NVR:更新原记录(含之前软删的)', async () => { const rows = [ instance({ id: 8, subjectId: SUBJECT_B, deletedAt: new Date(), name: '旧名字', ...ADDRESS }) ]; const service = serviceWith(rows); const updated = await service.create({ subjectId: SUBJECT_B, userId: 9, name: '新名字', password: 'p@ss', ...ADDRESS, }); assert(rows.length === 1, '同一主体内不应新增第二条'); assert(rows[0].deletedAt === null, '软删的记录要复活'); assert(updated.name === '新名字', JSON.stringify(updated)); }); });