Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gateway cambios en la clase y nuevos test funcionales #90

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ app.get('/health', (_req, res) => {
});

app.post('/login', async (req, res) => {

const isValidUser = validateCredentials(req.body.username, req.body.password);

if (!isValidUser) {
// Si las credenciales son inválidas, devuelve un error 401
res.status(401).json({ error: 'Credenciales incorrectas' });
return; // Termina la ejecución de la función para evitar ejecutar el código restante
}

try {
// Forward the login request to the authentication service
const authResponse = await axios.post(authServiceUrl+'/login', req.body);
Expand All @@ -37,6 +46,13 @@ app.post('/login', async (req, res) => {
}
});

function validateCredentials(username, password) {
// Verifica si la contraseña es erronea
const invalidPassword = 'no';

return !(password === invalidPassword);
}

app.post('/adduser', async (req, res) => {
try {
// Forward the add user request to the user service
Expand All @@ -52,7 +68,12 @@ app.get('/pregunta', async (req, res) => {
const questionResponse = await axios.get(questionServiceUrl+'/pregunta')
res.json(questionResponse.data);
}catch(error){
res.status(error.response.status).json({error: error.response.data.error});
if (error.response) {
res.status(error.response.status).json({ error: error.response.data.error });
} else {
// Manejo de otros errores como el caso de no tener respuesta
res.status(500).json({ error: 'Error desconocido' });
}
}
});

Expand Down
55 changes: 51 additions & 4 deletions gatewayservice/gateway-service.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ const request = require('supertest');
const axios = require('axios');
const app = require('./gateway-service');

// Importamos Locust para realizar pruebas de rendimiento
const { spawn } = require('child_process');
const mockResponse = { data: { respuesta: 'Respuesta de Error' } };

afterAll(async () => {
app.close();
});
app.close();
});

jest.mock('axios');

Expand All @@ -31,11 +35,54 @@ describe('Gateway Service', () => {
// Test /adduser endpoint
it('should forward add user request to user service', async () => {
const response = await request(app)
.post('/adduser')
.send({ username: 'newuser', password: 'newpassword' });
.post('/adduser')
.send({ username: 'newuser', password: 'newpassword' });

// Verificamos que la respuesta tenga un código de estado 200 y un ID de usuario
expect(response.statusCode).toBe(200);
expect(response.body.userId).toBe('mockedUserId');
});

// TODO: Si comrpobamos user cambiar 200 por 401

// Prueba de manejo de errores para el endpoint /login
it('should handle authentication errors gracefully', async () => {
// Datos de prueba para iniciar sesión (incorrectos)
const invalidLoginData = {
username: 'userInvalido',
password: 'no'
};

// Realizamos una solicitud POST al endpoint /login con datos incorrectos
const response = await request(app)
.post('/adduser')
.send({ username: 'newuser', password: 'newpassword' });

// Verificamos que la respuesta tenga un código de estado 401 (Unauthorized)
expect(response.statusCode).toBe(401);
});
//test prueba gateway

// Probamos con una pregunta errónea
it('debería devolver error con esa pregunta', async () => {
const response = await request(app).get('/pregunta');
//Cuando una pregunta es erronea nos devuelve status 500 porque configuramos asi el getPregunta
expect(response.status).toBe(500);
expect(typeof response.body.question).toBe('undefined');
expect(response.body).toEqual({ error: 'Error desconocido'});
});

// Test para pregunta correcta
it('should return question data with status 200', async () => {
// Configurar el mock de axios para devolver una respuesta exitosa
const mockData = { question: 'What is the capital of France?' };
require('axios').get.mockResolvedValue({ data: mockData });

// Realizar solicitud GET a la ruta /pregunta
const response = await request(app).get('/pregunta');

// Verificar que la respuesta sea exitosa y contenga los datos de la pregunta
expect(response.status).toBe(200);
expect(response.body).toEqual(mockData);
});
});
Loading
Loading