'use strict'; const { app, mock, assert } = require('egg-mock/bootstrap'); function configureCos() { const config = app.config.cos; mock(config, 'secretId', 'test-secret-id'); mock(config, 'secretKey', 'test-secret-key'); mock(config, 'bucket', 'test-bucket-123456'); mock(config, 'region', 'ap-guangzhou'); mock(config, 'publicUrl', 'https://images.example.com'); mock(config, 'cleanupMinAgeHours', 24); } /** * 文件登记 / 引用判定 / 清理 * * 用假 `app.model.query` 模拟 SQL 结果:重点验证查询分支与「引用保护」逻辑, * 不依赖真实 MySQL。 */ describe('test/app/service/file_storage.test.js', () => { it('上传后登记一行,并返回访问地址与上传者快照', async () => { configureCos(); let inserted = null; mock(app, 'cosClient', { async putObject(options) { this.uploaded = options; }, }); mock(app, 'model', { async query(sql, options) { if (sql.startsWith('INSERT INTO file_records')) { inserted = options.replacements; return [ 9, 1 ]; } throw new Error(`unexpected sql: ${sql}`); }, }); const result = await app.createAnonymousContext().service.fileStorage.uploadObject({ key: 'images/docs/a.png', body: Buffer.from('89504e470d0a1a0a', 'hex'), contentType: 'image/png', filename: 'a.png', category: 'doc', uploader: { id: 17, nickname: '小林' }, }); assert(inserted.key === 'images/docs/a.png' && inserted.uploaderId === 17, JSON.stringify(inserted)); assert(inserted.uploaderName === '小林' && inserted.size === 8, JSON.stringify(inserted)); assert(result.id === 9 && result.url === 'https://images.example.com/images/docs/a.png'); assert(app.cosClient.uploaded.Bucket === 'test-bucket-123456'); }); it('COS 凭证缺失时上传返回可读的 503', async () => { configureCos(); mock(app.config.cos, 'secretId', ''); let error = null; try { await app.createAnonymousContext().service.fileStorage.uploadObject({ key: 'images/docs/a.png', body: Buffer.from('x'), contentType: 'image/png', filename: 'a.png', category: 'doc', }); } catch (err) { error = err; } assert(error && error.status === 503 && error.expose, '缺少凭证要给运维看得见的错误'); }); it('列表按引用条件分页,并给出引用明细与统计', async () => { configureCos(); mock(app, 'model', { async query(sql) { // 统计 SQL 里也带引用子查询(含 users / doc_articles),必须先判断 if (sql.includes('AS total_bytes')) { return [ [{ total: 2, total_bytes: 150, referenced_count: 1, referenced_bytes: 100 }], [] ]; } if (sql.includes('COUNT(*) AS total FROM file_records f')) return [ [{ total: 2 }], [] ]; if (sql.includes('ORDER BY f.id DESC')) { return [ [ { id: 2, object_key: 'images/docs/used.png', url: 'https://images.example.com/images/docs/used.png', file_name: 'used.png', size: 100, mime_type: 'image/png', category: 'doc', uploader_id: 17, uploader_name: '小林', created_at: new Date('2026-11-20T02:00:00Z'), referenced: 1 }, { id: 1, object_key: 'images/docs/orphan.png', url: 'https://images.example.com/images/docs/orphan.png', file_name: 'orphan.png', size: 50, mime_type: 'image/png', category: 'doc', uploader_id: null, uploader_name: '', created_at: new Date('2026-11-20T01:00:00Z'), referenced: 0 }, ], [] ]; } if (sql.includes('FROM users u')) { return [ [{ id: 17, username: 'lin', nickname: '小林', avatar: 'https://images.example.com/images/docs/used.png' }], [] ]; } if (sql.includes('FROM doc_articles d')) { return [ [{ id: 3, title: '快速开始', content: '![x](https://images.example.com/images/docs/used.png)' }], [] ]; } throw new Error(`unexpected sql: ${sql}`); }, }); const data = await app.createAnonymousContext().service.fileStorage.list({ page: 1, pageSize: 20 }); assert(data.total === 2 && data.list.length === 2, JSON.stringify(data)); const [ used, orphan ] = data.list; assert(used.referenced === true && used.references.length === 2, JSON.stringify(used)); assert(used.references.some(item => item.type === 'avatar') && used.references.some(item => item.type === 'doc')); assert(orphan.referenced === false && orphan.references.length === 0); assert(data.stats.unreferencedCount === 1 && data.stats.unreferencedBytes === 50, JSON.stringify(data.stats)); }); it('未引用过滤:referenced=false 时 SQL 带 NOT EXISTS 条件', async () => { configureCos(); const sqls = []; mock(app, 'model', { async query(sql) { sqls.push(sql); if (sql.includes('AS total_bytes')) { return [ [{ total: 0, total_bytes: 0, referenced_count: 0, referenced_bytes: 0 }], [] ]; } if (sql.includes('COUNT(*) AS total FROM file_records f')) return [ [{ total: 0 }], [] ]; if (sql.includes('ORDER BY f.id DESC')) return [ [], [] ]; throw new Error(`unexpected sql: ${sql}`); }, }); await app.createAnonymousContext().service.fileStorage.list({ referenced: false }); assert(sqls.some(sql => sql.includes('AND NOT (EXISTS')), sqls.join('\n---\n')); }); it('删除仍被引用的文件默认拒绝,force 才真删', async () => { configureCos(); const executed = []; let deletedObject = null; mock(app, 'cosClient', { async deleteObject(options) { deletedObject = options.Key; }, }); mock(app, 'model', { async query(sql, options) { executed.push(sql); if (sql.includes('WHERE f.id = :id')) { return [ [{ id: 5, object_key: 'images/docs/a.png', url: 'https://images.example.com/images/docs/a.png', referenced: 1 }], [] ]; } if (sql.startsWith('DELETE FROM file_records')) return [ { affectedRows: 1 }, [] ]; throw new Error(`unexpected sql: ${sql}`); }, }); const ctx = app.createAnonymousContext(); let error = null; try { await ctx.service.fileStorage.remove(5); } catch (err) { error = err; } assert(error && error.status === 409, '有引用时必须拒绝'); assert(deletedObject === null, '拒绝时不能动 COS'); const result = await ctx.service.fileStorage.remove(5, { force: true }); assert(result.key === 'images/docs/a.png' && deletedObject === 'images/docs/a.png'); assert(executed.some(sql => sql.startsWith('DELETE FROM file_records')), 'force 时应删登记行'); }); it('清理:dryRun 只给清单,执行时才删 COS 与登记行', async () => { configureCos(); const deletedKeys = []; const deletedRows = []; mock(app, 'cosClient', { async deleteObject(options) { deletedKeys.push(options.Key); }, }); mock(app, 'model', { async query(sql, options) { if (sql.includes('f.created_at < :cutoff')) { return [ [ { id: 11, object_key: 'images/docs/a.png', url: 'https://images.example.com/images/docs/a.png', file_name: 'a.png', size: 10, created_at: new Date('2026-11-01T00:00:00Z') }, ], [] ]; } if (sql.startsWith('DELETE FROM file_records')) { deletedRows.push(options.replacements.id); return [ { affectedRows: 1 }, [] ]; } throw new Error(`unexpected sql: ${sql}`); }, }); const ctx = app.createAnonymousContext(); const preview = await ctx.service.fileStorage.cleanup({ dryRun: true }); assert(preview.dryRun === true && preview.candidates === 1 && preview.bytes === 10, JSON.stringify(preview)); assert(deletedKeys.length === 0 && deletedRows.length === 0, 'dryRun 不能产生删除'); const result = await ctx.service.fileStorage.cleanup({ dryRun: false, minAgeHours: 1 }); assert(result.deleted === 1 && result.failed.length === 0, JSON.stringify(result)); assert(deletedKeys[0] === 'images/docs/a.png' && deletedRows[0] === 11); }); it('清理时单个文件失败不影响其余文件', async () => { configureCos(); mock(app, 'cosClient', { async deleteObject(options) { if (options.Key.endsWith('bad.png')) throw new Error('COS 500'); }, }); mock(app, 'model', { async query(sql, options) { if (sql.includes('f.created_at < :cutoff')) { return [ [ { id: 1, object_key: 'images/docs/bad.png', url: 'u1', file_name: 'bad.png', size: 1, created_at: new Date('2026-11-01T00:00:00Z') }, { id: 2, object_key: 'images/docs/ok.png', url: 'u2', file_name: 'ok.png', size: 2, created_at: new Date('2026-11-01T00:00:00Z') }, ], [] ]; } if (sql.startsWith('DELETE FROM file_records')) return [ { affectedRows: 1 }, [] ]; throw new Error(`unexpected sql: ${sql}`); }, }); const result = await app.createAnonymousContext().service.fileStorage.cleanup({ dryRun: false }); assert(result.deleted === 1 && result.failed.length === 1, JSON.stringify(result)); assert(result.failed[0].key === 'images/docs/bad.png'); }); });