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

nuevos tests e2e y arreglos en modos de juego #282

Merged
merged 23 commits into from
Apr 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
8ae112c
Merge pull request #274 from Arquisoft/develop
uo282189 Apr 25, 2024
80e8146
ahora el modo de juego de pregunta diaria deberia de devolver la preg…
uo282189 Apr 25, 2024
b5d31b2
actualizado nombre de la cookie para el questiondiaria
uo282189 Apr 25, 2024
53fbba7
pruebas para que se guarde bien lo de la questionDiaria
uo282189 Apr 25, 2024
e592f9a
question diaria deberia funcionar correctamente
uo282189 Apr 25, 2024
9693cb0
cambiado la forma de que salga el que el usuario ya ha jugado la preg…
uo282189 Apr 25, 2024
d46f3dc
actualizados los tests e2e del daily mode
uo282189 Apr 25, 2024
0a51b46
actualizado el modo diaria y ahora si, deberia funcionar bien
uo282189 Apr 25, 2024
fc7bfa7
intento de arreglar el modo categoria (pendiente probarlo porque mi o…
uo282189 Apr 25, 2024
d11136e
empezar los tests e2e del categoria y arreglar algunas cosas
uo282189 Apr 25, 2024
8be0fac
ya se pasa bien la url a los servicios falta mirar la categoria
uo282189 Apr 25, 2024
c83451c
arreglos para el modo de elegir categoria
uo282189 Apr 25, 2024
84deb37
empezar el test e2e del infinity
uo282189 Apr 25, 2024
032139d
Merge pull request #280 from Arquisoft/develop
uo282189 Apr 25, 2024
60c401c
test e2e del infinity game pasan correctamente
uo282189 Apr 25, 2024
fd2f97a
añadida internacionalizacion a los botones de las categorias
uo282189 Apr 25, 2024
4cf1198
añadida internacionalizacion a los botones de las categorias (se me o…
uo282189 Apr 25, 2024
b3101f1
cambiado eso en la internacionalizacion para que salga bien
uo282189 Apr 25, 2024
d928643
intento de reducir duplicidad en el userservice-test
uo282189 Apr 25, 2024
0324c2a
arreglado el test del home para la nueva url
uo282189 Apr 25, 2024
d8029ab
añadido test del category
uo282189 Apr 25, 2024
fc99847
deberian de pasar ya los tests del dailygame
uo282189 Apr 25, 2024
11a3e0b
ahora el test del sameCategory deberia funcionar
uo282189 Apr 25, 2024
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
1 change: 1 addition & 0 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const handleServiceRequest = async (req, res, serviceUrl) => {
};

app.post('/login', (req, res) => handleServiceRequest(req, res, serviceUrls.auth));
app.post('/updateUserDaily', (req, res) => handleServiceRequest(req, res, serviceUrls.auth));
app.post('/adduser', (req, res) => handleServiceRequest(req, res, serviceUrls.user));

//*********************ENDPOINTS DEL QUESTION SERVICE********************************************* */
Expand Down
3 changes: 1 addition & 2 deletions questionservice/question-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ app.get('/getQuestionDiaria', async(req,res)=> {
try{
const idioma = req.query.idioma;
const fecha = req.query.fecha;
console.log("idioma: "+idioma+" fecha: "+fecha);
//coger pregunta bd
const questions = await question.obtenerPreguntaDiaria(idioma, fecha);
//para devolver la pregunta
Expand All @@ -58,11 +59,9 @@ app.get('/getQuestionDiaria', async(req,res)=> {
});

app.get('/getQuestionModoBasico', async(req,res)=> {
console.log('entra en el getQuestionModoBasico del question Service');
try{
const idioma = req.query.idioma;

console.log("idioma",idioma);
//coger pregunta bd
const questions = await question.obtenerPregunta(10, idioma);
//para devolver la pregunta
Expand Down
2 changes: 1 addition & 1 deletion users/authservice/auth-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const userSchema = new mongoose.Schema({
username: String,
password: String,
createdAt: Date,
lastDailyGame: Date,
diaria: String,
});

const User = mongoose.model('User', userSchema);
Expand Down
42 changes: 41 additions & 1 deletion users/authservice/auth-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,17 @@ function validateRequiredFields(req, requiredFields) {
}
}

function getFecha() {
const fecha = new Date(); // Obtenemos la fecha actual
// como nos da tambien la hora y no queremos eso, la eliminamos
const año = fecha.getFullYear();
const mes = fecha.getMonth() + 1;
const dia = fecha.getDate();
// Formateamos la fecha para que sea compatible con la base de datos
const fechaSinHora = `${año}-${mes < 10 ? '0' : ''}${mes}-${dia < 10 ? '0' : ''}${dia}`;
return fechaSinHora;
}

// Route for user login
app.post('/login', async (req, res) => {
try {
Expand All @@ -38,8 +49,21 @@ app.post('/login', async (req, res) => {
if (user && await bcrypt.compare(password, user.password)) {
// Generate a JWT token
const token = jwt.sign({ userId: user._id }, 'your-secret-key', { expiresIn: '1h' });

let ultimaDiaria;

if(user.diaria === getFecha()){
let expiryDate = new Date();
expiryDate.setHours(24, 0, 0, 0);
//si no hay ese token lo creamos
ultimaDiaria = JSON.stringify({
value: 'valor que quieras almacenar',
expiry: expiryDate.getTime(),
});
}

// Respond with the token and user information
res.json({ token: token, username: username, createdAt: user.createdAt , lastDailyGame: user.lastDailyGame});
res.json({ token: token, username: username, createdAt: user.createdAt , lastDailyGame: ultimaDiaria});
} else {
res.status(401).json({ error: 'Credenciales erroneas' });
}
Expand All @@ -48,6 +72,22 @@ app.post('/login', async (req, res) => {
}
});

app.post('/updateUserDaily', async (req, res) => {
try {
console.log("Entra en el auth service del update")
if((req.body.user != null && req.body.fecha != null) || (req.body.user != undefined && req.body.fecha != undefined)){
var user = await User.findOneAndUpdate(
{ username:req.body.user, $or: [{ diaria: null }, { diaria: { $exists: true } }] },
{ $set: { diaria: req.body.fecha } }, // Establecer el valor de 'diaria' a la fecha proporcionada
{ new: true, upsert: true, strict: false } // Para devolver el documento actualizado y permitir campos no definidos en el esquema
);
}
res.json({ user: user});
} catch (error) {
res.status(400).json({ error: error.message });
}
});

// Start the server
const server = app.listen(port, () => {
console.log(`Auth Service listening at http://localhost:${port}`);
Expand Down
39 changes: 15 additions & 24 deletions users/userservice/user-service.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ afterAll(async () => {
});

describe('User Service', () => {

const addUserTest = async (userData, expectedStatus, expectedError) => {
const response = await request(app).post('/adduser').send(userData);
expect(response.status).toBe(expectedStatus);
expect(response.body.error).toBe(expectedError);
};

it('should add a new user on POST /adduser', async () => {
const newUser = {
email: 'test@email.com',
Expand All @@ -25,9 +32,7 @@ describe('User Service', () => {
passwordConfirm: 'Testpassword_1',
};

const response = await request(app).post('/adduser').send(newUser);
expect(response.status).toBe(200);
expect(response.body).toHaveProperty('email', 'username', 'testuser');
await addUserTest(newUser, 200, undefined);
});

it('should not add a new user on POST /adduser', async () => {
Expand All @@ -38,9 +43,7 @@ describe('User Service', () => {
passwordConfirm: 'Testpassword_1',
};

const response = await request(app).post('/adduser').send(newUser);
expect(response.status).toBe(400);
expect(response.body.error).toBe("Missing required field: username");
await addUserTest(newUser, 400, 'Missing required field: username');
});

//pruebas para el formato de las contraseñas
Expand All @@ -60,9 +63,7 @@ describe('User Service', () => {
"La contraseña tiene que tener al menos un carácter especial"
;

const response = await request(app).post('/adduser').send(newUser);
expect(response.status).toBe(400);
expect(response.body.error).toBe(errors);
await addUserTest(newUser, 400, errors);
});

it('should send an error because the password is incorrect on POST /adduser', async () => {
Expand All @@ -80,9 +81,7 @@ describe('User Service', () => {
"La contraseña tiene que tener al menos un carácter especial"
;

const response = await request(app).post('/adduser').send(newUser);
expect(response.status).toBe(400);
expect(response.body.error).toBe(errors);
await addUserTest(newUser, 400, errors);
});

//pruebas para comprobar el formato del email
Expand All @@ -95,9 +94,7 @@ describe('User Service', () => {
passwordConfirm: 'Testpassword_1',
};

const response = await request(app).post('/adduser').send(newUser);
expect(response.status).toBe(400);
expect(response.body.error).toBe('El email es invalido');
await addUserTest(newUser, 400, 'El email es invalido');
});

//pruebas para comprobar si el email o el username ya existe en la bd
Expand All @@ -110,9 +107,7 @@ describe('User Service', () => {
passwordConfirm: 'Testpassword_1',
};

const response = await request(app).post('/adduser').send(newUser);
expect(response.status).toBe(400);
expect(response.body.error).toBe('El email ya existe en la base de datos');
await addUserTest(newUser, 400, 'El email ya existe en la base de datos');
});

it('should send an error because the username already exist in the database on POST /adduser', async () => {
Expand All @@ -123,9 +118,7 @@ describe('User Service', () => {
passwordConfirm: 'Testpassword_1',
};

const response = await request(app).post('/adduser').send(newUser);
expect(response.status).toBe(400);
expect(response.body.error).toBe('El username ya existe en la base de datos');
await addUserTest(newUser, 400, 'El username ya existe en la base de datos');
});


Expand All @@ -139,9 +132,7 @@ it('should send an error because the passwords are not equals on POST /adduser',
passwordConfirm: 'Testpassword_2',
};

const response = await request(app).post('/adduser').send(newUser);
expect(response.status).toBe(400);
expect(response.body.error).toBe('Las contraseñas no coinciden');
await addUserTest(newUser, 400, 'Las contraseñas no coinciden');
});

});
10 changes: 10 additions & 0 deletions webapp/e2e/features/customCategoryMode-form.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Feature: Custom Category Mode

Scenario: The user is not registered in the site
Given An unregistered user
When I fill the data in the form and press submit
Then The user is logged

Scenario: User play the custom category game
When I play the game
Then I should see a message with my game results
2 changes: 1 addition & 1 deletion webapp/e2e/features/dailyQuestionMode-form.feature
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ Scenario: User play the daily question

Scenario: User wants to play the daily question but he/she/they already played it
When I try to play the daily question
Then I should see a message with a message
Then I should see a message
10 changes: 10 additions & 0 deletions webapp/e2e/features/infinityMode-form.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Feature: Infinity Mode

Scenario: The user is not registered in the site
Given An unregistered user
When I fill the data in the form and press submit
Then The user is logged

Scenario: User play the infinity mode
When I play the infinity mode
Then I should see a message with my game results
4 changes: 4 additions & 0 deletions webapp/e2e/steps/basicButtons-form.steps.js
Original file line number Diff line number Diff line change
Expand Up @@ -186,5 +186,9 @@ defineFeature(feature, test => {
await expect(page).toMatchElement("#loginButton");
});
})

afterAll(async ()=>{
browser.close()
})

});
98 changes: 98 additions & 0 deletions webapp/e2e/steps/customCategoryMode-form.steps.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
const puppeteer = require('puppeteer');
const { defineFeature, loadFeature }=require('jest-cucumber');
const setDefaultOptions = require('expect-puppeteer').setDefaultOptions
const feature = loadFeature('./features/customCategoryMode-form.feature');

let page;
let browser;

defineFeature(feature, test => {

beforeAll(async () => {
browser = process.env.GITHUB_ACTIONS
? await puppeteer.launch()
: await puppeteer.launch({ headless: false, slowMo: 20 });
page = await browser.newPage();
//Way of setting up the timeout
setDefaultOptions({ timeout: 10000 })

await page
.goto("http://localhost:3000/addUser", {
waitUntil: "networkidle0",
})
.catch(() => {});

});

afterEach(async () => {
await page.waitForTimeout(1000);

await page.goto("http://localhost:3000/home", {
waitUntil: "networkidle0",
});
});

//test para crear el usuario
test('The user is not registered in the site', ({given,when,then}) => {

let email;
let username;
let password;
let passwordConfirmation;

given('An unregistered user', async () => {
email = "userTestDailyQuestionGame@email.com"
username = "userTestDailyQuestionGame"
password = "Contraseña_1?"
passwordConfirmation = "Contraseña_1?"
});

when('I fill the data in the form and press submit', async () => {

await expect(page).toFill('input[name="email"]', email);
await expect(page).toFill('input[name="username"]', username);
await expect(page).toFill('input[name="password"]', password);
await expect(page).toFill('input[name="passwordConfirm"]', passwordConfirmation);

await expect(page).toClick('#addRegister');

await page.goto("http://localhost:3000/login", {
waitUntil: "networkidle0",
});

//nos logeamos con ese usuario
await expect(page).toFill('input[name="username"]', username);
await expect(page).toFill('input[name="password"]', password);

await expect(page).toClick('#login');
});

then('The user is logged', async () => {
await expect(page).toMatchElement("#iconoUsuario");
});
})

test('User play the custom category game', ({when,then}) => {

when('I play the game', async () => {
//como en la bd tenemos preguntas de arte vamos a elegir esa categoria
await expect(page).toClick("#button-samecat-game");
await expect(page).toClick("#button-category-art");

//empieza el juego y responde 10 preguntas
for(let i = 0; i < 10; i++){
await expect(page).toClick("#buttonAnswer0");
}
});

then('I should see a message with my game results', async () => {
//comprobamos que se ha acabado el juego
await expect(page).toMatchElement(".finDelJuego");
});
})

afterAll(async ()=>{
browser.close()
})

});
12 changes: 6 additions & 6 deletions webapp/e2e/steps/dailyQuestionMode-form.steps.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,6 @@ defineFeature(feature, test => {
test('User play the daily question', ({when,then}) => {

when('I play the daily question', async () => {
//vamos a las opciones del usuario
await expect(page).toClick("#button-diario-game");

//empieza el juego y respoonde la pregunta
Expand All @@ -91,15 +90,16 @@ defineFeature(feature, test => {
test('User wants to play the daily question but he/she/they already played it', ({when,then}) => {

when('I try to play the daily question', async () => {
//vamos a las opciones del usuario
await expect(page).toClick("#button-diario-game");

//pendiente de implementar
});

then('I should see a message with a message', async () => {
//pendiente de implementar
then('I should see a message', async () => {
await expect(page).toMatchElement(".yaJugoDiaria");
});
})

afterAll(async ()=>{
browser.close()
})

});
5 changes: 4 additions & 1 deletion webapp/e2e/steps/gameBasicMode-form.steps.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,10 @@ defineFeature(feature, test => {
await expect(page).toMatchElement(".finDelJuego");
});
})



afterAll(async ()=>{
browser.close()
})

});
Loading