import fs from 'node:fs'; import path from 'node:path'; import request from 'supertest'; import { describe, expect, it, beforeAll, afterAll } from 'vitest'; import { createApp } from '../src/app.js'; import { env } from '../src/config/env.js'; import { User, hashPassword } from '../src/models/user.model.js'; import { signUserToken } from '../src/utils/jwt.js'; const app = createApp(); const TEST_EMAIL = 'upload-test@example.com'; let authToken = ''; const uploadedFiles: string[] = []; beforeAll(async () => { // Убеждаемся что uploadDir существует if (!fs.existsSync(env.uploadDir)) { fs.mkdirSync(env.uploadDir, { recursive: true }); } const user = await User.create({ email: TEST_EMAIL, passwordHash: await hashPassword('Upload-Pass-123'), }); authToken = signUserToken(user.id); }); afterAll(() => { // Удаляем загруженные тестовые файлы for (const file of uploadedFiles) { const filePath = path.join(env.uploadDir, file); if (fs.existsSync(filePath)) { fs.unlinkSync(filePath); } } }); /** Запоминает файл для последующей очистки. */ function trackFile(name: string): void { uploadedFiles.push(name); } /** Создаёт маленький PNG-файл (1x1 пиксель). */ function createTestPng(): Buffer { return Buffer.from( '89504e470d0a1a0a0000000d4948445200000001000000010802000000907753' + 'de0000000c4944415408d763f8cfc0f0000000050001b5f73564000000004945' + '4e44ae426082', 'hex', ); } describe('Загрузка файлов', () => { it('POST /api/uploads без токена — 401', async () => { const png = createTestPng(); const res = await request(app) .post('/api/uploads') .attach('file', png, 'test.png'); expect(res.status).toBe(401); }); it('успешная загрузка PNG', async () => { const png = createTestPng(); const res = await request(app) .post('/api/uploads') .set('Authorization', `Bearer ${authToken}`) .attach('file', png, 'test.png'); expect(res.status).toBe(201); expect(res.body.file.name).toBeDefined(); expect(res.body.file.url).toBe(`/uploads/${res.body.file.name}`); expect(res.body.file.name).toMatch(/^[0-9a-f-]{36}\.png$/); trackFile(res.body.file.name); // Файл существует на диске const filePath = path.join(env.uploadDir, res.body.file.name); expect(fs.existsSync(filePath)).toBe(true); }); it('загрузка PDF', async () => { const pdf = Buffer.from('%PDF-1.4 test'); const res = await request(app) .post('/api/uploads') .set('Authorization', `Bearer ${authToken}`) .attach('file', pdf, 'test.pdf'); expect(res.status).toBe(201); expect(res.body.file.name).toMatch(/\.pdf$/); trackFile(res.body.file.name); }); it('запрещённый MIME — 400', async () => { const exe = Buffer.from('MZ executable content'); const res = await request(app) .post('/api/uploads') .set('Authorization', `Bearer ${authToken}`) .attach('file', exe, 'malware.exe'); expect(res.status).toBe(400); expect(res.body.error.code).toBe('UPLOAD_ERROR'); }); it('без файла — 400', async () => { const res = await request(app) .post('/api/uploads') .set('Authorization', `Bearer ${authToken}`); expect(res.status).toBe(400); expect(res.body.error.code).toBe('NO_FILE'); }); it('GET /uploads/ отдаёт файл', async () => { const png = createTestPng(); const uploadRes = await request(app) .post('/api/uploads') .set('Authorization', `Bearer ${authToken}`) .attach('file', png, 'static-test.png'); const fileName = uploadRes.body.file.name; trackFile(fileName); const res = await request(app).get(`/uploads/${fileName}`); expect(res.status).toBe(200); expect(res.headers['content-type']).toContain('image/png'); }); });