Skip to content

Commit

Permalink
Merge pull request #172 from Arquisoft/integration-tests
Browse files Browse the repository at this point in the history
Some scenarios with Cucumber
  • Loading branch information
Pelayori authored Apr 7, 2024
2 parents ca7dd7e + b712fef commit c9f1eda
Show file tree
Hide file tree
Showing 28 changed files with 569 additions and 39 deletions.
1 change: 0 additions & 1 deletion src/main/java/com/uniovi/dto/AnswerDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class AnswerDto {
Expand Down
1 change: 0 additions & 1 deletion src/main/java/com/uniovi/dto/CategoryDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class CategoryDto {

Expand Down
1 change: 0 additions & 1 deletion src/main/java/com/uniovi/dto/PlayerDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class PlayerDto {
Expand Down
3 changes: 0 additions & 3 deletions src/main/java/com/uniovi/dto/RoleDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@
import lombok.*;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class RoleDto {

@Schema(description = "The name of the role", example = "ROLE_USER")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ public void insertSampleQuestions() throws InterruptedException {
generateSampleData();
}

@Transactional
public void generateTestQuestions() {
questionRepository.deleteAll();
questionService.testQuestions(4);
}

@Transactional
public void generateSampleData() throws InterruptedException {

Expand Down
10 changes: 9 additions & 1 deletion src/main/java/com/uniovi/services/QuestionService.java
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public interface QuestionService {

/**
* Update a question
* @param q The question to update
* @param id The id of the question to update
* @param questionDto The new data of the question
*/
void updateQuestion(Long id, QuestionDto questionDto);
Expand All @@ -97,4 +97,12 @@ public interface QuestionService {
* @param id The id of the question to delete
*/
void deleteQuestion(Long id);

/**
* Get some test questions
*
* @param num The number of questions to get
* @return The questions selected
*/
List<Question> testQuestions(int num);
}
6 changes: 0 additions & 6 deletions src/main/java/com/uniovi/services/RoleService.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,4 @@ public interface RoleService {
* @return The role with the given name
*/
Role getRole(String name);

/**
* Get all the roles in the database
* @return A list with all the roles
*/
List<Role> getRoles();
}
28 changes: 27 additions & 1 deletion src/main/java/com/uniovi/services/impl/QuestionServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public List<Question> getRandomQuestions(int num) {
List<Question> res = new ArrayList<>();
for (int i = 0; i < num; i++) {
int idx = random.nextInt(allQuestions.size());
while (allQuestions.get(idx).hasEmptyOptions()){
while (allQuestions.get(idx).hasEmptyOptions() || res.contains(allQuestions.get(idx))){
idx = random.nextInt(allQuestions.size());
}
res.add(allQuestions.get(idx));
Expand Down Expand Up @@ -170,4 +170,30 @@ public void deleteQuestion(Long id) {
}
}

@Override
public List<Question> testQuestions(int num) {
List<Question> res = new ArrayList<>();
Category c = new Category("Test category", "Test category");
categoryService.addNewCategory(c);
for (int i = 0; i < num; i++) {
Question q = new Question();
q.setStatement("Test question " + i);
q.setLanguage(LocaleContextHolder.getLocale().getLanguage());
Associations.QuestionsCategory.addCategory(q, c);
List<Answer> answers = new ArrayList<>();
for (int j = 0; j < 4; j++) {
Answer a = new Answer();
a.setText("Test answer " + j);
a.setCorrect(j == 0);
if(j==0) q.setCorrectAnswer(a);
answerService.addNewAnswer(a);
answers.add(a);
}
Associations.QuestionAnswers.addAnswer(q, answers);
addNewQuestion(q);
res.add(q);
}
return res;
}

}
7 changes: 0 additions & 7 deletions src/main/java/com/uniovi/services/impl/RoleServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,4 @@ public Role addRole(RoleDto role) {
public Role getRole(String name) {
return roleRepository.findById(name).orElse(null);
}

@Override
public List<Role> getRoles() {
List<Role> roles = new ArrayList<>();
roleRepository.findAll().forEach(roles::add);
return roles;
}
}
8 changes: 4 additions & 4 deletions src/main/java/com/uniovi/validators/SignUpValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,23 @@ public void validate(Object target, Errors errors) {
PlayerDto user = (PlayerDto) target;

if (!EmailValidator.getInstance().isValid(user.getEmail())) {
errors.rejectValue("email", null,
errors.rejectValue("email", "signup.error.email.valid",
"El email no es válido");
}

if(playerService.getUserByEmail(user.getEmail()).isPresent()){
errors.rejectValue("email", null,
errors.rejectValue("email", "signup.error.email.already",
"Ya hay una cuenta registrada con este email");
}

if (playerService.getUserByUsername(user.getUsername()).isPresent()) {
errors.rejectValue("username", null,
errors.rejectValue("username", "signup.error.username.already",
"Ya existe una cuenta con este nombre de usuario");
}

if (user.getPassword() == null
|| !user.getPassword().equals(user.getPasswordConfirm())) {
errors.rejectValue("passwordConfirm", null,
errors.rejectValue("passwordConfirm", "signup.error.password.match",
"Las contraseñas no coinciden");
}
}
Expand Down
5 changes: 4 additions & 1 deletion src/main/resources/messages.properties
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,10 @@ signup.passwordConfirm.label=Repita la contraseña:
signup.passwordConfirm.placeholder=Repita la contraseña
signup.submit=Registrarse
signup.title=Regístrate

signup.error.email.valid=El correo electrónico no es válido
signup.error.email.already=El correo electrónico ya está en uso
signup.error.username.already=El nombre de usuario ya está en uso
signup.error.password.match=Las contraseñas no coinciden
# -------------------Statements for the playerRanking.html and GlobalRanking.html file---------------------
ranking.title=Ranking
ranking.position=Posición
Expand Down
4 changes: 4 additions & 0 deletions src/main/resources/messages_en.properties
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ signup.passwordConfirm.label=Confirm Password:
signup.passwordConfirm.placeholder=Confirm your password
signup.submit=Sign up
signup.title=Sign up
signup.error.email.valid=Please enter a valid email address
signup.error.email.already=The email is already in use
signup.error.username.already=The username is already in use
signup.error.password.match=Passwords do not match

# -------------------Statements for the playerRanking.html and GlobalRanking.html file---------------------
ranking.title=Ranking
Expand Down
4 changes: 4 additions & 0 deletions src/main/resources/messages_es.properties
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ signup.passwordConfirm.label=Repita la contraseña:
signup.passwordConfirm.placeholder=Repita la contraseña
signup.submit=Registrarse
signup.title=Regístrate
signup.error.email.valid=El correo electrónico no es válido
signup.error.email.already=El correo electrónico ya está en uso
signup.error.username.already=El nombre de usuario ya está en uso
signup.error.password.match=Las contraseñas no coinciden

# -------------------Statements for the playerRanking.html and GlobalRanking.html file---------------------
ranking.title=Ranking
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/templates/player/signup.html
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,6 @@ <h2 th:text="#{signup.title}"></h2>
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
</form>
</div>
<footer th:replace="fragments/footer"/>
<footer th:replace="~{fragments/footer}"/>
</body>
</html>
2 changes: 1 addition & 1 deletion src/main/resources/templates/ranking/globalRanking.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<div class="table-responsive">
<h2 th:text="#{ranking.title}">Ranking</h2>
<div class="table-responsive">
<table class="table table-hover" th:fragment="globalRankingTable" id="globalRankingTable" th:replace="ranking/globalRanking_table"/>
<table class="table table-hover" th:fragment="globalRankingTable" id="globalRankingTable" th:replace="~{ranking/globalRanking_table}"/>
<footer th:replace="~{fragments/pagination}"/>
</div>
</div>
Expand Down
3 changes: 3 additions & 0 deletions src/test/java/com/uniovi/Wiq_IntegrationTests.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.uniovi;

import com.uniovi.util.FirefoxWebDriver;
import com.uniovi.util.PropertiesExtractor;
import io.cucumber.spring.CucumberContextConfiguration;
import org.junit.jupiter.api.*;
import org.openqa.selenium.WebDriver;
Expand All @@ -17,6 +18,8 @@
public class Wiq_IntegrationTests {
protected static final String URL = "http://localhost:3000/";

protected PropertiesExtractor p = new PropertiesExtractor("messages");

protected static WebDriver driver;

public Wiq_IntegrationTests() {
Expand Down
50 changes: 50 additions & 0 deletions src/test/java/com/uniovi/steps/APIStep.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.uniovi.steps;

import com.uniovi.Wiq_IntegrationTests;
import com.uniovi.util.SeleniumUtils;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.WebElement;

import java.util.List;

public class APIStep extends Wiq_IntegrationTests {

@And("I go to the API key page")
public void iGoToTheAPIKeyPage() {
List<WebElement> elems = SeleniumUtils.waitLoadElementsBy(driver, "free", "//*[@id=\"btnUser\"]", 5);
elems.get(0).click();
elems = SeleniumUtils.waitLoadElementsBy(driver, "@href", "/home/apikey", 5);
elems.get(0).click();
}

@Then("I should see the API key button")
public void iShouldSeeTheAPIKeyButton() {
List<WebElement> elems = SeleniumUtils.waitLoadElementsBy(driver, "@href", "/home/apikey/create", 5);
Assertions.assertTrue(elems.size() == 1);
}

@When("I press the API key button")
public void iPressTheAPIKeyButton() {
List<WebElement> elems = SeleniumUtils.waitLoadElementsBy(driver, "@href", "/home/apikey/create", 5);
elems.get(0).click();
}

@Then("I should see the API key")
public void iShouldSeeTheAPIKey() {
List<WebElement> elems = SeleniumUtils.waitLoadElementsBy(driver, "free", "//*[@id=\"apiKeyDiv\"]/form/div/div", 5);
Assertions.assertTrue(elems.size() == 1);
}

@And("I reenter the API key page")
public void iReenterTheAPIKeyPage() {
this.iGoToTheAPIKeyPage();
}

@Then("I should see the API key directly")
public void iShouldSeeTheAPIKeyDirectly() {
iShouldSeeTheAPIKey();
}
}
55 changes: 55 additions & 0 deletions src/test/java/com/uniovi/steps/GameStep.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.uniovi.steps;

import com.uniovi.Wiq_IntegrationTests;
import com.uniovi.services.InsertSampleDataService;
import com.uniovi.util.PropertiesExtractor;
import com.uniovi.util.SeleniumUtils;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class GameStep extends Wiq_IntegrationTests {

@Autowired
private InsertSampleDataService dataService;
private Logger log = LoggerFactory.getLogger(GameStep.class);

@When("I press Play")
public void iPressPlay() {
dataService.generateTestQuestions();
List<WebElement> elems = SeleniumUtils.waitLoadElementsBy(driver, "free", "//*[@href=\"/game\"]", 5);
elems.get(0).click();
}

@Then("I should start playing")
public void iShouldStartPlaying() throws InterruptedException {
boolean playing = true;
String xpath = "//*[contains(text(),'" + p.getString("game.finish", PropertiesExtractor.getSPANISH()) + "')]";
int i= 0;
List<WebElement> finalMessage;
while(playing){
//I obtain the buttons for the answers
List<WebElement> elems = SeleniumUtils.waitLoadElementsBy(driver, "text", "Test answer 0", 10);
log.info("Found " + elems.size() + " buttons");
log.info("Iteration " + i + " of the game");
//I click on the first button
elems.get(0).click();

try{
finalMessage= SeleniumUtils.waitLoadElementsByXpath(driver, xpath, 10);
}catch(Exception e){
continue;
}
if(finalMessage.size()>0){
playing = false;
}
i++;
}
}
}
46 changes: 46 additions & 0 deletions src/test/java/com/uniovi/steps/LogInStep.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.uniovi.steps;

import com.uniovi.Wiq_IntegrationTests;
import com.uniovi.util.SeleniumUtils;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import java.util.List;

public class LogInStep extends Wiq_IntegrationTests {
@And("I press the login button")
public void iPressTheLoginButton() {
By button = By.className("btn");
driver.findElement(button).click();
}

@And("I fill in the form with valid data email: {string} password: {string}")
public void iFillInTheFormWithValidDataEmailPassword(String username, String pass) {
WebElement mail = driver.findElement(By.name("username"));
mail.click();
mail.clear();
mail.sendKeys(username);
WebElement password = driver.findElement(By.name("password"));
password.click();
password.clear();
password.sendKeys(pass);
}

@And("I access the personal ranking page")
public void iAccessThePersonalRankingPage() {
List<WebElement> elems = SeleniumUtils.waitLoadElementsBy(driver, "free", "//*[@id=\"navbarDropdown2\"]", 5);
elems.get(0).click();
elems = SeleniumUtils.waitLoadElementsBy(driver, "free", "//*[@href=\"/ranking/playerRanking\"]", 5);
elems.get(0).click();
}

@Then("I should see the personal ranking page")
public void iShouldSeeThePersonalRankingPage() {
List<WebElement> elems = SeleniumUtils.waitLoadElementsBy(driver, "@id", "playerRankingTable", 5);
Assertions.assertFalse(elems.isEmpty());
}
}
Loading

0 comments on commit c9f1eda

Please sign in to comment.