Files
mtusi2026lab3/test/failures.e2e-spec.ts
T

167 lines
6.0 KiB
TypeScript
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.
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { randomUUID } from 'crypto';
import Redis from 'ioredis';
import { CacheService } from '../src/cache/cache.service';
import { ChatsService } from '../src/chats/chats.service';
import { PrismaService } from '../src/db/prisma.service';
import { bearer, createTestApp, registerUser } from './helpers';
const UNREACHABLE_REDIS = 'redis://127.0.0.1:1/0';
const UNREACHABLE_DB = 'postgresql://test:test@127.0.0.1:1/none?connect_timeout=1';
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
describe('Уровень 4: expiry, отказы зависимостей, rollback (e2e)', () => {
const apps: INestApplication[] = [];
async function start(env: Record<string, string> = {}) {
const started = await createTestApp(env);
apps.push(started.app);
return started;
}
afterAll(async () => {
await Promise.all(apps.map((app) => app.close()));
});
it('сессия истекает при коротком SESSION_TTL_SECONDS, в том числе из кэша', async () => {
const { server } = await start({ SESSION_TTL_SECONDS: '2' });
const user = await registerUser(server, 'ttl');
await request(server)
.get('/api/v1/users/me')
.set('Authorization', bearer(user))
.expect(200);
await sleep(2500);
const res = await request(server)
.get('/api/v1/users/me')
.set('Authorization', bearer(user))
.expect(401);
expect(res.headers['www-authenticate']).toBe('Bearer realm="messenger"');
});
it('без Redis вход и проверка сессии работают через PostgreSQL, logout — 503 без отзыва', async () => {
const { server } = await start({ CACHE_URL: UNREACHABLE_REDIS });
const user = await registerUser(server, 'noredis');
await request(server)
.get('/api/v1/users/me')
.set('Authorization', bearer(user))
.expect(200);
const res = await request(server)
.delete('/api/v1/auth/sessions/current')
.set('Authorization', bearer(user))
.expect(503);
expect(res.body.error.code).toBe('unavailable');
await request(server)
.get('/api/v1/users/me')
.set('Authorization', bearer(user))
.expect(200);
await request(server).get('/api/v1/users/me').expect(401);
});
it('logout через реплику без связи с Redis не создаёт расхождения с репликой, у которой сессия в кэше', async () => {
const a = await start();
const b = await start();
const user = await registerUser(a.server, 'partition');
const me = (server: any, status: number) =>
request(server)
.get('/api/v1/users/me')
.set('Authorization', bearer(user))
.expect(status);
const logout = (status: number) =>
request(a.server)
.delete('/api/v1/auth/sessions/current')
.set('Authorization', bearer(user))
.expect(status);
const cache = a.app.get(CacheService) as any;
const redis = cache.client as Redis;
await me(b.server, 200);
redis.disconnect();
await logout(503);
await me(b.server, 200);
await me(a.server, 200);
await redis.connect();
await sleep(200);
expect(cache.trusted).toBe(true);
await me(b.server, 200);
expect((await redis.keys('session:v1:*')).length).toBeGreaterThan(0);
await logout(204);
await me(b.server, 401);
await me(a.server, 401);
});
it('без PostgreSQL отвечает ограниченным 503 и не пускает анонима', async () => {
const healthy = await start();
const user = await registerUser(healthy.server, 'nodb');
await request(healthy.server)
.get('/api/v1/users/me')
.set('Authorization', bearer(user))
.expect(200);
const { server } = await start({ DATABASE_URL: UNREACHABLE_DB });
const ready = await request(server).get('/health/ready').expect(503);
expect(ready.body.error.code).toBe('unavailable');
expect(JSON.stringify(ready.body)).not.toMatch(/127\.0\.0\.1|postgresql:|prisma/i);
await request(server).get('/api/v1/chats').expect(401);
await request(server)
.get('/api/v1/chats')
.set('X-User-Id', user.id)
.expect(401);
await request(server)
.get('/api/v1/chats')
.set('Authorization', 'Bearer unknown-token-value')
.expect(503);
const res = await request(server)
.get('/api/v1/chats')
.set('Authorization', bearer(user))
.expect(503);
expect(res.body.error.code).toBe('unavailable');
await request(server)
.post('/api/v1/users')
.send({
username: `nodb_${randomUUID().slice(0, 8)}`,
display_name: 'X',
password: 'Long-enough-pass-1',
})
.expect(503);
});
it('неожиданное исключение — 500 internal_error без деталей, с X-Request-Id и X-Instance-Id', async () => {
const { app, server } = await start();
const user = await registerUser(server, 'boom');
jest
.spyOn(app.get(ChatsService), 'listForMember')
.mockRejectedValueOnce(new Error('secret internal details'));
const res = await request(server)
.get('/api/v1/chats')
.set('Authorization', bearer(user))
.expect(500);
expect(res.body.error.code).toBe('internal_error');
expect(JSON.stringify(res.body)).not.toMatch(/secret/);
expect(res.body.error.request_id).toBe(res.headers['x-request-id']);
expect(res.headers['x-instance-id']).toBeTruthy();
});
it('откатывает создание чата целиком, если один из участников не существует', async () => {
const { app, server } = await start();
const alice = await registerUser(server, 'rollback');
const title = `rollback ${randomUUID()}`;
const res = await request(server)
.post('/api/v1/chats')
.set('Authorization', bearer(alice))
.send({ title, member_ids: [alice.id, randomUUID()] })
.expect(400);
expect(res.body.error.code).toBe('invalid_request');
const prisma = app.get(PrismaService);
expect(await prisma.chat.count({ where: { title } })).toBe(0);
expect(
await prisma.chatMember.count({ where: { userId: alice.id } }),
).toBe(0);
});
});