packServer/backend/test/app/controller/admin_file.test.js
liufumingren bde5dc7bad feat(backend): 图片上传接入腾讯云 COS,新增存储管理与未引用清理
- 头像 / 文档图片改由后端校验并转发到 COS,密钥只留在服务端
- 新增 file_records 登记表(迁移 20261123170000),记录对象键、大小、上传者等
- 引用关系实时计算(用户头像 / 文档正文),改删业务数据后状态自动同步
- 新增平台管理「存储管理」页:引用状态与明细、单删、两步清理未引用
- 新增接口 GET /api/web/admin/files、POST /api/web/admin/files/cleanup、
  DELETE /api/web/admin/files/:id(仍被引用默认 409,force 才删)
- COS 目录前缀(COS_DIR_AVATAR / COS_DIR_DOC)、大小上限、清理保护期改为可配置

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-23 16:39:47 +08:00

143 lines
5.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { app, mock, assert } = require('egg-mock/bootstrap');
/** 造一个可用的平台管理员令牌(apiAuth + platformAdmin 都放行) */
function adminToken(user = { id: 1, username: 'admin', nickname: '管理员', status: 1 }) {
mock(app, 'model', {
User: {
async findByPk() {
return { toJSON: () => user };
},
},
});
app.mockService('adminMember', 'isAdmin', async () => true);
return app.createAnonymousContext().service.jwt.signUser(user);
}
describe('test/app/controller/admin_file.test.js', () => {
it('GET /api/web/admin/files:透传分页与引用过滤,返回统计与存储配置', async () => {
const token = adminToken();
let received = null;
app.mockService('fileStorage', 'list', async params => {
received = params;
return {
list: [ { id: 1, key: 'images/docs/a.png', url: 'https://images.example.com/images/docs/a.png', referenced: false, references: [] } ],
total: 1,
page: 2,
pageSize: 10,
stats: { total: 1, totalBytes: 10, referencedCount: 0, referencedBytes: 0, unreferencedCount: 1, unreferencedBytes: 10 },
};
});
app.mockService('fileStorage', 'storageMeta', () => ({
bucket: 'test-bucket-123456',
region: 'ap-guangzhou',
publicUrl: 'https://images.example.com',
maxFileSize: 5242880,
dirs: { avatar: 'images/avatars', doc: 'images/docs' },
cleanupMinAgeHours: 24,
configured: true,
}));
const res = await app.httpRequest()
.get('/api/web/admin/files?page=2&pageSize=10&keyword=a&category=doc&referenced=0')
.set('Authorization', `Bearer ${token}`)
.expect(200);
assert(received.page === 2 && received.pageSize === 10, JSON.stringify(received));
assert(received.keyword === 'a' && received.category === 'doc' && received.referenced === false, JSON.stringify(received));
assert(res.body.data.total === 1 && res.body.data.stats.unreferencedCount === 1, JSON.stringify(res.body));
assert(res.body.data.storage.bucket === 'test-bucket-123456');
});
it('GET /api/web/admin/files:pageSize 超过 100 时收敛到 100', async () => {
const token = adminToken();
let received = null;
app.mockService('fileStorage', 'list', async params => {
received = params;
return { list: [], total: 0, page: 1, pageSize: 100, stats: {} };
});
app.mockService('fileStorage', 'storageMeta', () => ({}));
await app.httpRequest()
.get('/api/web/admin/files?pageSize=9999')
.set('Authorization', `Bearer ${token}`)
.expect(200);
assert(received.pageSize === 100, JSON.stringify(received));
});
it('POST /api/web/admin/files/cleanup:不传 dryRun 时按预览处理', async () => {
const token = adminToken();
let received = null;
app.mockService('fileStorage', 'cleanup', async params => {
received = params;
return { dryRun: params.dryRun, minAgeHours: 24, candidates: 0, bytes: 0, deleted: 0, failed: [], items: [] };
});
const res = await app.httpRequest()
.post('/api/web/admin/files/cleanup')
.set('Authorization', `Bearer ${token}`)
.send({})
.expect(200);
assert(received.dryRun === true, '默认必须是安全的预览模式');
assert(res.body.data.dryRun === true);
});
it('POST /api/web/admin/files/cleanup:dryRun=false 才真删,并透传保护期', async () => {
const token = adminToken();
let received = null;
app.mockService('fileStorage', 'cleanup', async params => {
received = params;
return { dryRun: false, minAgeHours: 6, candidates: 2, bytes: 20, deleted: 2, failed: [], items: [] };
});
const res = await app.httpRequest()
.post('/api/web/admin/files/cleanup')
.set('Authorization', `Bearer ${token}`)
.send({ dryRun: false, minAgeHours: 6, limit: 50 })
.expect(200);
assert(received.dryRun === false && received.minAgeHours === 6 && received.limit === 50, JSON.stringify(received));
assert(res.body.data.deleted === 2);
});
it('DELETE /api/web/admin/files/:id:id 非法 400,force 参数透传', async () => {
const token = adminToken();
await app.httpRequest()
.delete('/api/web/admin/files/abc')
.set('Authorization', `Bearer ${token}`)
.expect(400);
let received = null;
app.mockService('fileStorage', 'remove', async (id, options) => {
received = { id, options };
return { id, key: 'images/docs/a.png' };
});
const res = await app.httpRequest()
.delete('/api/web/admin/files/7?force=1')
.set('Authorization', `Bearer ${token}`)
.expect(200);
assert(received.id === 7 && received.options.force === true, JSON.stringify(received));
assert(res.body.data.key === 'images/docs/a.png');
});
it('非平台管理员访问存储管理接口 → 403', async () => {
const user = { id: 5, username: 'member', status: 1 };
mock(app, 'model', { User: { async findByPk() { return { toJSON: () => user }; } } });
app.mockService('adminMember', 'isAdmin', async () => false);
const token = app.createAnonymousContext().service.jwt.signUser(user);
const res = await app.httpRequest()
.get('/api/web/admin/files')
.set('Authorization', `Bearer ${token}`)
.expect(403);
assert(res.body.status === 'not_platform_admin', JSON.stringify(res.body));
});
});