From 7dd2568122b235e3cb96719b9fad70e007b0f386 Mon Sep 17 00:00:00 2001 From: carlospelazas Date: Wed, 1 May 2024 19:31:00 +0200 Subject: [PATCH 1/3] tests for create and join group --- game/groupservice/GroupController.js | 43 ++-- game/groupservice/group-service.test.js | 252 +++++++++++------------- 2 files changed, 141 insertions(+), 154 deletions(-) diff --git a/game/groupservice/GroupController.js b/game/groupservice/GroupController.js index 3f41e600..674f9b6a 100644 --- a/game/groupservice/GroupController.js +++ b/game/groupservice/GroupController.js @@ -76,12 +76,12 @@ let GroupController = { createGroup: async (req,res) =>{ try{ - requiredFields =['groupName','creatorUUID','description','isPublic'] + let requiredFields =['groupName','creatorUUID','description','isPublic'] validateRequiredFields(req,requiredFields); - + console.log(req.body) let newGroup; - if(req.body.isPublic){ + if(req.body.isPublic){ newGroup = new Group({ admin: req.body.creatorUUID, members: [req.body.creatorUUID], @@ -92,25 +92,24 @@ let GroupController = { groupName: req.body.groupName, uuid: uuid.v4(), }) - await newGroup.save(); - - } else { - const joinCode = generateJoinCode(); - - newGroup = new Group({ - groupName: req.body.groupName, - admin: req.body.creatorUUID, - members: [req.body.creatorUUID], - maxNumUsers: maxNumUsers, - description: req.body.description, - isPublic: false, - joinCode: joinCode, - creationDate: Date(), - uuid: uuid.v4(), - }); - await newGroup.save(); - } - res.json(newGroup); + } else { + const joinCode = generateJoinCode(); + newGroup = new Group({ + groupName: req.body.groupName, + admin: req.body.creatorUUID, + members: [req.body.creatorUUID], + maxNumUsers: maxNumUsers, + description: req.body.description, + isPublic: false, + joinCode: joinCode, + creationDate: Date(), + uuid: uuid.v4(), + }); + } + console.log(newGroup) + const savedGroup = await newGroup.save() + console.log(savedGroup) + res.json(savedGroup); } catch(error){ res.status(500).json({error: error.message}) diff --git a/game/groupservice/group-service.test.js b/game/groupservice/group-service.test.js index 81adad56..b4f32260 100644 --- a/game/groupservice/group-service.test.js +++ b/game/groupservice/group-service.test.js @@ -1,18 +1,17 @@ const request = require('supertest'); const { MongoMemoryServer } = require('mongodb-memory-server'); -const mongoose = require('mongoose'); -const app = require('./group-service'); // Replace 'your-app-file' with the filename where your app is defined const Group = require('./group-model'); -const uuid = require('uuid'); let mongoServer; +let app; describe('Group Service API Tests', () => { beforeAll(async () => { mongoServer = await MongoMemoryServer.create(); const mongoUri = mongoServer.getUri(); process.env.MONGODB_URI = mongoUri; - }); + app = require('./group-service'); + }); afterAll(async () => { app.close(); @@ -25,152 +24,141 @@ describe('Group Service API Tests', () => { expect(response.body.message).toBe('Welcome to group service module'); }); - it('POST /joinGroup should join a user to a group with valid data', async () => { - const uuidGroup = uuid.v4(); - const admin = uuid.v4(); - const group = new Group({ - groupName: 'Test Group', - members: [admin], - isPublic: true, - admin: admin, - uuid: uuidGroup, - joinCode: '123456', - description: 'Test group', - creationDate: Date(), - maxNumUsers: 10, - }); - await group.save(); + it('should create a group when all required fields are provided public group', async () => { + // Prepare request body with all required fields + const requestBody = { + groupName: 'Test Group1', + creatorUUID: 'creator_id1', + description: 'Test description', + isPublic: true + }; + + const response = await request(app).post('/createGroup').send(requestBody); + expect(response.status).toBe(200); + + // Expect response body to contain the created group + expect(response.body).toHaveProperty('groupName', requestBody.groupName); + expect(response.body).toHaveProperty('admin', requestBody.creatorUUID); + expect(response.body).toHaveProperty('description', requestBody.description); + expect(response.body).toHaveProperty('isPublic', requestBody.isPublic); + expect(response.body).toHaveProperty('uuid'); + }); - const newUserUUID = uuid.v4(); - const joinData = { - uuid: newUserUUID, - groupName: 'Test Group', + it('should create a group when all required fields are provided private group', async () => { + // Prepare request body with all required fields + const requestBody = { + groupName: 'Test Group2', + creatorUUID: 'creator_id2', + description: 'Test description', + isPublic: false }; - const res = await request(app) - .post('/joinGroup') - .send(joinData) - .expect(200); + const response = await request(app).post('/createGroup').send(requestBody); + expect(response.status).toBe(200); - await Group.findOneAndDelete({uuid: uuidGroup}); - expect(res.body.members).toContain(newUserUUID); + // Expect response body to contain the created group + expect(response.body).toHaveProperty('groupName', requestBody.groupName); + expect(response.body).toHaveProperty('admin', requestBody.creatorUUID); + expect(response.body).toHaveProperty('description', requestBody.description); + expect(response.body).toHaveProperty('isPublic', requestBody.isPublic); + expect(response.body).toHaveProperty('uuid'); + expect(response.body).toHaveProperty('joinCode'); +}); + + it('should return status 500 when one or more required fields are missing', async () => { + const requestBody = { + groupName: 'Test Group', + creatorUUID: 'creator_id', + }; + + const response = await request(app).post('/createGroup').send(requestBody); + expect(response.status).toBe(500); + expect(response.body).toHaveProperty('error', expect.stringContaining('Missing required field')); }); - it('POST /joinGroup should return an error if the user is already in the group', async () => { - const uuidGroup = uuid.v4(); - const admin = uuid.v4(); - const testUser = uuid.v4(); - const group = new Group({ - groupName: 'Test Group2', - members: [admin, testUser], - isPublic: true, - admin: admin, - uuid: uuidGroup, - joinCode: '123456', - description: 'Test group2', - creationDate: Date(), - maxNumUsers: 10, + it('should successfully add user to the group', async () => { + const group = await Group.create({ + uuid: 'successfully_added_group_uuid', + groupName: 'Succesfully added Test Group', + admin: 'admin_id', + members: ['admin_id'], + maxNumUsers: 5, + isPublic: true, }); - await group.save(); - const joinData = { - uuid: testUser, - groupName: 'Test Group2', + const requestBody = { + uuid: 'user_to_join_uuid', + groupName: 'Succesfully added Test Group', }; - const res = await request(app) - .post('/joinGroup') - .send(joinData) - .expect(200); - - await Group.findOneAndDelete({uuid: uuidGroup}); - expect(res.body.message).toBe('User is already in this group'); - }); - - it('POST /leaveGroup should remove a user from the group with valid data', async () => { - const uuidGroup = uuid.v4(); - const admin = uuid.v4(); - const testUser = uuid.v4(); - const group = new Group({ - groupName: 'Test Group2', - members: [admin, testUser], - isPublic: true, - admin: admin, - uuid: uuidGroup, - joinCode: '123456', - description: 'Test group2', - creationDate: Date(), - maxNumUsers: 10, + const response = await request(app).post('/joingroup').send(requestBody); + expect(response.status).toBe(200); + expect(response.body).toHaveProperty('members'); + expect(response.body.members).toContain(requestBody.uuid); +}); + +it('should return message when user is already in the group', async () => { + const group = await Group.create({ + uuid: 'user_already_in_group_uuid', + groupName: 'User already in group Test Group', + members: ['userInGroup_id', 'admin_id'], + admin: 'admin_id', + maxNumUsers: 5, + isPublic: true }); - await group.save(); - const leaveData = { - expelledUUID: testUser, - groupName: 'Test Group2', - adminUUID: admin + const requestBody = { + uuid: 'userInGroup_id', + groupName: 'User already in group Test Group' }; - const res = await request(app) - .post('/leaveGroup') - .send(leaveData) - .expect(200); - - await Group.findOneAndDelete({uuid: uuidGroup}); - expect(res.body.members).not.toContain(testUser); + const response = await request(app).post('/joingroup').send(requestBody); + expect(response.status).toBe(200); + expect(response.body).toEqual({ message: 'User is already in this group' }); +}); + +it('should return message when group is full', async () => { + const group = await Group.create({ + uuid: 'full_group_uuid', + groupName: 'Full group Test Group', + members: Array(30).fill("member_uuid"), + admin: 'admin_id', + maxNumUsers: 30, + isPublic: true, }); - it('POST /leaveGroup should assign a new admin if the expelled user was the admin', async () => { - const uuidGroup = uuid.v4(); - const admin = uuid.v4(); - const testUser = uuid.v4(); - const group = new Group({ - groupName: 'Test Group2', - members: [admin, testUser], - isPublic: true, - admin: admin, - uuid: uuidGroup, - joinCode: '123456', - description: 'Test group2', - creationDate: Date(), - maxNumUsers: 10, - }); - await group.save(); + const requestBody = { + uuid: 'userToJoinFullGroup_id', + groupName: 'Full group Test Group' + }; + + const response = await request(app).post('/joingroup').send(requestBody); + expect(response.status).toBe(200); + expect(response.body).toEqual({ message: 'This group is full' }); +}); + +it('should return message when join code is incorrect for a private group', async () => { + const group = await Group.create({ + uuid: 'incorrect_join_code_group_uuid', + groupName: 'Test Group Incorrect Join Code', + members: ['admin_id'], + maxNumUsers: 5, + admin: 'admin_id', + isPublic: false, + joinCode: 'correct_join_code' + }); - const leaveData = { - expelledUUID: admin, - groupName: 'Test Group2', - adminUUID: admin - }; + const requestBody = { + uuid: 'user_id', + groupName: 'Test Group Incorrect Join Code', + joinCode: 'incorrect_join_code' + }; - const res = await request(app) - .post('/leaveGroup') - .send(leaveData) - .expect(200); + const response = await request(app).post('/joingroup').send(requestBody); - await Group.findOneAndDelete({uuid: uuidGroup}); - expect(res.body.members).not.toContain(admin); - expect(res.body.admin).toBe(testUser); - }); + expect(response.status).toBe(200); + expect(response.body).toEqual({ message: 'Invalid join code' }); +}); - it('POST /createGroup should create a public group with valid data', async () => { - const admin = uuid.v4(); - const groupData = { - groupName: 'Public Test Group', - creatorUUID: admin, - description: 'This is a public test group', - isPublic: true - }; - const res = await request(app) - .post('/createGroup') - .send(groupData) - .expect(200); - - await Group.findOneAndDelete({uuid: res.body.uuid}); // Delete the group after testing - expect(res.body.groupName).toBe(groupData.groupName); - expect(res.body.admin).toBe(groupData.creatorUUID); - expect(res.body.members).toContain(groupData.creatorUUID); - expect(res.body.isPublic).toBe(true); - - }); -}); \ No newline at end of file +}) \ No newline at end of file From 75fd51371c13585230bdf3b31565694b4a152870 Mon Sep 17 00:00:00 2001 From: carlospelazas Date: Wed, 1 May 2024 20:26:04 +0200 Subject: [PATCH 2/3] group service tests --- game/groupservice/GroupController.js | 15 +- game/groupservice/group-service.js | 2 +- game/groupservice/group-service.test.js | 227 +++++++++++++++++++++++- 3 files changed, 230 insertions(+), 14 deletions(-) diff --git a/game/groupservice/GroupController.js b/game/groupservice/GroupController.js index 674f9b6a..ec9ee715 100644 --- a/game/groupservice/GroupController.js +++ b/game/groupservice/GroupController.js @@ -35,20 +35,17 @@ let GroupController = { res.json(response); }catch(error){ - console.log(error) - res.status(400).json({error: error.message}) + res.status(500).json({error: error.message}) } }, leaveGroup: async (req,res) => { try{ - console.log(req.body) requiredFields = ['expelledUUID','groupName', 'adminUUID'] validateRequiredFields(req, requiredFields); const group = await getGroupByName(req.body.groupName); - console.log(req.body.adminUUID +" - "+ req.body.expelledUUID) + if(req.body.adminUUID != group.admin && req.body.adminUUID != req.body.expelledUUID){ - console.log("entra en la condicion") res.json({ message: 'User is unable to perform this operation' }); return; } @@ -78,7 +75,6 @@ let GroupController = { let requiredFields =['groupName','creatorUUID','description','isPublic'] validateRequiredFields(req,requiredFields); - console.log(req.body) let newGroup; if(req.body.isPublic){ @@ -106,9 +102,7 @@ let GroupController = { uuid: uuid.v4(), }); } - console.log(newGroup) const savedGroup = await newGroup.save() - console.log(savedGroup) res.json(savedGroup); } catch(error){ @@ -143,9 +137,8 @@ let GroupController = { async function getGroupByName(name) { try { const group = await Group.findOne({ groupName: name }); - if (!group) { - throw new Error('This group does not exist'); + throw new Error('This group does not exist'); } return group; @@ -163,4 +156,4 @@ function validateRequiredFields(req, requiredFields) { } } -module.exports = GroupController; \ No newline at end of file +module.exports = {GroupController, getGroupByName}; \ No newline at end of file diff --git a/game/groupservice/group-service.js b/game/groupservice/group-service.js index ddf87c7b..402e3299 100644 --- a/game/groupservice/group-service.js +++ b/game/groupservice/group-service.js @@ -1,6 +1,6 @@ const express = require('express'); const mongoose = require('mongoose'); -const GroupController = require('./GroupController'); +const {GroupController} = require('./GroupController'); const app = express(); const port = 8005; diff --git a/game/groupservice/group-service.test.js b/game/groupservice/group-service.test.js index b4f32260..48afe168 100644 --- a/game/groupservice/group-service.test.js +++ b/game/groupservice/group-service.test.js @@ -1,6 +1,7 @@ const request = require('supertest'); const { MongoMemoryServer } = require('mongodb-memory-server'); const Group = require('./group-model'); +const { getGroupByName } = require('./GroupController') let mongoServer; let app; @@ -13,6 +14,11 @@ describe('Group Service API Tests', () => { app = require('./group-service'); }); + afterEach(async () => { + jest.restoreAllMocks(); + await Group.deleteMany({}); + }); + afterAll(async () => { app.close(); await mongoServer.stop(); @@ -122,7 +128,7 @@ it('should return message when group is full', async () => { uuid: 'full_group_uuid', groupName: 'Full group Test Group', members: Array(30).fill("member_uuid"), - admin: 'admin_id', + admin: 'admin_id2', maxNumUsers: 30, isPublic: true, }); @@ -141,7 +147,7 @@ it('should return message when join code is incorrect for a private group', asyn const group = await Group.create({ uuid: 'incorrect_join_code_group_uuid', groupName: 'Test Group Incorrect Join Code', - members: ['admin_id'], + members: ['admin_id3'], maxNumUsers: 5, admin: 'admin_id', isPublic: false, @@ -159,6 +165,223 @@ it('should return message when join code is incorrect for a private group', asyn expect(response.status).toBe(200); expect(response.body).toEqual({ message: 'Invalid join code' }); }); +it('should return status 500 and error message when an error occurs', async () => { + const mockError = new Error('Internal server error'); + jest.spyOn(Group, 'findOne').mockRejectedValue(mockError); + const requestBody = { + uuid: 'user_id', + groupName: 'Test Group Failure' + }; + const response = await request(app).post('/joingroup').send(requestBody); + + expect(response.status).toBe(500); + expect(response.body).toEqual({ error: 'Internal server error' }); +}); + +it('should successfully remove user from the group', async () => { + const group = await Group.create({ + uuid: 'successfully_remove_member_group_uuid', + groupName: 'Succesfully remove member from Test Group', + members: ['user_id', 'admin_id4'], + admin: 'admin_id4', + isPublic: true, + maxNumUsers: 5 + }); + + const requestBody = { + expelledUUID: 'user_id', + groupName: 'Succesfully remove member from Test Group', + adminUUID: 'admin_id4' + }; + + const response = await request(app).post('/leaveGroup').send(requestBody); + expect(response.status).toBe(200); + expect(response.body).toHaveProperty('members'); + expect(response.body.members).not.toContain(requestBody.expelledUUID); +}); + +it('should successfully remove user from the group and remove the group when nobody is left', async () => { + const group = await Group.create({ + uuid: 'successfully_remove_member_group_and_remove_group_uuid', + groupName: 'Succesfully remove member, and group Test Group', + members: ['admin_id'], + admin: 'admin_id', + isPublic: true, + maxNumUsers: 5 + }); + + const requestBody = { + expelledUUID: 'admin_id', + groupName: 'Succesfully remove member, and group Test Group', + adminUUID: 'admin_id' + }; + + const response = await request(app).post('/leaveGroup').send(requestBody); + expect(response.status).toBe(200); + expect(response.body).toHaveProperty('message'); + expect(response.body.message).toEqual('Group deleted'); +}); + +it('should successfully remove user from the group and remove the group when nobody is left', async () => { + const group = await Group.create({ + uuid: 'successfully_remove_member_group_and_remove_group_uuid', + groupName: 'Succesfully remove member, and change admin group Test Group', + members: ['admin_id','user_id'], + admin: 'admin_id', + isPublic: true, + maxNumUsers: 5 + }); + + const requestBody = { + expelledUUID: 'admin_id', + groupName: 'Succesfully remove member, and change admin group Test Group', + adminUUID: 'admin_id' + }; + + const response = await request(app).post('/leaveGroup').send(requestBody); + expect(response.status).toBe(200); + expect(response.body).toHaveProperty('members'); + expect(response.body.members).not.toContain(requestBody.expelledUUID); + expect(response.body.admin).toBe('user_id'); +}); +it('should return message when user is unable to perform the operation leaveGroup', async () => { + const group = await Group.create({ + uuid: 'group_uuid', + groupName: 'Test Group', + members: ['user_id'], + admin: 'different_admin_id', + isPublic: true, + maxNumUsers: 5 + }); + const requestBody = { + expelledUUID: 'user_id', + groupName: 'Test Group', + adminUUID: 'admin_id' + }; + + const response = await request(app).post('/leavegroup').send(requestBody); + expect(response.status).toBe(200); + expect(response.body).toEqual({ message: 'User is unable to perform this operation' }); +}); + +it('should return status 500 and error message when an error occurs', async () => { + const mockError = new Error('Internal server error'); + jest.spyOn(Group, 'findOne').mockRejectedValue(mockError); + + const requestBody = { + expelledUUID: 'user_id', + groupName: 'Test Group', + adminUUID: 'admin_id' + }; + + const response = await request(app).post('/leavegroup').send(requestBody); + expect(response.status).toBe(500); + expect(response.body).toEqual({ error: 'Internal server error' }); +}); + +it('should return the group when it exists', async () => { + const group = { + uuid: 'group_uuid', + groupName: 'Test Group', + members: ['user_id'], + admin: 'different_admin_id', + isPublic: true, + maxNumUsers: 5 + }; + + const savedGroup = await Group.create(group); + const expectedResponse = { + _id: savedGroup._id.toString(), + __v: savedGroup.__v, + uuid: savedGroup.uuid, + groupName: savedGroup.groupName, + members: savedGroup.members, + admin: savedGroup.admin, + isPublic: savedGroup.isPublic, + maxNumUsers: savedGroup.maxNumUsers, + creationDate: savedGroup.creationDate.toISOString(), + }; + + const response = await request(app).get(`/getGroup/${group.uuid}`); + expect(response.status).toBe(200); + expect(response.body).toEqual(expectedResponse); +}); + +it('should return status 404 and error message when group is not found', async () => { + const response = await request(app).get('/getGroup/non_existent_uuid'); + expect(response.status).toBe(404); + expect(response.body).toEqual({ error: 'Group not found' }); +}); + +it('should return all groups', async () => { + // Create some groups in the database + const groups = [ + { + uuid: 'group_uuid1', + groupName: 'Test Group1', + members: ['user_id1'], + admin: 'admin_id1', + isPublic: true, + maxNumUsers: 5 + }, + { + uuid: 'group_uuid2', + groupName: 'Test Group2', + members: ['user_id2'], + admin: 'admin_id2', + isPublic: true, + maxNumUsers: 5 + }, + { + uuid: 'group_uuid3', + groupName: 'Test Group3', + members: ['user_id3'], + admin: 'admin_id3', + isPublic: true, + maxNumUsers: 5 + } + ]; + await Group.create(groups); + + const response = await request(app).get('/getGroups'); + expect(response.status).toBe(200); + expect(response.body).toBeInstanceOf(Array); + expect(response.body.length).toBe(3); + + // Assert that the names of the groups in the response match the expected names + expect(response.body.map(group => group.groupName)).toEqual( + expect.arrayContaining(groups.map(group => group.groupName)) + ); +}); + +it('should return status 500 and error message when an error occurs', async () => { + const mockError = new Error('Internal server error'); + jest.spyOn(Group, 'find').mockRejectedValue(mockError); + const response = await request(app).get('/getGroups'); + expect(response.status).toBe(500); + expect(response.body).toEqual({ error: 'Internal server error' }); +}); + +it('should return status 500 and error message when an error occurs', async () => { + // Mock the behavior of the findOne function to throw an error + const mockError = new Error('Internal server error'); + jest.spyOn(Group, 'findOne').mockRejectedValue(mockError); + + // Send request to get a group + const response = await request(app).get('/getGroup/group_uuid'); + + // Expect response status to be 500 + expect(response.status).toBe(500); + + // Expect response body to contain the error message + expect(response.body).toEqual({ error: 'Internal server error' }); +}); + +it('should throw an error with the message "This group does not exist"', async () => { + jest.spyOn(Group, 'findOne').mockResolvedValue(null); + + await expect(getGroupByName('NonExistentGroup')).rejects.toThrow('This group does not exist'); +}); }) \ No newline at end of file From f56e49a681d5bf06cd794078cf3d67e16f2a0683 Mon Sep 17 00:00:00 2001 From: carlospelazas Date: Wed, 1 May 2024 20:39:42 +0200 Subject: [PATCH 3/3] fix issue with test on game service --- game/gameservice/GameController.js | 8 +++----- game/gameservice/gameservice.js | 10 ++++++---- game/gameservice/queries/CreateGame.js | 4 ++-- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/game/gameservice/GameController.js b/game/gameservice/GameController.js index dfce9b6a..55d77926 100644 --- a/game/gameservice/GameController.js +++ b/game/gameservice/GameController.js @@ -1,6 +1,5 @@ let Game = require('./game-model'); const { createGame } = require('./queries/CreateGame'); -const mongoose = require('mongoose'); let GameController = { /* HACER EN USER - GET LAST GAME BY USER @@ -11,10 +10,9 @@ let GameController = { },*/ create: async (req, res) => { try{ - const { questions, players } = req.body; - console.log(questions, players) - const game = await createGame(questions, players); - res.json(game); + const { questions, players } = req.body; + const game = await createGame(questions, players); + res.json(game); } catch(error){ res.status(500).json({ message: error.message }); } diff --git a/game/gameservice/gameservice.js b/game/gameservice/gameservice.js index 9f365232..beb5f97b 100644 --- a/game/gameservice/gameservice.js +++ b/game/gameservice/gameservice.js @@ -1,15 +1,13 @@ // gameservice.js const express = require('express'); -const axios = require('axios'); const mongoose = require('mongoose'); -const { createGame } = require('./queries/CreateGame'); +const bodyParser = require('body-parser'); const GameController = require('./GameController'); const app = express(); const port = 8004; -// app.use(bodyParser.json()); -app.use(express.json()); +app.use(bodyParser.json()); const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/userdb'; mongoose.connect(mongoUri); @@ -29,4 +27,8 @@ const server = app.listen(port, () => { console.log(`Question generator Service listening at http://localhost:${port}`); }); +server.on('close', () => { + mongoose.connection.close(); +}); + module.exports = server; diff --git a/game/gameservice/queries/CreateGame.js b/game/gameservice/queries/CreateGame.js index d2732693..03daca65 100644 --- a/game/gameservice/queries/CreateGame.js +++ b/game/gameservice/queries/CreateGame.js @@ -5,10 +5,10 @@ const uuid = require('uuid') async function createGame(questions, players) { try { // Create a new Game instance - if(players.length == 0){ + if(players.length === 0){ throw new Error('No players found') } - if(players[0].uuid == null || players[0].uuid == undefined){ + if(players[0].uuid === null || players[0].uuid === undefined){ throw new Error('No players found') } const game = new Game({