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

Some fixes on tests #77

Closed
wants to merge 11 commits into from
5 changes: 2 additions & 3 deletions docs/src/09_architecture_decisions.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ ifndef::imagesdir[:imagesdir: ../images]
== Architecture Decisions


[role="arc42help"]
****

.Contents
Important, expensive, large scale or risky architecture decisions including rationales.
With "decisions" we mean selecting one alternative based on given criteria.
Expand All @@ -32,4 +31,4 @@ With "decisions" we mean selecting one alternative based on given criteria.
|====


****

43 changes: 27 additions & 16 deletions questions/creationservice/creation-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,40 +7,51 @@ const port = 8005;

app.use(express.json());

const optionsNumber = 4;

// It will be the country of the question
var country= "";
var questionObject= "";
// It will be the correct capital of the question
var capitalCorrect = "";
var correctOption = "";
// It will be the different options for the answers
var capitalOptions = [];
var answerOptions = [];

var randomQuerySelector;
// Array of the possible queries
var queries = ['SELECT DISTINCT ?questionObject ?questionObjectLabel ?answer ?answerLabel WHERE { ?questionObject wdt:P31 wd:Q6256. ?questionObject wdt:P36 ?answer. SERVICE wikibase:label {bd:serviceParam wikibase:language "[AUTO_LANGUAGE],es".}}'];
// Array of the possible questions
var questions = ["¿Cual es la capital de "];

