From 2162eca57278bf2fb3642c2b806b940e63cd2ab4 Mon Sep 17 00:00:00 2001 From: uo283055 Date: Fri, 26 Apr 2024 20:57:54 +0200 Subject: [PATCH 1/9] edit metodos ranking p1 --- users/rankingservice/ranking-service.js | 14 ++------------ webapp/src/components/Login.js | 4 ++-- 2 files changed, 4 insertions(+), 14 deletions(-) diff --git a/users/rankingservice/ranking-service.js b/users/rankingservice/ranking-service.js index edbcbed1..ab2089a2 100644 --- a/users/rankingservice/ranking-service.js +++ b/users/rankingservice/ranking-service.js @@ -51,8 +51,7 @@ app.post('/updateRanking', async (req, res) => { }); -//crea un elemento ranking si no existe y si existe lo deja a 0 para actualizar a posterior sus datos -//tambien actualiza si se elimino un usuario de eliminar el elemento ranking correspondiente +//crea un elemento ranking si no existe app.post('/createUserRank', async (req, res) => { try { const { usernames } = req.body; @@ -67,16 +66,7 @@ app.post('/createUserRank', async (req, res) => { // Buscar si ya existe un ranking para el usuario const existingUserRank = await UserRank.findOne({ username: safeUsername }); - if (existingUserRank) { - // Si ya existe un ranking para el usuario, actualizar los valores a cero - // para actualizarlos después con los valores de las jugadas - existingUserRank.porcentajeAciertos = 0; - existingUserRank.preguntasCorrectas = 0; - existingUserRank.preguntasFalladas = 0; - existingUserRank.numPartidas = 0; - - await existingUserRank.save(); - } else { + if (!existingUserRank) { // Si no existe un ranking para el usuario, crear uno nuevo const newUserRank = new UserRank({ username, diff --git a/webapp/src/components/Login.js b/webapp/src/components/Login.js index cf0ad5ff..33deb11c 100644 --- a/webapp/src/components/Login.js +++ b/webapp/src/components/Login.js @@ -59,8 +59,8 @@ const Login = ({ setLogged }) => { // Envía todos los nombres de usuario en una sola solicitud await axios.post(`${apiEndpoint}/createUserRank`, { usernames }); - const { data: updatedRankingData } = await axios.get(`${apiEndpoint}/actRanking`); - await axios.post(`${apiEndpoint}/updateAllRanking`, updatedRankingData); + //const { data: updatedRankingData } = await axios.get(`${apiEndpoint}/actRanking`); + //await axios.post(`${apiEndpoint}/updateAllRanking`, updatedRankingData); setLoading(false); setOpenSnackbar(true); From e51f37b1af6e5337651acb8754bf679f4bb99df8 Mon Sep 17 00:00:00 2001 From: uo283055 Date: Fri, 26 Apr 2024 21:01:52 +0200 Subject: [PATCH 2/9] edit metodos ranking elim updateall --- gatewayservice/gateway-service.js | 11 ----- gatewayservice/gateway-service.test.js | 17 +------ users/rankingservice/ranking-service.js | 46 ------------------ users/rankingservice/ranking-service.test.js | 50 -------------------- webapp/src/components/Login.js | 1 - 5 files changed, 1 insertion(+), 124 deletions(-) diff --git a/gatewayservice/gateway-service.js b/gatewayservice/gateway-service.js index fafb7d2e..78d5c518 100644 --- a/gatewayservice/gateway-service.js +++ b/gatewayservice/gateway-service.js @@ -174,17 +174,6 @@ app.post('/updateRanking', async (req, res) => { } }); -app.post('/updateAllRanking', async (req, res) => { - try { - // Reenviar la solicitud POST al servicio de ranking para actualizar el ranking de un usuario - const rankingResponse = await axios.post(`${rankingServiceUrl}/updateAllRanking`, req.body); - res.json(rankingResponse.data); - } catch (error) { - res.status(500).json({ error: 'Error interno del servidor' }); - } -}); - - ///////////////para los question del juego // Ruta para agregar una pregunta de prueba diff --git a/gatewayservice/gateway-service.test.js b/gatewayservice/gateway-service.test.js index 0bc53e74..3ff614f7 100644 --- a/gatewayservice/gateway-service.test.js +++ b/gatewayservice/gateway-service.test.js @@ -23,9 +23,7 @@ describe('Gateway Service', () => { return Promise.resolve({ data: { rankId: 'mockedRankId' } }); } else if (url.endsWith('/updateRanking')) { return Promise.resolve({ data: { updatedRanking: true } }); - } else if (url.endsWith('/updateAllRanking')) { - return Promise.resolve({ data: { updatedRanking: true } }); - } else if (url.endsWith('/addOrUpdateQuestionGenerator')) { + } else if (url.endsWith('/addOrUpdateQuestionGenerator')) { return Promise.resolve({ data: { questionId: 'mockedQuestionId' } }); } else if (url.endsWith('/addGeneratedQuestion')) { return Promise.resolve({ data: { generatedQuestionId: 'mockedGeneratedQuestionId' } }); @@ -151,18 +149,6 @@ describe('Gateway Service', () => { expect(response.body.updatedRanking).toBe(true); }); - // Test /updateAllRanking endpoint - it('should update all rankings in ranking service', async () => { - const mockRanking = { username: 'testuser' }; - - const response = await request(app) - .post('/updateAllRanking') - .send(mockRanking); - - expect(response.statusCode).toBe(200); - expect(response.body.updatedRanking).toBe(true); - }); - // Test /addOrUpdateQuestionGenerator endpoint success it('should add or update a question successfully', async () => { const mockQuestion = { @@ -326,7 +312,6 @@ describe('Gateway Service', () => { { method: 'post', endpoint: '/addQuestion', data: { questionBody: '¿Cual es la capital de Francia?', typeQuestion: 'pais_capital' } }, { method: 'post', endpoint: '/createUserRank', data: { username: 'testuser' } }, { method: 'post', endpoint: '/updateRanking', data: { username: 'testuser' } }, - { method: 'post', endpoint: '/updateAllRanking', data: { username: 'testuser' } }, { method: 'post', endpoint: '/addOrUpdateQuestionGenerator', data: { questionBody: '¿Cual es la capital de Francia?', typeQuestion: 'pais_capital' } }, { method: 'get', endpoint: '/getRandomQuestionSports' }, { method: 'get', endpoint: '/getRandomQuestionMusic' }, diff --git a/users/rankingservice/ranking-service.js b/users/rankingservice/ranking-service.js index ab2089a2..7cabdd7a 100644 --- a/users/rankingservice/ranking-service.js +++ b/users/rankingservice/ranking-service.js @@ -119,52 +119,6 @@ app.get('/obtainRank', async (req, res) => { } }); -//actualiza al inicio los rankings si hubo algun cambio en la base de datos -app.post('/updateAllRanking', async (req, res) => { - try { - const rankingData = req.body; - - // Iterar sobre los datos recibidos y actualizar los rankings correspondientes - for (const userData of rankingData) { - const username = userData.username.toString(); - const preguntasCorrectas = userData.preguntasCorrectas; - const preguntasFalladas = userData.preguntasFalladas; - const numPartidas = userData.numPartidas; - - // Buscar al usuario en la base de datos - const existingUser = await UserRank.findOne({ username }); - - if (!existingUser) { - // Si el usuario no tiene ranking, crear un nuevo ranking para él - const newUserRank = new UserRank({ - username, - porcentajeAciertos: 0, - preguntasCorrectas, - preguntasFalladas, - numPartidas // Al ser el primer registro, el número de partidas es 1 - }); - - await newUserRank.save(); - } else { - // Si el usuario ya existe, actualizar su ranking - existingUser.preguntasCorrectas += preguntasCorrectas; - existingUser.preguntasFalladas += preguntasFalladas; - existingUser.numPartidas += numPartidas; - - const totalPreguntas = existingUser.preguntasCorrectas + existingUser.preguntasFalladas; - const porcentajeAciertos = (existingUser.preguntasCorrectas / totalPreguntas) * 100; - existingUser.porcentajeAciertos = porcentajeAciertos.toFixed(2); - - await existingUser.save(); - } - } - - res.json({ message: 'Rankings actualizados correctamente.' }); - } catch (error) { - res.status(400).json({ error: error.message }); - } -}); - // Read the OpenAPI YAML file synchronously const openapiPath='./openapi.yaml' if (fs.existsSync(openapiPath)) { diff --git a/users/rankingservice/ranking-service.test.js b/users/rankingservice/ranking-service.test.js index 70ee2191..791d0880 100644 --- a/users/rankingservice/ranking-service.test.js +++ b/users/rankingservice/ranking-service.test.js @@ -209,29 +209,6 @@ it('should reset an existing user rank', async () => { expect(updatedUserRank.numPartidas).toBe(0); }); -it('should return 400 if user does not exist', async () => { - // Arrange - const username = 'testUser'; - const initialUserRank = new UserRank({ - username, - porcentajeAciertos: 50, - preguntasCorrectas: 10, - preguntasFalladas: 10, - numPartidas: 1 - }); - await initialUserRank.save(); - - // Act - await request(app) - .post('/updateAllRanking') - .send({ usernames: ['anotherUser'] }) // username not included - .expect(400); // Expect 400 status code - - // Assert - const deletedUserRank = await UserRank.findOne({ username }); - expect(deletedUserRank).not.toBeNull(); // Expect the user rank to still exist -}); - describe('GET /obtainRank', () => { it('it should GET all the rankings', async () => { const response = await request(app).get('/obtainRank'); @@ -240,31 +217,4 @@ describe('GET /obtainRank', () => { }); }); -describe('POST /updateAllRanking', () => { - it('it should update all rankings', async () => { - const rankingData = [ - { - username: 'testUser1', - preguntasCorrectas: 5, - preguntasFalladas: 3, - numPartidas: 1 - }, - { - username: 'testUser2', - preguntasCorrectas: 7, - preguntasFalladas: 2, - numPartidas: 1 - } - ]; - - const response = await request(app) - .post('/updateAllRanking') - .send(rankingData); - - expect(response.status).toBe(200); - expect(response.body).toHaveProperty('message', 'Rankings actualizados correctamente.'); - }); -}); - - }); diff --git a/webapp/src/components/Login.js b/webapp/src/components/Login.js index 33deb11c..39344ea4 100644 --- a/webapp/src/components/Login.js +++ b/webapp/src/components/Login.js @@ -60,7 +60,6 @@ const Login = ({ setLogged }) => { await axios.post(`${apiEndpoint}/createUserRank`, { usernames }); //const { data: updatedRankingData } = await axios.get(`${apiEndpoint}/actRanking`); - //await axios.post(`${apiEndpoint}/updateAllRanking`, updatedRankingData); setLoading(false); setOpenSnackbar(true); From 7b38e695fbc770c4df6405f83c306a95acb11353 Mon Sep 17 00:00:00 2001 From: uo283055 Date: Fri, 26 Apr 2024 21:05:51 +0200 Subject: [PATCH 3/9] edit metodos ranking elim actranking --- gatewayservice/gateway-service.js | 9 ------ gatewayservice/gateway-service.test.js | 12 -------- questions/recordservice/record-service.js | 30 ------------------- .../recordservice/record-service.test.js | 29 ------------------ webapp/src/components/Login.js | 2 -- 5 files changed, 82 deletions(-) diff --git a/gatewayservice/gateway-service.js b/gatewayservice/gateway-service.js index 78d5c518..76f33380 100644 --- a/gatewayservice/gateway-service.js +++ b/gatewayservice/gateway-service.js @@ -132,15 +132,6 @@ app.get('/getFullQuestion', async (req, res) => { } }); -app.get('/actRanking', async (req, res) => { - try { - const rankingResponse = await axios.get(`${recordServiceUrl}/actRanking`); - res.json(rankingResponse.data); - } catch (error) { - res.status(500).json({ error: 'Error interno del servidor' }); - } -}); - ////////////////////////ranking app.post('/createUserRank', async (req, res) => { diff --git a/gatewayservice/gateway-service.test.js b/gatewayservice/gateway-service.test.js index 3ff614f7..a63c2527 100644 --- a/gatewayservice/gateway-service.test.js +++ b/gatewayservice/gateway-service.test.js @@ -38,8 +38,6 @@ describe('Gateway Service', () => { return Promise.resolve({ data: { records: ['record1', 'record2'] } }); } else if (url.endsWith('/getFullQuestion')) { return Promise.resolve({ data: { question: 'mockedQuestion' } }); - } else if (url.endsWith('/actRanking')) { - return Promise.resolve({ data: { ranking: 'mockedRanking' } }); } else if (url.endsWith('/obtainRank')) { return Promise.resolve({ data: { rank: 'mockedRank' } }); } else if (url.endsWith('/getRandomQuestionDeporte') || url.endsWith('/getRandomQuestionAnio') @@ -222,15 +220,6 @@ describe('Gateway Service', () => { expect(response.body.question).toBe('mockedQuestion'); }); - // Test /actRanking endpoint - it('should get a ranking from ranking service', async () => { - const response = await request(app) - .get('/actRanking'); - - expect(response.statusCode).toBe(200); - expect(response.body.ranking).toBe('mockedRanking'); - }); - // Test /obtainRank endpoint it('should get a rank from rank service', async () => { const response = await request(app) @@ -322,7 +311,6 @@ describe('Gateway Service', () => { { method: 'get', endpoint: '/getRecords/:userId' }, { method: 'get', endpoint: '/getAllUsers' }, { method: 'get', endpoint: '/getFullQuestion' }, - { method: 'get', endpoint: '/actRanking' }, { method: 'get', endpoint: '/obtainRank' }, { method: 'get', endpoint: '/getAllQuestionGenerator' }, { method: 'get', endpoint: '/countQuestionGenerator' }, diff --git a/questions/recordservice/record-service.js b/questions/recordservice/record-service.js index 55632cec..79a04e4d 100644 --- a/questions/recordservice/record-service.js +++ b/questions/recordservice/record-service.js @@ -67,36 +67,6 @@ app.get('/getRecords/:userId', async (req, res) => { } }); -// Nuevo endpoint paraactualizar el ranking de los usurias si surgiera algo -app.get('/actRanking', async (req, res) => { - try { - const allRecords = await Record.find(); - - const rankingData = {}; - - allRecords.forEach(record => { - const userId = record.userId; - if (!(userId in rankingData)) { - rankingData[userId] = { - username: userId, - preguntasCorrectas: 0, - preguntasFalladas: 0, - numPartidas: 0 - }; - } - - rankingData[userId].preguntasCorrectas += record.correctQuestions; - rankingData[userId].preguntasFalladas += record.failedQuestions; - rankingData[userId].numPartidas += 1; - }); - - const rankingArray = Object.values(rankingData); - - res.json(rankingArray); - } catch (error) { - res.status(400).json({ error: error.message }); - } -}); // Read the OpenAPI YAML file synchronously const openapiPath='./openapi.yaml' diff --git a/questions/recordservice/record-service.test.js b/questions/recordservice/record-service.test.js index bab606a7..0889ff3f 100644 --- a/questions/recordservice/record-service.test.js +++ b/questions/recordservice/record-service.test.js @@ -100,33 +100,4 @@ describe('Record Service', () => { expect(response.body.length).toBe(2); }); - it('Should calculate and return a ranking of users /actRanking', async () => { - // Add the records to the database - await request(app).post('/addRecord').send(record); - await request(app).post('/addRecord').send(record2); - await request(app).post('/addRecord').send(record3); - - // Request the ranking - const response = await request(app).get('/actRanking'); - - // Check the status code - expect(response.status).toBe(200); - - // Check the structure and content of the response - expect(response.body).toEqual(expect.arrayContaining([ - expect.objectContaining({ - username: 'testuserid', - preguntasCorrectas: 28, - preguntasFalladas: 12, - numPartidas: 4 - }), - expect.objectContaining({ - username: 'testuserid2', - preguntasCorrectas: 10, - preguntasFalladas: 10, - numPartidas: 2 - }) - ])); - }); - }); diff --git a/webapp/src/components/Login.js b/webapp/src/components/Login.js index 39344ea4..7c23a9f9 100644 --- a/webapp/src/components/Login.js +++ b/webapp/src/components/Login.js @@ -59,8 +59,6 @@ const Login = ({ setLogged }) => { // Envía todos los nombres de usuario en una sola solicitud await axios.post(`${apiEndpoint}/createUserRank`, { usernames }); - //const { data: updatedRankingData } = await axios.get(`${apiEndpoint}/actRanking`); - setLoading(false); setOpenSnackbar(true); } catch (error) { From f17853784f1a4a76cf1bb753f82018b8db13d5a4 Mon Sep 17 00:00:00 2001 From: uo283055 Date: Fri, 26 Apr 2024 21:28:49 +0200 Subject: [PATCH 4/9] limpieza de metodos no necesarion micro ranking, falta corregir tests --- users/rankingservice/ranking-service.js | 67 ++++++++----------------- webapp/src/components/Login.js | 5 +- 2 files changed, 21 insertions(+), 51 deletions(-) diff --git a/users/rankingservice/ranking-service.js b/users/rankingservice/ranking-service.js index 7cabdd7a..4038687f 100644 --- a/users/rankingservice/ranking-service.js +++ b/users/rankingservice/ranking-service.js @@ -54,61 +54,34 @@ app.post('/updateRanking', async (req, res) => { //crea un elemento ranking si no existe app.post('/createUserRank', async (req, res) => { try { - const { usernames } = req.body; - - await deleteRankingElements(usernames); - - // Iterar sobre cada nombre de usuario recibido - for (const username of usernames) { - // Convertir el nombre de usuario en una cadena - const safeUsername = username.toString(); - - // Buscar si ya existe un ranking para el usuario - const existingUserRank = await UserRank.findOne({ username: safeUsername }); - - if (!existingUserRank) { - // Si no existe un ranking para el usuario, crear uno nuevo - const newUserRank = new UserRank({ - username, - porcentajeAciertos: 0, - preguntasCorrectas: 0, - preguntasFalladas: 0, - numPartidas: 0 - }); - - await newUserRank.save(); - } + const { username } = req.body; + + // Convertir el nombre de usuario en una cadena + const safeUsername = username.toString(); + + // Buscar si ya existe un ranking para el usuario + const existingUserRank = await UserRank.findOne({ username: safeUsername }); + + if (!existingUserRank) { + // Si no existe un ranking para el usuario, crear uno nuevo + const newUserRank = new UserRank({ + username: safeUsername, + porcentajeAciertos: 0, + preguntasCorrectas: 0, + preguntasFalladas: 0, + numPartidas: 0 + }); + + await newUserRank.save(); } + // Respuesta inmediata al cliente indicando que la operación se ha completado con éxito res.json({ message: 'Rankings de usuarios creados o actualizados correctamente.' }); } catch (error) { res.status(400).json({ error: error.message }); } }); - -//actualiza si se elimino un usuario de eliminar el elemento ranking correspondiente -async function deleteRankingElements(usernames) { - try { - // Obtener todos los elementos de ranking - const allUserRanks = await UserRank.find({}); - - // Crear un conjunto de nombres de usuario en la lista recibida - const usernamesSet = new Set(usernames); - - // Iterar sobre cada elemento de ranking - for (const userRank of allUserRanks) { - // Verificar si el nombre de usuario del elemento de ranking no está en la lista recibida - if (!usernamesSet.has(userRank.username)) { - // Si el nombre de usuario no está en la lista, eliminar el elemento de ranking - await UserRank.deleteOne({ username: userRank.username }); - } - } - } catch (error) { - throw new Error('Error al actualizar los rankings de usuarios: ' + error.message); - } -} - app.get('/obtainRank', async (req, res) => { try { diff --git a/webapp/src/components/Login.js b/webapp/src/components/Login.js index 7c23a9f9..0ecabaa4 100644 --- a/webapp/src/components/Login.js +++ b/webapp/src/components/Login.js @@ -52,12 +52,9 @@ const Login = ({ setLogged }) => { setLoginSuccess(true); setLogged(); setLoading(true); - - // Reúne todos los nombres de usuario en un array - const usernames = users.map(user => user.username); // Envía todos los nombres de usuario en una sola solicitud - await axios.post(`${apiEndpoint}/createUserRank`, { usernames }); + await axios.post(`${apiEndpoint}/createUserRank`, { username }); setLoading(false); setOpenSnackbar(true); From ca662a0a8668fb41ed27c6192197cf503c90d3aa Mon Sep 17 00:00:00 2001 From: uo283055 Date: Fri, 26 Apr 2024 21:33:48 +0200 Subject: [PATCH 5/9] prueba edicion de tests por modificaciones anteriores --- users/rankingservice/ranking-service.test.js | 49 +++++++++++--------- 1 file changed, 27 insertions(+), 22 deletions(-) diff --git a/users/rankingservice/ranking-service.test.js b/users/rankingservice/ranking-service.test.js index 791d0880..b0b56e64 100644 --- a/users/rankingservice/ranking-service.test.js +++ b/users/rankingservice/ranking-service.test.js @@ -25,27 +25,21 @@ afterEach(async () => { describe('User Service', () => { // Prueba para el endpoint POST /createUserRank describe('POST /createUserRank', () => { - it('should create new user ranks', async () => { - const newUser = { username: 'testuser1' }; - const newUser2 = { username: 'testuser2' }; - const newUser3 = { username: 'testuser3' }; - const newUser4 = { username: 'testuser4' }; - const users = [newUser, newUser2, newUser3, newUser4]; + it('should create new user rank if user does not exist', async () => { + const username = 'testuser1'; - // Realizar una solicitud POST para crear nuevos rankings de usuarios + // Realizar una solicitud POST para crear un nuevo ranking de usuario const response = await request(app) - .post('/createUserRank') // Cambio en el endpoint - .send({ usernames: users.map(user => user.username) }); + .post('/createUserRank') + .send({ username }); // Enviamos solo el nombre de usuario // Verificar el código de estado de la respuesta expect(response.status).toBe(200); - // Verificar si se crearon correctamente los nuevos rankings de usuario en la base de datos - for (const user of users) { - const createdUserRank = await UserRank.findOne({ username: user.username }); - expect(createdUserRank).toBeTruthy(); - expect(createdUserRank.username).toBe(user.username); - } + // Verificar si se creó correctamente el nuevo ranking de usuario en la base de datos + const createdUserRank = await UserRank.findOne({ username }); + expect(createdUserRank).toBeTruthy(); + expect(createdUserRank.username).toBe(username); }); }); @@ -110,16 +104,27 @@ describe('User Service', () => { describe('User Service (Negative Tests)', () => { // Prueba negativa para el endpoint POST /createUserRank describe('POST /createUserRank (Negative Test)', () => { - it('should return 400 if username is missing', async () => { - // Realizar una solicitud POST sin proporcionar el nombre de usuario + it('should not create new user rank if user already exists', async () => { + const existingUser = new UserRank({ + username: 'existinguser', + porcentajeAciertos: 50, + preguntasCorrectas: 20, + preguntasFalladas: 10, + numPartidas: 5 + }); + await existingUser.save(); + + // Realizar una solicitud POST para crear un nuevo ranking de usuario con el mismo nombre de usuario const response = await request(app) .post('/createUserRank') - .send({}); - + .send({ username: existingUser.username }); // Enviamos solo el nombre de usuario existente + // Verificar el código de estado de la respuesta - expect(response.status).toBe(400); - // Verificar si el cuerpo de la respuesta contiene un mensaje de error - expect(response.body.error).toBeTruthy(); + expect(response.status).toBe(200); + + // Verificar que no se haya creado un nuevo ranking para el usuario existente + const userRankCount = await UserRank.countDocuments({ username: existingUser.username }); + expect(userRankCount).toBe(1); // Debería seguir siendo solo 1 (el existente) }); }); From 00ed1165061c27820373dfec187b714b7adc65d8 Mon Sep 17 00:00:00 2001 From: uo283055 Date: Fri, 26 Apr 2024 21:43:18 +0200 Subject: [PATCH 6/9] edit tests --- users/rankingservice/ranking-service.test.js | 35 ++++---------------- 1 file changed, 7 insertions(+), 28 deletions(-) diff --git a/users/rankingservice/ranking-service.test.js b/users/rankingservice/ranking-service.test.js index b0b56e64..fff728e5 100644 --- a/users/rankingservice/ranking-service.test.js +++ b/users/rankingservice/ranking-service.test.js @@ -25,22 +25,17 @@ afterEach(async () => { describe('User Service', () => { // Prueba para el endpoint POST /createUserRank describe('POST /createUserRank', () => { - it('should create new user rank if user does not exist', async () => { - const username = 'testuser1'; - - // Realizar una solicitud POST para crear un nuevo ranking de usuario + it('should create a new user rank if the user does not exist', async () => { + const newUser = { username: 'testUser' }; + const response = await request(app) .post('/createUserRank') - .send({ username }); // Enviamos solo el nombre de usuario - - // Verificar el código de estado de la respuesta + .send(newUser); + expect(response.status).toBe(200); - - // Verificar si se creó correctamente el nuevo ranking de usuario en la base de datos - const createdUserRank = await UserRank.findOne({ username }); - expect(createdUserRank).toBeTruthy(); - expect(createdUserRank.username).toBe(username); + expect(response.body.message).toBe('Rankings de usuarios creados o actualizados correctamente.'); }); + }); // Prueba para el endpoint POST /updateRanking @@ -165,22 +160,6 @@ describe('User Service', () => { }); -test('POST /createUserRank creates or resets a user ranking', async () => { - const username = 'testUser'; - - const response = await request(app) - .post('/createUserRank') - .send({ usernames: [username] }); - - expect(response.status).toBe(200); - expect(response.body.message).toBe('Rankings de usuarios creados o actualizados correctamente.'); - - const userRank = await UserRank.findOne({ username }); - expect(userRank.preguntasCorrectas).toBe(0); - expect(userRank.preguntasFalladas).toBe(0); - expect(userRank.numPartidas).toBe(0); -}); - test('GET /obtainRank gets all user rankings', async () => { const response = await request(app).get('/obtainRank'); From 7572995828875f64231ecd35c021c02cc98d71e0 Mon Sep 17 00:00:00 2001 From: uo283055 Date: Fri, 26 Apr 2024 21:50:32 +0200 Subject: [PATCH 7/9] edit tests --- users/rankingservice/ranking-service.test.js | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/users/rankingservice/ranking-service.test.js b/users/rankingservice/ranking-service.test.js index fff728e5..18244b16 100644 --- a/users/rankingservice/ranking-service.test.js +++ b/users/rankingservice/ranking-service.test.js @@ -22,22 +22,6 @@ afterEach(async () => { await UserRank.deleteMany({}); }); -describe('User Service', () => { - // Prueba para el endpoint POST /createUserRank - describe('POST /createUserRank', () => { - it('should create a new user rank if the user does not exist', async () => { - const newUser = { username: 'testUser' }; - - const response = await request(app) - .post('/createUserRank') - .send(newUser); - - expect(response.status).toBe(200); - expect(response.body.message).toBe('Rankings de usuarios creados o actualizados correctamente.'); - }); - - }); - // Prueba para el endpoint POST /updateRanking describe('POST /updateRanking', () => { it('should update an existing user rank', async () => { From 73cfe3192440839b15bed89a13fef3e365284e7d Mon Sep 17 00:00:00 2001 From: uo283055 Date: Fri, 26 Apr 2024 21:56:45 +0200 Subject: [PATCH 8/9] edit tests --- users/rankingservice/ranking-service.test.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/users/rankingservice/ranking-service.test.js b/users/rankingservice/ranking-service.test.js index 18244b16..fab33138 100644 --- a/users/rankingservice/ranking-service.test.js +++ b/users/rankingservice/ranking-service.test.js @@ -22,6 +22,8 @@ afterEach(async () => { await UserRank.deleteMany({}); }); +describe('User Service', () => { + // Prueba para el endpoint POST /updateRanking describe('POST /updateRanking', () => { it('should update an existing user rank', async () => { From 44a8edb987ef7862971f0674483ec2c0a703b879 Mon Sep 17 00:00:00 2001 From: uo283055 Date: Fri, 26 Apr 2024 21:59:22 +0200 Subject: [PATCH 9/9] siguiente edit tests --- users/rankingservice/ranking-service.test.js | 40 +++++++------------- 1 file changed, 14 insertions(+), 26 deletions(-) diff --git a/users/rankingservice/ranking-service.test.js b/users/rankingservice/ranking-service.test.js index fab33138..f15c1059 100644 --- a/users/rankingservice/ranking-service.test.js +++ b/users/rankingservice/ranking-service.test.js @@ -23,6 +23,20 @@ afterEach(async () => { }); describe('User Service', () => { + // Prueba para el endpoint POST /createUserRank + describe('POST /createUserRank', () => { + it('should create a new user rank if the user does not exist', async () => { + const newUser = { username: 'testUser' }; + + const response = await request(app) + .post('/createUserRank') + .send(newUser); + + expect(response.status).toBe(200); + expect(response.body.message).toBe('Rankings de usuarios creados o actualizados correctamente.'); + }); + + }); // Prueba para el endpoint POST /updateRanking describe('POST /updateRanking', () => { @@ -153,32 +167,6 @@ test('GET /obtainRank gets all user rankings', async () => { expect(Array.isArray(response.body)).toBe(true); }); -it('should reset an existing user rank', async () => { - // Arrange - const username = 'testUser'; - const initialUserRank = new UserRank({ - username, - porcentajeAciertos: 50, - preguntasCorrectas: 10, - preguntasFalladas: 10, - numPartidas: 1 - }); - await initialUserRank.save(); - - // Act - await request(app) - .post('/createUserRank') - .send({ usernames: [username] }) - .expect(200); - - // Assert - const updatedUserRank = await UserRank.findOne({ username }); - expect(updatedUserRank.porcentajeAciertos).toBe(0); - expect(updatedUserRank.preguntasCorrectas).toBe(0); - expect(updatedUserRank.preguntasFalladas).toBe(0); - expect(updatedUserRank.numPartidas).toBe(0); -}); - describe('GET /obtainRank', () => { it('it should GET all the rankings', async () => { const response = await request(app).get('/obtainRank');