import { INestApplication } from '@nestjs/common'; import Ajv2020 from 'ajv/dist/2020'; import { randomUUID } from 'crypto'; import request from 'supertest'; import { PrismaService } from '../src/db/prisma.service'; import { loadDocument } from '../src/docs/swagger'; import { basic, bearer, createTestApp, PASSWORD, processAttachment, registerUser, TestUser, } from './helpers'; import { jpeg, SAMPLE_PNG } from './images'; const CONTRACT_ID = 'https://contract.local/openapi.json'; describe('Все ответы соответствуют контракту: коды, схемы, заголовки (e2e)', () => { let app: INestApplication; let server: any; let alice: TestUser; let bob: TestUser; let eve: TestUser; const document: any = loadDocument(); const ajv = new Ajv2020({ strict: false, validateFormats: false }); ajv.addSchema(document, CONTRACT_ID); const covered = new Set(); const call = async ( method: 'get' | 'post' | 'delete', template: string, values: Record, expected: number, { user, auth, query = '', body, raw, type, headers = {}, }: { user?: TestUser | null; auth?: string; query?: string; body?: unknown; raw?: Buffer | string; type?: string; headers?: Record; } = {}, ) => { const path = template.replace(/\{(\w+)\}/g, (_, name) => values[name]); let req = request(server)[method](path + query).buffer(true).parse(binaryParser); if (user) { req = req.set('Authorization', bearer(user)); } if (auth) { req = req.set('Authorization', auth); } for (const [name, value] of Object.entries(headers)) { req = req.set(name, value); } if (type) { req = req.set('Content-Type', type); } const res = raw !== undefined ? await req.send(raw) : body !== undefined ? await req.send(body as object) : await req; const operation = document.paths[template][method]; const label = `${method.toUpperCase()} ${template} -> ${res.status}`; expect({ label, status: res.status }).toEqual({ label, status: expected }); expect({ label, declared: String(res.status) in operation.responses }).toEqual({ label, declared: true }); expect({ label, requestId: Boolean(res.headers['x-request-id']) }).toEqual({ label, requestId: true }); expect({ label, instanceId: Boolean(res.headers['x-instance-id']) }).toEqual({ label, instanceId: true }); const declared = operation.responses[String(res.status)]; const content = declared.content ?? {}; const type_ = (res.headers['content-type'] ?? '').split(';')[0]; if (res.status === 204) { expect({ label, length: res.body.length }).toEqual({ label, length: 0 }); } else if (content['application/json']) { expect({ label, type: type_ }).toEqual({ label, type: 'application/json' }); const json = JSON.parse(res.body.toString('utf8')); const schema = content['application/json'].schema; const validate = ajv.compile(schema.$ref ? { $ref: CONTRACT_ID + schema.$ref } : schema); const valid = validate(json); expect({ label, valid, errors: validate.errors }).toEqual({ label, valid: true, errors: null }); if (json && typeof json === 'object' && 'error' in json) { expect({ label, same: json.error.request_id === res.headers['x-request-id'] }).toEqual({ label, same: true }); } } else { expect({ label, type: Object.keys(content).includes(type_) }).toEqual({ label, type: true }); } covered.add(label); return res.status === 204 || !content['application/json'] ? res.body : JSON.parse(res.body.toString('utf8')); }; beforeAll(async () => { ({ app, server } = await createTestApp()); alice = await registerUser(server, 'ct_alice'); bob = await registerUser(server, 'ct_bob'); eve = await registerUser(server, 'ct_eve'); }); afterAll(async () => { await app.close(); }); it('health, пользователи и сессии', async () => { await call('get', '/health/live', {}, 200); await call('get', '/health/ready', {}, 200); const username = `ct_${randomUUID().slice(0, 8)}`; await call('post', '/api/v1/users', {}, 201, { body: { username, display_name: 'C', password: PASSWORD } }); await call('post', '/api/v1/users', {}, 409, { body: { username, display_name: 'C', password: PASSWORD } }); await call('post', '/api/v1/users', {}, 400, { body: { username: 'BAD NAME', display_name: 'C', password: PASSWORD } }); await call('post', '/api/v1/users', {}, 400, { raw: '{bad', type: 'application/json' }); await call('post', '/api/v1/auth/sessions', {}, 201, { auth: basic(username, PASSWORD) }); await call('post', '/api/v1/auth/sessions', {}, 401, { auth: basic(username, 'wrong-password-123') }); await call('post', '/api/v1/auth/sessions', {}, 400, { auth: basic(username, PASSWORD), body: { username }, }); await call('get', '/api/v1/users/me', {}, 200, { user: alice }); await call('get', '/api/v1/users/me', {}, 401); await call('get', '/api/v1/users/me', {}, 401, { auth: basic(username, PASSWORD) }); const temp = await registerUser(server, 'ct_tmp'); await call('delete', '/api/v1/auth/sessions/current', {}, 204, { user: temp }); await call('delete', '/api/v1/auth/sessions/current', {}, 401, { user: temp }); }); it('чаты и сообщения', async () => { const chat = await call('post', '/api/v1/chats', {}, 201, { user: alice, body: { title: 'Contract', member_ids: [alice.id, bob.id] }, }); await call('post', '/api/v1/chats', {}, 400, { user: alice, body: { title: 'x', member_ids: [bob.id] } }); await call('post', '/api/v1/chats', {}, 401, { body: { title: 'x', member_ids: [] } }); await call('get', '/api/v1/chats', {}, 200, { user: bob, query: '?limit=1' }); await call('get', '/api/v1/chats', {}, 400, { user: bob, query: '?limit=0' }); await call('get', '/api/v1/chats', {}, 400, { user: bob, query: '?cursor=garbage' }); const ids = { chat_id: chat.id }; await call('get', '/api/v1/chats/{chat_id}', ids, 200, { user: bob }); await call('get', '/api/v1/chats/{chat_id}', ids, 404, { user: eve }); await call('get', '/api/v1/chats/{chat_id}', { chat_id: 'nope' }, 400, { user: bob }); const key = randomUUID(); const send = (status: number, body: unknown, user: TestUser = alice, idem: string | null = randomUUID()) => call('post', '/api/v1/chats/{chat_id}/messages', ids, status, { user, body, headers: idem ? { 'Idempotency-Key': idem } : {}, }); await send(201, { text: 'привет' }, alice, key); await send(201, { text: 'привет' }, alice, key); await send(201, { text: 'второе' }, bob); await send(409, { text: 'другое' }, alice, key); await send(400, { text: 'без ключа' }, alice, null); await send(400, { text: '' }); await send(400, { text: 'x', sender_id: alice.id }); await send(404, { text: 'x' }, eve); await send(404, { text: 'x', attachment_ids: [randomUUID()] }); const page = await call('get', '/api/v1/chats/{chat_id}/messages', ids, 200, { user: bob, query: '?limit=1' }); await call('get', '/api/v1/chats/{chat_id}/messages', ids, 200, { user: bob, query: `?limit=1&cursor=${encodeURIComponent(page.next_cursor)}`, }); await call('get', '/api/v1/chats/{chat_id}/messages', ids, 400, { user: bob, query: '?limit=101' }); await call('get', '/api/v1/chats/{chat_id}/messages', ids, 404, { user: eve }); }); it('вложения во всех состояниях', async () => { const chat = await call('post', '/api/v1/chats', {}, 201, { user: alice, body: { title: 'Files', member_ids: [alice.id, bob.id] }, }); const ids = { chat_id: chat.id }; const upload = (status: number, body: Buffer, type = 'image/png', query = '?filename=a.png', user: TestUser | null = alice) => call('post', '/api/v1/chats/{chat_id}/attachments', ids, status, { user, raw: body, type, query }); const queued = await upload(202, SAMPLE_PNG); expect(queued.status).toBe('queued'); await upload(202, await jpeg(), 'image/jpeg'); await upload(400, SAMPLE_PNG, 'image/png', '?filename=../a.png'); await upload(415, SAMPLE_PNG, 'image/jpeg'); await upload(415, Buffer.from('text'), 'text/plain'); await upload(413, Buffer.alloc(10 * 1024 * 1024 + 1), 'image/png'); await upload(404, SAMPLE_PNG, 'image/png', '?filename=a.png', eve); await upload(401, SAMPLE_PNG, 'image/png', '?filename=a.png', null); const one = { attachment_id: queued.id }; const meta = '/api/v1/attachments/{attachment_id}'; const content = '/api/v1/attachments/{attachment_id}/content'; expect((await call('get', meta, one, 200, { user: bob })).status).toBe('queued'); await call('get', content, one, 409, { user: bob }); await call('get', content, one, 409, { user: bob, query: '?variant=thumbnail' }); await call('post', '/api/v1/chats/{chat_id}/messages', ids, 201, { user: alice, body: { text: '', attachment_ids: [queued.id] }, headers: { 'Idempotency-Key': randomUUID() }, }); expect(await processAttachment(app, queued.id)).toBe('ready'); const ready = await call('get', meta, one, 200, { user: bob }); expect(ready.variants.map((v: any) => v.name)).toEqual(['thumbnail', 'crop', 'optimized']); for (const variant of ['', '?variant=original', '?variant=thumbnail', '?variant=crop', '?variant=optimized']) { await call('get', content, one, 200, { user: bob, query: variant }); } await call('get', content, one, 400, { user: bob, query: '?variant=huge' }); await call('get', content, one, 404, { user: eve }); await call('get', meta, one, 404, { user: eve }); await call('get', meta, { attachment_id: 'nope' }, 400, { user: bob }); await call('get', meta, one, 401); const broken = await upload(202, SAMPLE_PNG); const prisma = app.get(PrismaService); await prisma.attachmentJob.updateMany({ where: { attachmentId: broken.id }, data: { maxAttempts: 1 } }); await prisma.attachment.update({ where: { id: broken.id }, data: { sha256: 'f'.repeat(64) } }); expect(await processAttachment(app, broken.id)).toBe('failed'); const failed = await call('get', meta, { attachment_id: broken.id }, 200, { user: bob }); expect(failed).toMatchObject({ status: 'failed', error_code: 'checksum_mismatch', variants: [] }); await call('get', content, { attachment_id: broken.id }, 409, { user: bob }); await call('post', '/api/v1/chats/{chat_id}/messages', ids, 409, { user: alice, body: { text: '', attachment_ids: [broken.id] }, headers: { 'Idempotency-Key': randomUUID() }, }); }); it('каждая операция контракта вызвана хотя бы раз', () => { const operations = Object.entries(document.paths).flatMap(([path, ops]: [string, any]) => Object.keys(ops) .filter((method) => ['get', 'post', 'delete'].includes(method)) .map((method) => `${method.toUpperCase()} ${path}`), ); const called = new Set([...covered].map((label) => label.split(' -> ')[0])); expect(operations.filter((operation) => !called.has(operation))).toEqual([]); }); }); function binaryParser(res: any, done: (error: Error | null, body: Buffer) => void): void { const chunks: Buffer[] = []; res.on('data', (chunk: Buffer) => chunks.push(chunk)); res.on('end', () => done(null, Buffer.concat(chunks))); }