Skip to content

Commit

Permalink
Test unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Pelayori committed Mar 18, 2024
1 parent 6a0384a commit 74e2218
Show file tree
Hide file tree
Showing 6 changed files with 191 additions and 67 deletions.
65 changes: 4 additions & 61 deletions .github/workflows/unit-tests-push.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,38 +10,7 @@ on:
types: [opened, synchronize, reopened]

jobs:
unit-tests:
runs-on: ubuntu-latest
services:
mysql:
image: mysql:latest
env:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: test_database
ports:
- 3306:3306
options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3
steps:
- uses: actions/checkout@v2
- name: Set up JDK 17
uses: actions/setup-java@v1
with:
java-version: '17'
- name: Cache Maven
uses: actions/cache@v2
with:
path: |
~/.m2
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Add exec permission to mvnw
run: chmod +x mvnw
- name: Run unit tests
run: ./mvnw test -Dgroups="unit" -Dspring.profiles.active=test -Dspring.datasource.url=jdbc:mysql://localhost:3306/test_database -Dspring.datasource.username=root -Dspring.datasource.password=root -Dspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

integration-tests:
needs: unit-tests
app-tests-analyze:
runs-on: ubuntu-latest
services:
mysql:
Expand All @@ -59,34 +28,8 @@ jobs:
uses: actions/setup-java@v1
with:
java-version: '17'
- name: Set up Chrome
uses: browser-actions/setup-chrome@latest
- name: Set up ChromeDriver
uses: nanasess/setup-chromedriver@v2
- name: Cache Maven
uses: actions/cache@v2
with:
path: |
~/.m2
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Add exec permission to mvnw
run: chmod +x mvnw
- name: Run integration tests with Selenium
run: ./mvnw test -Dgroups="integration" -Dspring.profiles.active=test -Dspring.datasource.url=jdbc:mysql://localhost:3306/test_database -Dspring.datasource.username=root -Dspring.datasource.password=root -Dspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

sonarcloud-analysis:
needs: unit-tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 17
uses: actions/setup-java@v1
with:
java-version: '17'
- name: SonarCloud analysis
uses: SonarSource/sonarcloud-github-action@master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
- name: Run all tests with sonar analysis
run: |
./mvnw -B clean verify sonar:sonar -Dsonar.projectKey=Arquisoft_wiq_es04b -Dsonar.organization=arquisoft -Dsonar.branch.name=${{ github.ref }} -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_TOKEN }} -Dspring.profiles.active=test -Dspring.datasource.url=jdbc:mysql://localhost:3306/test_database -Dspring.datasource.username=root -Dspring.datasource.password=root -Dspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
17 changes: 16 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,22 @@
<artifactId>commons-validator</artifactId>
<version>1.7</version>
</dependency>

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.1.0</version> <!-- Use latest version -->
</dependency>
<!-- WebDriver Manager -->
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.0.3</version> <!-- Use latest version -->
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.1</version> <!-- Check for the latest version -->
</dependency>
</dependencies>

