Files
scouthub/scouthub-magazzino-be/tests/integration/tipiEvento.endpoint.test.ts
T

162 lines
5.3 KiB
TypeScript

import { generateKeyPairSync } from 'crypto';
import request from 'supertest';
import nock from 'nock';
import jwt from 'jsonwebtoken';
process.env.KEYCLOAK_BASE_URL = 'http://keycloak.test';
process.env.KEYCLOAK_REALM = 'scouthub';
process.env.KEYCLOAK_MAGAZZINO_CLIENT_ID = 'test-client';
process.env.KEYCLOAK_MAGAZZINO_CLIENT_SECRET = 'test-secret';
process.env.DATABASE_URL = 'postgresql://user:pass@localhost:5432/scouthub_magazzino_test';
const tipoEventoFindMany = jest.fn();
const tipoEventoCreate = jest.fn();
const tipoEventoUpdate = jest.fn();
const tipoEventoDelete = jest.fn();
jest.mock('../../src/db/prisma', () => ({
prisma: {
tipoEvento: {
findMany: (...args: unknown[]) => tipoEventoFindMany(...args),
create: (...args: unknown[]) => tipoEventoCreate(...args),
update: (...args: unknown[]) => tipoEventoUpdate(...args),
delete: (...args: unknown[]) => tipoEventoDelete(...args),
},
},
}));
import { app } from '../../src/app';
const KEYCLOAK_HOST = 'http://keycloak.test';
const CERTS_PATH = '/realms/scouthub/protocol/openid-connect/certs';
const KID = 'test-kid';
const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
const jwk = publicKey.export({ format: 'jwk' }) as Record<string, unknown>;
const privateKeyPem = privateKey.export({ type: 'pkcs1', format: 'pem' }) as string;
function signToken(payload: object): string {
return jwt.sign(payload, privateKeyPem, { algorithm: 'RS256', keyid: KID, expiresIn: '5m' });
}
function utenteToken(): string {
return signToken({
sub: 'user-1',
realm_access: { roles: ['censito'] },
organization: { 'gruppo-alfa': { id: 'org-1', roles: [] } },
});
}
function adminCatalogoToken(): string {
return signToken({
sub: 'admin-1',
realm_access: { roles: ['moderatore'] },
organization: { 'gruppo-omega': { id: 'org-9', roles: [] } },
});
}
beforeAll(() => {
nock(KEYCLOAK_HOST).persist().get(CERTS_PATH).reply(200, {
keys: [{ ...jwk, kid: KID, alg: 'RS256', use: 'sig' }],
});
});
afterAll(() => {
nock.cleanAll();
});
beforeEach(() => {
jest.clearAllMocks();
});
describe('GET /tipi-evento', () => {
test('è pubblico e restituisce la lista', async () => {
tipoEventoFindMany.mockResolvedValueOnce([{ id: 't-1', nome: 'Campo estivo' }]);
const response = await request(app).get('/tipi-evento');
expect(response.status).toBe(200);
expect(response.body).toEqual([{ id: 't-1', nome: 'Campo estivo' }]);
});
});
describe('POST /tipi-evento', () => {
test('un utente normale non può creare un tipo evento', async () => {
const response = await request(app)
.post('/tipi-evento')
.set('Authorization', `Bearer ${utenteToken()}`)
.send({ nome: 'Bivacco' });
expect(response.status).toBe(403);
expect(tipoEventoCreate).not.toHaveBeenCalled();
});
test('un moderatore può creare un tipo evento', async () => {
tipoEventoCreate.mockResolvedValueOnce({ id: 't-2', nome: 'Bivacco' });
const response = await request(app)
.post('/tipi-evento')
.set('Authorization', `Bearer ${adminCatalogoToken()}`)
.send({ nome: 'Bivacco' });
expect(response.status).toBe(201);
expect(tipoEventoCreate).toHaveBeenCalledWith({ data: { nome: 'Bivacco' } });
});
test('risponde 401 senza token', async () => {
const response = await request(app).post('/tipi-evento').send({ nome: 'Bivacco' });
expect(response.status).toBe(401);
expect(tipoEventoCreate).not.toHaveBeenCalled();
});
});
describe('PUT /tipi-evento/:id', () => {
test('un utente normale non può modificare un tipo evento', async () => {
const response = await request(app)
.put('/tipi-evento/t-1')
.set('Authorization', `Bearer ${utenteToken()}`)
.send({ nome: 'Uscita di branco' });
expect(response.status).toBe(403);
expect(tipoEventoUpdate).not.toHaveBeenCalled();
});
test('un moderatore può modificare un tipo evento', async () => {
tipoEventoUpdate.mockResolvedValueOnce({ id: 't-1', nome: 'Uscita di branco' });
const response = await request(app)
.put('/tipi-evento/t-1')
.set('Authorization', `Bearer ${adminCatalogoToken()}`)
.send({ nome: 'Uscita di branco' });
expect(response.status).toBe(200);
expect(tipoEventoUpdate).toHaveBeenCalledWith({ where: { id: 't-1' }, data: { nome: 'Uscita di branco' } });
});
});
describe('DELETE /tipi-evento/:id', () => {
test('un utente normale non può eliminare un tipo evento', async () => {
const response = await request(app).delete('/tipi-evento/t-1').set('Authorization', `Bearer ${utenteToken()}`);
expect(response.status).toBe(403);
expect(tipoEventoDelete).not.toHaveBeenCalled();
});
test('un moderatore può eliminare un tipo evento', async () => {
tipoEventoDelete.mockResolvedValueOnce({ id: 't-1', nome: 'Sede' });
const response = await request(app).delete('/tipi-evento/t-1').set('Authorization', `Bearer ${adminCatalogoToken()}`);
expect(response.status).toBe(204);
expect(tipoEventoDelete).toHaveBeenCalledWith({ where: { id: 't-1' } });
});
test('risponde 401 senza token', async () => {
const response = await request(app).delete('/tipi-evento/t-1');
expect(response.status).toBe(401);
expect(tipoEventoDelete).not.toHaveBeenCalled();
});
});