forked from mtusi2026/mtusi2026lab6
207 lines
12 KiB
TypeScript
207 lines
12 KiB
TypeScript
import { INestApplication } from '@nestjs/common';
|
||
import { randomUUID } from 'crypto';
|
||
import request from 'supertest';
|
||
import { bearer, createTestApp, PASSWORD, registerUser, TestUser } from './helpers';
|
||
import { SAMPLE_PNG } from './images';
|
||
|
||
type Case = [label: string, run: () => request.Test, expected: number];
|
||
|
||
describe('Каждое ограничение запроса из контракта отклоняется 400, граница принимается (e2e)', () => {
|
||
let app: INestApplication;
|
||
let server: any;
|
||
let alice: TestUser;
|
||
let bob: TestUser;
|
||
let chatId: string;
|
||
let attachmentId: string;
|
||
|
||
beforeAll(async () => {
|
||
({ app, server } = await createTestApp());
|
||
alice = await registerUser(server, 'rc_alice');
|
||
bob = await registerUser(server, 'rc_bob');
|
||
const chat = await request(server)
|
||
.post('/api/v1/chats')
|
||
.set('Authorization', bearer(alice))
|
||
.send({ title: 'Constraints', member_ids: [alice.id, bob.id] })
|
||
.expect(201);
|
||
chatId = chat.body.id;
|
||
const upload = await request(server)
|
||
.post(`/api/v1/chats/${chatId}/attachments?filename=a.png`)
|
||
.set('Authorization', bearer(alice))
|
||
.set('Content-Type', 'image/png')
|
||
.send(SAMPLE_PNG)
|
||
.expect(202);
|
||
attachmentId = upload.body.id;
|
||
});
|
||
|
||
afterAll(async () => {
|
||
await app.close();
|
||
});
|
||
|
||
const check = async (cases: Case[]) => {
|
||
const mismatches: string[] = [];
|
||
for (const [label, run, expected] of cases) {
|
||
const res = await run();
|
||
const okHeaders = Boolean(res.headers['x-request-id'] && res.headers['x-instance-id']);
|
||
const okBody = expected >= 400 ? res.body?.error?.code === 'invalid_request' : true;
|
||
if (res.status !== expected || !okHeaders || !okBody) {
|
||
mismatches.push(`${label}: expected ${expected}, got ${res.status} ${JSON.stringify(res.body).slice(0, 120)}`);
|
||
}
|
||
}
|
||
expect(mismatches).toEqual([]);
|
||
};
|
||
|
||
const emoji = (n: number) => '😀'.repeat(n);
|
||
const user = (body: unknown) => () => request(server).post('/api/v1/users').send(body as object);
|
||
const name = () => `rc_${randomUUID().slice(0, 8)}`;
|
||
const valid = () => ({ username: name(), display_name: 'R', password: PASSWORD });
|
||
|
||
it('POST /users', async () => {
|
||
const drop = (field: string) => {
|
||
const body: any = valid();
|
||
delete body[field];
|
||
return body;
|
||
};
|
||
await check([
|
||
['без username', user(drop('username')), 400],
|
||
['без display_name', user(drop('display_name')), 400],
|
||
['без password', user(drop('password')), 400],
|
||
['username число', user({ ...valid(), username: 123 }), 400],
|
||
['username null', user({ ...valid(), username: null }), 400],
|
||
['display_name массив', user({ ...valid(), display_name: ['a'] }), 400],
|
||
['password число', user({ ...valid(), password: 123456789012 }), 400],
|
||
['лишнее поле', user({ ...valid(), role: 'admin' }), 400],
|
||
['лишнее поле в другом регистре', user({ ...valid(), Username: 'x' }), 400],
|
||
['username 2 символа', user({ ...valid(), username: 'ab' }), 400],
|
||
['username 33 символа', user({ ...valid(), username: 'a'.repeat(33) }), 400],
|
||
['username заглавные', user({ ...valid(), username: 'Alice_' + randomUUID().slice(0, 4) }), 400],
|
||
['username пробел', user({ ...valid(), username: 'al ice' }), 400],
|
||
['username кириллица', user({ ...valid(), username: 'алиса' }), 400],
|
||
['username дефис', user({ ...valid(), username: 'al-ice' }), 400],
|
||
['username 3 символа', user({ ...valid(), username: randomUUID().slice(0, 3).replace(/-/g, '_') }), 201],
|
||
['username 32 символа', user({ ...valid(), username: (name() + '_'.repeat(32)).slice(0, 32) }), 201],
|
||
['display_name пустой', user({ ...valid(), display_name: '' }), 400],
|
||
['display_name пробелы', user({ ...valid(), display_name: ' ' }), 400],
|
||
['display_name 101 code point', user({ ...valid(), display_name: emoji(101) }), 400],
|
||
['display_name 100 code points', user({ ...valid(), display_name: emoji(100) }), 201],
|
||
['password 11', user({ ...valid(), password: 'x'.repeat(11) }), 400],
|
||
['password 129 code points', user({ ...valid(), password: emoji(129) }), 400],
|
||
['password пробелы', user({ ...valid(), password: ' '.repeat(12) }), 400],
|
||
['password 12', user({ ...valid(), password: 'x'.repeat(12) }), 201],
|
||
['password 128 code points', user({ ...valid(), password: emoji(128) }), 201],
|
||
['тело массив', user([valid()]), 400],
|
||
['тело строка', () => request(server).post('/api/v1/users').set('Content-Type', 'application/json').send('"x"'), 400],
|
||
['тело null', () => request(server).post('/api/v1/users').set('Content-Type', 'application/json').send('null'), 400],
|
||
['битый JSON', () => request(server).post('/api/v1/users').set('Content-Type', 'application/json').send('{bad'), 400],
|
||
['мусор после JSON', () => request(server).post('/api/v1/users').set('Content-Type', 'application/json').send(JSON.stringify(valid()) + 'x'), 400],
|
||
['text/plain', () => request(server).post('/api/v1/users').set('Content-Type', 'text/plain').send(JSON.stringify(valid())), 400],
|
||
['без тела', () => request(server).post('/api/v1/users'), 400],
|
||
]);
|
||
});
|
||
|
||
it('POST /chats', async () => {
|
||
const chat = (body: unknown) => () =>
|
||
request(server).post('/api/v1/chats').set('Authorization', bearer(alice)).send(body as object);
|
||
const members = (n: number) => [alice.id, ...Array.from({ length: n - 1 }, () => randomUUID())];
|
||
await check([
|
||
['без title', chat({ member_ids: [alice.id] }), 400],
|
||
['без member_ids', chat({ title: 'x' }), 400],
|
||
['title число', chat({ title: 1, member_ids: [alice.id] }), 400],
|
||
['title пустой', chat({ title: '', member_ids: [alice.id] }), 400],
|
||
['title пробелы', chat({ title: ' ', member_ids: [alice.id] }), 400],
|
||
['title 101 code point', chat({ title: emoji(101), member_ids: [alice.id] }), 400],
|
||
['title 100 code points', chat({ title: emoji(100), member_ids: [alice.id] }), 201],
|
||
['member_ids не массив', chat({ title: 'x', member_ids: alice.id }), 400],
|
||
['member_ids пустой', chat({ title: 'x', member_ids: [] }), 400],
|
||
['member_ids 101', chat({ title: 'x', member_ids: members(101) }), 400],
|
||
['member_ids дубль', chat({ title: 'x', member_ids: [alice.id, alice.id] }), 400],
|
||
['member_ids дубль в другом регистре', chat({ title: 'x', member_ids: [alice.id, alice.id.toUpperCase()] }), 400],
|
||
['member_ids не UUID', chat({ title: 'x', member_ids: [alice.id, 'nope'] }), 400],
|
||
['member_ids число', chat({ title: 'x', member_ids: [alice.id, 1] }), 400],
|
||
['member_ids null', chat({ title: 'x', member_ids: null }), 400],
|
||
['без вызывающего', chat({ title: 'x', member_ids: [bob.id] }), 400],
|
||
['неизвестный участник', chat({ title: 'x', member_ids: [alice.id, randomUUID()] }), 400],
|
||
['лишнее поле', chat({ title: 'x', member_ids: [alice.id], owner_id: alice.id }), 400],
|
||
]);
|
||
});
|
||
|
||
it('POST /chats/{chat_id}/messages', async () => {
|
||
const send = (body: unknown, key: string | null = randomUUID(), chat = chatId) => () => {
|
||
const req = request(server).post(`/api/v1/chats/${chat}/messages`).set('Authorization', bearer(alice));
|
||
if (key !== null) {
|
||
req.set('Idempotency-Key', key);
|
||
}
|
||
return req.send(body as object);
|
||
};
|
||
await check([
|
||
['без text', send({ attachment_ids: [attachmentId] }), 400],
|
||
['text число', send({ text: 1 }), 400],
|
||
['text null', send({ text: null }), 400],
|
||
['text 4001 code point', send({ text: emoji(4001) }), 400],
|
||
['text 4000 code points', send({ text: emoji(4000) }), 201],
|
||
['text пустой без вложений', send({ text: '' }), 400],
|
||
['text пробелы без вложений', send({ text: ' ' }), 400],
|
||
['text пустой с []', send({ text: '', attachment_ids: [] }), 400],
|
||
['text пустой с вложением', send({ text: '', attachment_ids: [attachmentId] }), 201],
|
||
['attachment_ids не массив', send({ text: 'x', attachment_ids: attachmentId }), 400],
|
||
['attachment_ids null', send({ text: 'x', attachment_ids: null }), 400],
|
||
['attachment_ids 11', send({ text: 'x', attachment_ids: Array.from({ length: 11 }, () => randomUUID()) }), 400],
|
||
['attachment_ids дубль', send({ text: 'x', attachment_ids: [attachmentId, attachmentId] }), 400],
|
||
['attachment_ids не UUID', send({ text: 'x', attachment_ids: ['nope'] }), 400],
|
||
['sender_id в теле', send({ text: 'x', sender_id: alice.id }), 400],
|
||
['лишнее поле', send({ text: 'x', extra: 1 }), 400],
|
||
['тело массив', send([{ text: 'x' }]), 400],
|
||
['без Idempotency-Key', send({ text: 'x' }, null), 400],
|
||
['Idempotency-Key пустой', send({ text: 'x' }, ''), 400],
|
||
['Idempotency-Key 129', send({ text: 'x' }, 'k'.repeat(129)), 400],
|
||
['Idempotency-Key пробел', send({ text: 'x' }, 'a b'), 400],
|
||
['Idempotency-Key слэш', send({ text: 'x' }, 'a/b'), 400],
|
||
['Idempotency-Key 128 из всех допустимых символов', send({ text: 'x' }, ('Az09._:-' + randomUUID().replace(/-/g, '')).padEnd(128, 'k')), 201],
|
||
['chat_id не UUID', send({ text: 'x' }, randomUUID(), 'nope'), 400],
|
||
]);
|
||
});
|
||
|
||
it('query и path параметры', async () => {
|
||
const get = (path: string) => () => request(server).get(path).set('Authorization', bearer(alice));
|
||
const lists = ['/api/v1/chats', `/api/v1/chats/${chatId}/messages`];
|
||
const cases: Case[] = [];
|
||
for (const base of lists) {
|
||
for (const limit of ['0', '101', '-1', 'abc', '1.5', '', ' ', '1e1', '0x10', '10abc']) {
|
||
cases.push([`${base} limit=${JSON.stringify(limit)}`, get(`${base}?limit=${encodeURIComponent(limit)}`), 400]);
|
||
}
|
||
cases.push([`${base} limit дважды`, get(`${base}?limit=1&limit=2`), 400]);
|
||
cases.push([`${base} limit=1`, get(`${base}?limit=1`), 200]);
|
||
cases.push([`${base} limit=100`, get(`${base}?limit=100`), 200]);
|
||
cases.push([`${base} cursor пустой`, get(`${base}?cursor=`), 400]);
|
||
cases.push([`${base} cursor мусор`, get(`${base}?cursor=garbage`), 400]);
|
||
cases.push([`${base} cursor base64 числа`, get(`${base}?cursor=${Buffer.from('123').toString('base64url')}`), 400]);
|
||
cases.push([`${base} cursor base64 null`, get(`${base}?cursor=${Buffer.from('null').toString('base64url')}`), 400]);
|
||
}
|
||
cases.push(['chat_id не UUID', get('/api/v1/chats/nope'), 400]);
|
||
cases.push(['chat_id почти UUID', get(`/api/v1/chats/${chatId}0`), 400]);
|
||
cases.push(['attachment_id не UUID', get('/api/v1/attachments/nope'), 400]);
|
||
cases.push(['content attachment_id не UUID', get('/api/v1/attachments/nope/content'), 400]);
|
||
for (const variant of ['', 'Original', 'THUMBNAIL', 'big']) {
|
||
cases.push([`variant=${JSON.stringify(variant)}`, get(`/api/v1/attachments/${attachmentId}/content?variant=${variant}`), 400]);
|
||
}
|
||
cases.push(['variant дважды', get(`/api/v1/attachments/${attachmentId}/content?variant=crop&variant=crop`), 400]);
|
||
await check(cases);
|
||
});
|
||
|
||
it('POST /chats/{chat_id}/attachments: filename и chat_id', async () => {
|
||
const upload = (query: string, chat = chatId) => () =>
|
||
request(server)
|
||
.post(`/api/v1/chats/${chat}/attachments${query}`)
|
||
.set('Authorization', bearer(alice))
|
||
.set('Content-Type', 'image/png')
|
||
.send(SAMPLE_PNG);
|
||
await check([
|
||
['без filename', upload(''), 400],
|
||
['filename пустой', upload('?filename='), 400],
|
||
['filename 256 code points', upload(`?filename=${encodeURIComponent(emoji(256))}`), 400],
|
||
['filename 255 code points', upload(`?filename=${encodeURIComponent(emoji(255))}`), 202],
|
||
['filename дважды', upload('?filename=a.png&filename=b.png'), 400],
|
||
['chat_id не UUID', upload('?filename=a.png', 'nope'), 400],
|
||
]);
|
||
});
|
||
});
|