<build>
Expand Down
10 changes: 9 additions & 1 deletion src/main/java/com/uniovi/services/InsertSampleDataService.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
Expand All @@ -31,22 +32,29 @@ public class InsertSampleDataService {
private final CategoryService categoryService;
private final QuestionRepository questionRepository;
private final GameSessionRepository gameSessionRepository;
private Environment environment;

private Logger log = LoggerFactory.getLogger(InsertSampleDataService.class);;

public InsertSampleDataService(PlayerService playerService, QuestionService questionService,
CategoryService categoryService, QuestionRepository questionRepository,
GameSessionRepository gameSessionRepository) {
GameSessionRepository gameSessionRepository, Environment environment) {
this.playerService = playerService;
this.questionService = questionService;
this.categoryService = categoryService;
this.questionRepository = questionRepository;
this.gameSessionRepository = gameSessionRepository;
this.environment = environment;
}

@Transactional
@EventListener(ApplicationReadyEvent.class) // Uncomment this line to insert sample data on startup
public void insertSampleQuestions() {
if (Arrays.stream(environment.getActiveProfiles()).anyMatch(env -> (env.equalsIgnoreCase("test")))) {
log.info("Test profile active, skipping sample data insertion");
return;
}

if (!playerService.getUserByEmail("[email protected]").isPresent()) {
PlayerDto player = new PlayerDto();
player.setEmail("[email protected]");
Expand Down
42 changes: 38 additions & 4 deletions src/test/java/com/uniovi/Wiq_IntegrationTests.java
Original file line number Diff line number Diff line change
@@ -1,17 +1,51 @@
package com.uniovi;

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.jupiter.api.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;

@SpringBootTest
@Tag("integration")
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@ActiveProfiles("test")
class Wiq_IntegrationTests {
static final String URL = "http://localhost:3000/";

@Test
void contextLoads() {
static WebDriver driver;

@BeforeAll
static public void begin() {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
driver.navigate().to(URL);
}

@BeforeEach
void setup() {
driver.navigate().to(URL);
}

@AfterEach
void tearDown() {
driver.manage().deleteAllCookies();
}

@AfterAll
static public void end() {
//Cerramos el navegador al finalizar las pruebas
driver.quit();
}

@Test
@Order(1)
void testHome() {
// Check the title
Assertions.assertEquals("Wikigame", driver.getTitle());
}
}
5 changes: 5 additions & 0 deletions src/test/java/com/uniovi/Wiq_UnitTests.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
package com.uniovi;

import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;

@SpringBootTest
@Tag("unit")
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@ActiveProfiles("test")
class Wiq_UnitTests {

@Test
Expand Down
119 changes: 119 additions & 0 deletions src/test/java/com/uniovi/util/SeleniumUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package com.uniovi.util;


import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.List;

public class SeleniumUtils {
/**
* Aborta si el "texto" no está presente en la página actual
* @param driver: apuntando al navegador abierto actualmente.
* @param text: texto a buscar
*/
static public void textIsPresentOnPage(WebDriver driver, String text)
{
List<WebElement> list = driver.findElements(By.xpath("//*[contains(text(),'" + text + "')]"));
Assertions.assertTrue(list.size() > 0, "Texto " + text + " no localizado!");
}

/**
* Aborta si el "texto" está presente en la página actual
* @param driver: apuntando al navegador abierto actualmente.
* @param text: texto a buscar
*/
static public void textIsNotPresentOnPage(WebDriver driver, String text)
{
List<WebElement> list = driver.findElements(By.xpath("//*[contains(text(),'" + text + "')]"));
Assertions.assertEquals(0, list.size(), "Texto " + text + " no está presente !");
}

/**
* Aborta si el "texto" está presente en la página actual tras timeout segundos.
* @param driver: apuntando al navegador abierto actualmente.
* @param text: texto a buscar
* @param timeout: el tiempo máximo que se esperará por la aparición del texto a buscar
*/
static public void waitTextIsNotPresentOnPage(WebDriver driver, String text, int timeout)
{
Boolean resultado =
(new WebDriverWait(driver, Duration.ofSeconds(timeout))).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[contains(text(),'" + text + "')]")));

Assertions.assertTrue(resultado);
}


/**
* Espera por la visibilidad de un elemento/s en la vista actualmente cargandose en driver. Para ello se empleará una consulta xpath.
* @param driver: apuntando al navegador abierto actualmente.
* @param xpath: consulta xpath.
* @param timeout: el tiempo máximo que se esperará por la aparición del elemento a buscar con xpath
* @return Se retornará la lista de elementos resultantes de la búsqueda con xpath.
*/
static public List<WebElement> waitLoadElementsByXpath(WebDriver driver, String xpath, int timeout)
{
WebElement result =
(new WebDriverWait(driver, Duration.ofSeconds(timeout))).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
Assertions.assertNotNull(result);
return driver.findElements(By.xpath(xpath));
}

/**
* Espera por la visibilidad de un elemento/s en la vista actualmente cargandose en driver. Para ello se empleará una consulta xpath
* según varios criterios..
*
* @param driver: apuntando al navegador abierto actualmente.
* @param criterio: "id" or "class" or "text" or "@attribute" or "free". Si el valor de criterio es free es una expresion xpath completa.
* @param text: texto correspondiente al criterio.
* @param timeout: el tiempo máximo que se esperará por la apareción del elemento a buscar con criterio/text.
* @return Se retornará la lista de elementos resultantes de la búsqueda.
*/
static public List<WebElement> waitLoadElementsBy(WebDriver driver, String criterio, String text, int timeout)
{
String searchCriterio;
switch (criterio) {
case "id":
searchCriterio = "//*[contains(@id,'" + text + "')]";
break;
case "class":
searchCriterio = "//*[contains(@class,'" + text + "')]";
break;
case "text":
searchCriterio = "//*[contains(text(),'" + text + "')]";
break;
case "free":
searchCriterio = text;
break;
default:
searchCriterio = "//*[contains(" + criterio + ",'" + text + "')]";
break;
}

return waitLoadElementsByXpath(driver, searchCriterio, timeout);
}


/**
* PROHIBIDO USARLO PARA VERSIÓN FINAL.
* Esperar "segundos" durante la ejecucion del navegador
* @param driver: apuntando al navegador abierto actualmente.
* @param seconds: Segundos de bloqueo de la ejecución en el navegador.
*/
static public void waitSeconds(WebDriver driver, int seconds){

//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized(driver){
try {
driver.wait(seconds * 1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

0 comments on commit 74e2218

Please sign in to comment.