forked from mtusi2026/mtusi2026lab2
feat: explain analyze
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { randomUUID } from 'crypto';
|
||||
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 вход, проверка сессии и logout работают через PostgreSQL', 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);
|
||||
await request(server)
|
||||
.delete('/api/v1/auth/sessions/current')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(204);
|
||||
await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(401);
|
||||
await request(server).get('/api/v1/users/me').expect(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('откатывает создание чата целиком, если один из участников не существует', 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);
|
||||
});
|
||||
});
|
||||
+14
-7
@@ -17,16 +17,23 @@ export interface TestUser {
|
||||
token: string;
|
||||
}
|
||||
|
||||
export async function createTestApp(): Promise<{
|
||||
export async function createTestApp(env: Record<string, string> = {}): Promise<{
|
||||
app: INestApplication;
|
||||
server: any;
|
||||
}> {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
const app = moduleRef.createNestApplication<NestFastifyApplication>(
|
||||
new FastifyAdapter(),
|
||||
);
|
||||
const saved = { ...process.env };
|
||||
Object.assign(process.env, env);
|
||||
let app: NestFastifyApplication;
|
||||
try {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
app = moduleRef.createNestApplication<NestFastifyApplication>(
|
||||
new FastifyAdapter(),
|
||||
);
|
||||
} finally {
|
||||
process.env = saved;
|
||||
}
|
||||
configureApp(app);
|
||||
await app.listen(0, '127.0.0.1');
|
||||
return { app, server: app.getHttpServer() };
|
||||
|
||||
Reference in New Issue
Block a user