Skip to content

Commit

Permalink
fix(acceptance-test): New acceptance test when reactive-web or api-re…
Browse files Browse the repository at this point in the history
…st component exists (#620)

* fix: homologate api paths in entry point webflux with type router false or true

* fix: acceptance test to basic web entry point

* fix: update GetMapping value to /usecase/path

* fix: set api rest acceptance test when module reactive-web or api-rest exist
  • Loading branch information
santicalleg authored Jan 22, 2025
1 parent a1e3622 commit 27b16b1
Show file tree
Hide file tree
Showing 12 changed files with 149 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ public class AcceptanceTestKarate implements ModuleFactory {

@Override
public void buildModule(ModuleBuilder builder) throws IOException, CleanException {
builder.setupFromTemplate("test/acceptance-test");
String templatePath = "test/acceptance-test";

if (Boolean.TRUE.equals(builder.getBooleanParam("task-param-exist-api-rest"))) {
templatePath += "/api-rest";
}

builder.setupFromTemplate(templatePath);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package co.com.bancolombia.task;

import co.com.bancolombia.task.annotations.CATask;
import java.util.ArrayList;

@CATask(
name = "generateAcceptanceTest",
Expand All @@ -10,6 +11,12 @@ public class GenerateAcceptanceTestTask extends AbstractResolvableTypeTask {

@Override
protected void prepareParams() {
var modules = new ArrayList<>(getProject().getChildProjects().keySet());

builder.addParam(
"task-param-exist-api-rest",
modules.stream()
.anyMatch(value -> value.equals("reactive-web") || value.equals("api-rest")));
builder.addParam("acceptanceTestPath", name);
}

Expand Down
4 changes: 2 additions & 2 deletions src/main/resources/entry-point/rest-mvc/api.java.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ public class ApiRest {
{{#task-param-authorize}}
@PreAuthorize("hasRole('permission')")
{{/task-param-authorize}}
@GetMapping(path = "/path")
@GetMapping(path = "/usecase/path")
public String commandName() {
return "Hello World";
return "";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ class ApiRestTest {
@Test
void apiRestTest() {
var response = apiRest.commandName();
assertEquals("Hello World", response);
assertEquals("", response);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class ApiRest {
{{#task-param-authorize}}
@PreAuthorize("hasRole('permission')")
{{/task-param-authorize}}
@GetMapping(path = "/path")
@GetMapping(path = "/usecase/path")
public Mono<String> commandName() {
// return useCase.doAction();
return Mono.just("");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class ApiRestTest {
@Test
void testCommandName() {
webTestClient.get()
.uri("/api/path")
.uri("/api/usecase/path")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class ConfigTest {
@Test
void corsConfigurationShouldAllowOrigins() {
webTestClient.get()
.uri("/api/path")
.uri("/api/usecase/path")
.exchange()
.expectStatus().isOk()
.expectHeader().valueEquals("Content-Security-Policy",
Expand Down
15 changes: 15 additions & 0 deletions src/main/resources/test/acceptance-test/api-rest/definition.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"folders": [
"deployment/{{acceptanceTestPath}}/src/test/java/{{packagePath}}/utils"
],
"files": {
"test/acceptance-test/resources/logback-test.xml.mustache": "deployment/{{acceptanceTestPath}}/src/test/resources/logback-test.xml",
"test/acceptance-test/api-rest/resources/karate-config.js.mustache": "deployment/{{acceptanceTestPath}}/src/test/resources/karate-config.js",
"test/acceptance-test/api-rest/resources/myapp.feature.mustache": "deployment/{{acceptanceTestPath}}/src/test/resources/{{packagePath}}/myapp.feature",
"test/acceptance-test/api-rest/readme.md.mustache": "deployment/{{acceptanceTestPath}}/README.md",
"test/acceptance-test/TestParallel.java.mustache": "deployment/{{acceptanceTestPath}}/src/test/java/{{packagePath}}/TestParallel.java",
"test/acceptance-test/utils/validator.test.utils.java.mustache": "deployment/{{acceptanceTestPath}}/src/test/java/{{packagePath}}/utils/ValidatorTestUtils.java",
"test/acceptance-test/build.gradle.mustache": "deployment/{{acceptanceTestPath}}/build.gradle",
"test/acceptance-test/settings.gradle.mustache": "deployment/{{acceptanceTestPath}}/settings.gradle"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Proyecto Base de Karate para pruebas de integración en AcceptanceTest - REST, GraphQL, SOAP
_Karate es una herramienta de código abierto que combina la automatización de pruebas de API, simulacros , pruebas de rendimiento e incluso la automatización de la interfaz de usuario en un marco único y unificado . La sintaxis BDD popularizada por Cucumber es un lenguaje neutro y fácil incluso para los no programadores. Las afirmaciones y los informes HTML están integrados y puede ejecutar pruebas en paralelo para aumentar la velocidad._

_Si está familiarizado con Cucumber / Gherkin, la gran diferencia aquí es que no necesita escribir código extra de "pegamento" o "definiciones de pasos" de Java._

**RECOMENDACION !!!**: Visitar la documentación oficial para obtener todas las ventajas de este potencial framework: https://github.com/intuit/karate
## Comenzando

### Instalación 🔧

**IMPORTANTE**: Este proyecto es una demo, proyecto base, para estructurar las pruebas de integración (AcceptanceTest) que se realizarán. Este proyecto es funcional yo consume la pet-store API en su versión 3 (https://petstore3.swagger.io/api/v3), sin embargo, a continuación te contamos que debes modificar y configurar para comenzar en tu contexto de aplicación con las pruebas:
- Ir al karate-config.js y modificar la `urlBase` por la url o endpoint de tu aplicación.
- Ir al karate-config.js y modificar la `oasUrl` por el path y nombre de la deficnicón open Api de la API a testear.
- Ir a los archivos .feature (src>test>resources>{{package}}) agregar tus escenarios, métodos de prueba, aserciones, y todo lo necesario para tus pruebas en particular.

Aquí se detalla la estructura que debe guiar las pruebas con Karate, es un ejemplo:

```
src
└── test
├── java
│ └── {{package}}
│ ├── TestParallel.java
│ └── utils
│ └── ValidatorTestUtils.java
└── resources
├── {{package}}
│ └── myapp.feature
├── karate-config.js
└── logback-test.xml
```

- TestParallel -> Clase general en java que ejecuta los TESTS de karate en Paralelo y tambien genera el reporte de dichos TESTS en formato json que luego se convierte en reporte cucumber

## Ejecutando las pruebas ⚙️
Este proyecto soporta ejecución por features tageados de manera independiente, como es el caso del feature demo.feature el cual tiene el tag @acceptanceTest.

```gradle
gradlew clean test "-Dkarate.options=--tags @acceptanceTest" -i
```

De esta manera se ejecutaran todos los features con el tag @acceptanceTest.

Por otra parte, si lo que se quiere es ejecutar todos los features almacenados en el proyecto bastará con ejecura el comando

```gradle
gradlew clean test -i
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
function fn() {
var env = karate.env || "dev";
var connectTimeout = karate.properties["connectTimeout"] || 45000;
var baseUrl =
karate.properties["baseUrl"] ||
"http://localhost:8080";
var config = {
baseUrl
};

karate.log("karate.env system property was: ", env);

karate.configure('connectTimeout', 2000);
karate.configure('readTimeout', 2000);
karate.configure('ssl', true);
return config;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# We suggest to consulting the Karate Framework documentation: https://github.com/intuit/karate
@acceptanceTest
Feature: Here is the full description of the test suite to be run DEMO

How ...
Required ...
To ...


Background:
# This property is taken from the karate-config.js file
* url baseUrl

# Reference
# https://github.com/karatelabs/karate#request
# https://github.com/karatelabs/karate#reading-files
Scenario: This is the description of this scenario to be tested and its objective
Given path '/api/usecase/path'
When method get
Then status 200
28 changes: 27 additions & 1 deletion src/test/java/co/com/bancolombia/task/GenerateTestTaskTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@ class GenerateTestTaskTest {
private static final String TEST_DIR = getTestDir(GenerateTestTaskTest.class);

private static GenerateAcceptanceTestTask task;
private static Project project;

@BeforeAll
public static void setup() throws IOException, CleanException {
deleteStructure(Path.of(TEST_DIR));
Project project = setupProject(GenerateTestTaskTest.class, GenerateStructureTask.class);
project = setupProject(GenerateTestTaskTest.class, GenerateStructureTask.class);

GenerateStructureTask taskStructure = getTask(project, GenerateStructureTask.class);
taskStructure.setType(GenerateStructureTask.ProjectType.REACTIVE);
Expand Down Expand Up @@ -65,4 +66,29 @@ void generateAcceptanceTest() throws IOException, CleanException {
"build.gradle",
"README.md");
}

@Test
void generateEntryPointAcceptanceTest() throws IOException, CleanException {
// Arrange
ProjectBuilder.builder()
.withName("reactive-web")
.withProjectDir(new File(TEST_DIR + "/infrastructure/entry-points/reactive-web"))
.withParent(project)
.build();

task.setName("acceptance-test");
// Act
task.execute();
// Assert
assertFilesExistsInDir(
TEST_DIR + "/deployment/acceptance-test/",
"src/test/java/co/com/bancolombia/TestParallel.java",
"src/test/java/co/com/bancolombia/utils/ValidatorTestUtils.java",
"src/test/resources/logback-test.xml",
"src/test/resources/karate-config.js",
"src/test/resources/co/com/bancolombia/myapp.feature",
"settings.gradle",
"build.gradle",
"README.md");
}
}

0 comments on commit 27b16b1

Please sign in to comment.