// Recieves the information of the query and select wich data use on the question (country and capitals)
function getQuestionInfo(info){
capitalOptions = [];
fourRows = [];
answerOptions = [];
var fourRows = [];
const numEles = info.length;

// Select 4 random rows of the data
for (let i = 0; i<4; i++){
for (let i = 0; i<optionsNumber; i++){
var indexRow = Math.floor(Math.random() * numEles);
fourRows.push(info[indexRow]);
// Store the 4 posible answers
capitalOptions.push(info[indexRow].capitalLabel.value);
answerOptions.push(info[indexRow].answerLabel.value);
}

// Select the row where it will extract the country and capital
const indexQuestion = Math.floor(Math.random() * 4);
var indexQuestion = Math.floor(Math.random() * optionsNumber);
// Store the country choosen and its capital
country=fourRows[indexQuestion].countryLabel.value;
capitalCorrect = fourRows[indexQuestion].capitalLabel.value;
questionObject= questions[randomQuerySelector] + fourRows[indexQuestion].questionObjectLabel.value + "?";
correctOption = fourRows[indexQuestion].answerLabel.value;
}

function selectRandomQuery(){
randomQuerySelector = Math.floor(Math.random() * queries.length);
}

app.post('/createquestion', async (req, res) => {
const sparqlQuery = 'SELECT DISTINCT ?country ?countryLabel ?capital ?capitalLabel WHERE { ?country wdt:P31 wd:Q6256. ?country wdt:P36 ?capital. SERVICE wikibase:label {bd:serviceParam wikibase:language "[AUTO_LANGUAGE],es".}}';
const apiUrl = `https://query.wikidata.org/sparql?query=${encodeURIComponent(sparqlQuery)}&format=json`;
selectRandomQuery();
const apiUrl = `https://query.wikidata.org/sparql?query=${encodeURIComponent(queries[randomQuerySelector])}&format=json`;

try {

// Makes the petition to the url
const response = await fetch(apiUrl, {
headers: {
Expand All @@ -62,9 +73,9 @@ app.post('/createquestion', async (req, res) => {

// Declare what will be return
solution = {
responseCountry : country,
responseCapitalCorrect : capitalCorrect,
responseCapitalOptions : capitalOptions
responseQuestionObject : questionObject,
responseCorrectOption : correctOption,
responseAnswerOptions : answerOptions
};

// Return the resoult with a 200 status
Expand Down
20 changes: 6 additions & 14 deletions webapp/src/App.test.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,13 @@
/*
import { render, screen } from '@testing-library/react';
import {BrowserRouter as Router} from "react-router-dom";
import App from './App';

test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/Welcome to the 2024 edition of the Software Architecture course/i);
render(
<Router>
<App />
</Router>);
const linkElement = screen.getByText(/Bienvenido a WIQ 2024 del curso de Arquitectura del Software/i);
expect(linkElement).toBeInTheDocument();
});
*/
import React from 'react';
import { render } from '@testing-library/react';
import App from './App';

describe('./App', () => {
it('should render the component without crashing', () => {
// Render the component
render(<App />);

});
});
18 changes: 2 additions & 16 deletions webapp/src/components/AddUser.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/*
import React from 'react';
import { render, fireEvent, screen, waitFor } from '@testing-library/react';
import axios from 'axios';
Expand All @@ -17,7 +16,7 @@ describe('AddUser component', () => {

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
const addUserButton = screen.getByRole('button', { name: /Add User/i });
const addUserButton = screen.getByRole('button', { name: /Crear usuario/i });

// Mock the axios.post request to simulate a successful response
mockAxios.onPost('http://localhost:8000/adduser').reply(200);
Expand All @@ -40,7 +39,7 @@ describe('AddUser component', () => {

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
const addUserButton = screen.getByRole('button', { name: /Add User/i });
const addUserButton = screen.getByRole('button', { name: /Crear usuario/i });

// Mock the axios.post request to simulate an error response
mockAxios.onPost('http://localhost:8000/adduser').reply(500, { error: 'Internal Server Error' });
Expand All @@ -58,18 +57,5 @@ describe('AddUser component', () => {
});
});
});
*/

import AddUser from './AddUser';
import React from 'react';
import { render } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom'; // Import BrowserRouter


describe('./AddUser', () => {
it('should render the Login component without crashing', () => {
// Wrap Login within BrowserRouter to provide routing context
render(<BrowserRouter><AddUser /></BrowserRouter>);
});
});

21 changes: 9 additions & 12 deletions webapp/src/components/Game.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ const colorOnMousePreguntas= 'rgba(28, 84, 106, 0.764)';
const Game = () => {
const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000';

const [country, setCountry] = useState('');
const [capitalCorrect, setCapitalCorrect] = useState('');
const [capitalOptions, setcapitalOptions] = useState([]);
const [questionObject, setQuestionObject] = useState('');
const [correctOption, setCorrectOption] = useState('');
const [answerOptions, setAnswerOptions] = useState([]);
const [correctCounter, setCorrectCounter] = useState(0);

const [questionCounter, setQuestionCounter] = useState(0);
Expand Down Expand Up @@ -43,9 +43,9 @@ const Game = () => {
// It makes a petition to the api and store the response
const response = await axios.post(`${apiEndpoint}/createquestion`, { });
// Extract all the info of the response and store it
setCountry(response.data.responseCountry);
setCapitalCorrect(response.data.responseCapitalCorrect);
setcapitalOptions(response.data.responseCapitalOptions);
setQuestionObject(response.data.responseQuestionObject);
setCorrectOption(response.data.responseCorrectOption);
setAnswerOptions(response.data.responseAnswerOptions);
const buttons = document.querySelectorAll('button[title="btnsPreg"]');
buttons.forEach(button => {
button.name = "sinContestar";
Expand All @@ -64,7 +64,7 @@ const Game = () => {
const handleAnswerClick = (option, index) => {
// Get what component is the button to change its color later
//const button = document.getElementById(`button_${index}`);
if(option === capitalCorrect) {
if(option === correctOption) {
const buttonId = `button_${index}`;
const correctButton = document.getElementById(buttonId);
if (correctButton) {
Expand All @@ -88,9 +88,6 @@ const Game = () => {
setTimeout(() => {
handleShowQuestion();
}, 1500);



}

const incrementCorrect = () => {
Expand All @@ -112,10 +109,10 @@ const Game = () => {
Saber y Ganar Juego
</Typography>
<Typography variant="body1" paragraph>
Pregunta {questionCounter}: ¿Cuál es la capital de {country}?
Pregunta {questionCounter}: ¿Cuál es la capital de {questionObject}?
</Typography>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', alignItems: 'center', marginTop: '2em' }}>
{capitalOptions.map((option, index) => (
{answerOptions.map((option, index) => (
<Button id={`button_${index}`} title="btnsPreg" key={index} variant="contained" color="primary" onClick={() => handleAnswerClick(option,index)} >
{option}
</Button>
Expand Down
40 changes: 13 additions & 27 deletions webapp/src/components/Login.test.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/*
import React from 'react';
import { render, fireEvent, screen, waitFor, act } from '@testing-library/react';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import {BrowserRouter as Router} from "react-router-dom";
import Login from './Login';

const mockAxios = new MockAdapter(axios);
Expand All @@ -13,11 +13,14 @@ describe('Login component', () => {
});

it('should log in successfully', async () => {
render(<Login />);
render(
<Router>
<Login />
</Router>);

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
const loginButton = screen.getByRole('button', { name: /Login/i });
const loginButton = screen.getByRole('button', { name: /Iniciar sesión/i });

// Mock the axios.post request to simulate a successful response
mockAxios.onPost('http://localhost:8000/login').reply(200, { createdAt: '2024-01-01T12:34:56Z' });
Expand All @@ -28,18 +31,17 @@ describe('Login component', () => {
fireEvent.change(passwordInput, { target: { value: 'testPassword' } });
fireEvent.click(loginButton);
});

// Verify that the user information is displayed
expect(screen.getByText(/Hello testUser!/i)).toBeInTheDocument();
expect(screen.getByText(/Your account was created on 1\/1\/2024/i)).toBeInTheDocument();
});

it('should handle error when logging in', async () => {
render(<Login />);
render(
<Router>
<Login />
</Router>);

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
const loginButton = screen.getByRole('button', { name: /Login/i });
const loginButton = screen.getByRole('button', { name: /Iniciar sesión/i });

// Mock the axios.post request to simulate an error response
mockAxios.onPost('http://localhost:8000/login').reply(401, { error: 'Unauthorized' });
Expand All @@ -56,21 +58,5 @@ describe('Login component', () => {
expect(screen.getByText(/Error: Unauthorized/i)).toBeInTheDocument();
});

// Verify that the user information is not displayed
expect(screen.queryByText(/Hello testUser!/i)).toBeNull();
expect(screen.queryByText(/Your account was created on/i)).toBeNull();
});
});
*/

import React from 'react';
import { render } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom'; // Import BrowserRouter
import Login from './Login'; // Assuming Login is the component under test

describe('./Login', () => {
it('should render the Login component without crashing', () => {
// Wrap Login within BrowserRouter to provide routing context
render(<BrowserRouter><Login /></BrowserRouter>);
});
});
});
});
Loading