From 31a06e46938738749f10180af713174a00831297 Mon Sep 17 00:00:00 2001 From: Feliphe Jesus Date: Tue, 31 Mar 2026 17:08:12 -0300 Subject: [PATCH 1/3] Implementing login tests (#5) --- pom.xml | 2 +- .../client/login/LoginClient.java | 19 ++++ .../login/dto/request/LoginRequest.java | 15 +++ .../login/dto/response/LoginResponse.java | 15 +++ .../service/login/LoginService.java | 21 ++++ src/main/resources/config/config.properties | 11 +-- .../suite/FullTestSuite.java | 14 +++ .../apitestautomation/test/LoginIT.java | 96 +++++++++++++++++++ .../testdata/LoginProvider.java | 29 ++++++ .../resources/schemas/login/empty-email.json | 13 +++ .../schemas/login/empty-password.json | 13 +++ src/test/resources/schemas/login/success.json | 17 ++++ .../resources/schemas/login/unauthorized.json | 13 +++ 13 files changed, 270 insertions(+), 8 deletions(-) create mode 100644 src/main/java/io/github/felseje/apitestautomation/client/login/LoginClient.java create mode 100644 src/main/java/io/github/felseje/apitestautomation/client/login/dto/request/LoginRequest.java create mode 100644 src/main/java/io/github/felseje/apitestautomation/client/login/dto/response/LoginResponse.java create mode 100644 src/main/java/io/github/felseje/apitestautomation/service/login/LoginService.java create mode 100644 src/test/java/io/github/felseje/apitestautomation/suite/FullTestSuite.java create mode 100644 src/test/java/io/github/felseje/apitestautomation/test/LoginIT.java create mode 100644 src/test/java/io/github/felseje/apitestautomation/testdata/LoginProvider.java create mode 100644 src/test/resources/schemas/login/empty-email.json create mode 100644 src/test/resources/schemas/login/empty-password.json create mode 100644 src/test/resources/schemas/login/success.json create mode 100644 src/test/resources/schemas/login/unauthorized.json diff --git a/pom.xml b/pom.xml index a2f04a7..cfe8703 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ io.github.felseje java-api-test-automation-framework - 1.0.4 + 1.1.0 1.0.12 diff --git a/src/main/java/io/github/felseje/apitestautomation/client/login/LoginClient.java b/src/main/java/io/github/felseje/apitestautomation/client/login/LoginClient.java new file mode 100644 index 0000000..8d1138d --- /dev/null +++ b/src/main/java/io/github/felseje/apitestautomation/client/login/LoginClient.java @@ -0,0 +1,19 @@ +package io.github.felseje.apitestautomation.client.login; + +import io.github.felseje.apitestautomation.client.login.dto.request.LoginRequest; +import io.github.felseje.apitestautomation.core.client.AbstractClient; +import io.github.felseje.apitestautomation.core.request.RequestContext; +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class LoginClient extends AbstractClient { + + public Response login(LoginRequest request) { + RequestContext context = RequestContext.builder() + .body(request) + .contentType(ContentType.JSON) + .build(); + return post(context, "/login"); + } + +} diff --git a/src/main/java/io/github/felseje/apitestautomation/client/login/dto/request/LoginRequest.java b/src/main/java/io/github/felseje/apitestautomation/client/login/dto/request/LoginRequest.java new file mode 100644 index 0000000..c81e1ed --- /dev/null +++ b/src/main/java/io/github/felseje/apitestautomation/client/login/dto/request/LoginRequest.java @@ -0,0 +1,15 @@ +package io.github.felseje.apitestautomation.client.login.dto.request; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class LoginRequest { + + private String email; + private String password; + +} diff --git a/src/main/java/io/github/felseje/apitestautomation/client/login/dto/response/LoginResponse.java b/src/main/java/io/github/felseje/apitestautomation/client/login/dto/response/LoginResponse.java new file mode 100644 index 0000000..3752a21 --- /dev/null +++ b/src/main/java/io/github/felseje/apitestautomation/client/login/dto/response/LoginResponse.java @@ -0,0 +1,15 @@ +package io.github.felseje.apitestautomation.client.login.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class LoginResponse { + + private String message; + private String authorization; + +} diff --git a/src/main/java/io/github/felseje/apitestautomation/service/login/LoginService.java b/src/main/java/io/github/felseje/apitestautomation/service/login/LoginService.java new file mode 100644 index 0000000..533773b --- /dev/null +++ b/src/main/java/io/github/felseje/apitestautomation/service/login/LoginService.java @@ -0,0 +1,21 @@ +package io.github.felseje.apitestautomation.service.login; + +import io.github.felseje.apitestautomation.client.login.LoginClient; +import io.github.felseje.apitestautomation.client.login.dto.request.LoginRequest; +import io.github.felseje.apitestautomation.core.response.ApiResponse; +import io.github.felseje.apitestautomation.util.ArgumentValidator; +import io.restassured.response.Response; +import lombok.RequiredArgsConstructor; + +@RequiredArgsConstructor +public class LoginService { + + private final LoginClient loginClient; + + public ApiResponse login(LoginRequest request) { + ArgumentValidator.requireNotNull(request, "The login request cannot be null"); + Response response = loginClient.login(request); + return new ApiResponse(response); + } + +} diff --git a/src/main/resources/config/config.properties b/src/main/resources/config/config.properties index f784a01..c7921f2 100644 --- a/src/main/resources/config/config.properties +++ b/src/main/resources/config/config.properties @@ -1,7 +1,4 @@ -# Api url -base.url=https://api-link-here.com - -# Timeouts -http.connect.timeout=5000 -http.socket.timeout=10000 -http.connection-manager.timeout=10000 \ No newline at end of file +base.url=https://serverest.dev +http.connect.timeout=10000 +http.socket.timeout=15000 +http.connection-manager.timeout=15000 \ No newline at end of file diff --git a/src/test/java/io/github/felseje/apitestautomation/suite/FullTestSuite.java b/src/test/java/io/github/felseje/apitestautomation/suite/FullTestSuite.java new file mode 100644 index 0000000..9bf0aa3 --- /dev/null +++ b/src/test/java/io/github/felseje/apitestautomation/suite/FullTestSuite.java @@ -0,0 +1,14 @@ +package io.github.felseje.apitestautomation.suite; + +import io.github.felseje.apitestautomation.test.LoginIT; +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.Suite; +import org.junit.platform.suite.api.SuiteDisplayName; + +@Suite +@SuiteDisplayName("Full Test Suite") +@SelectClasses({ + LoginIT.class +}) +public class FullTestSuite { +} diff --git a/src/test/java/io/github/felseje/apitestautomation/test/LoginIT.java b/src/test/java/io/github/felseje/apitestautomation/test/LoginIT.java new file mode 100644 index 0000000..3e0400a --- /dev/null +++ b/src/test/java/io/github/felseje/apitestautomation/test/LoginIT.java @@ -0,0 +1,96 @@ +package io.github.felseje.apitestautomation.test; + +import io.github.felseje.apitestautomation.client.login.LoginClient; +import io.github.felseje.apitestautomation.client.login.dto.request.LoginRequest; +import io.github.felseje.apitestautomation.core.response.ApiResponse; +import io.github.felseje.apitestautomation.service.login.LoginService; +import io.github.felseje.apitestautomation.testdata.LoginProvider; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +@Tag("login") +@DisplayName("Login Tests") +public class LoginIT { + + private final LoginService loginService = new LoginService(new LoginClient()); + + @Nested + @DisplayName("Successful login scenarios") + public class SuccessfulLogin { + + private static final String LOGIN_SUCCESS_SCHEMA = "schemas/login/success.json"; + + @Test + @DisplayName("Should authenticate successfully when valid credentials are provided") + void shouldAuthenticateSuccessfully() { + // Arrange + LoginRequest request = LoginProvider.getValidLoginRequest(); + + // Act + ApiResponse response = loginService.login(request); + + // Assert + response.shouldBeOk() + .shouldMatchJsonSchemaInClasspath(LOGIN_SUCCESS_SCHEMA); + } + + } + + @Nested + @DisplayName("Failed login scenarios") + public class FailedLogin { + + private static final String LOGIN_UNAUTHORIZED_SCHEMA = "schemas/login/unauthorized.json"; + private static final String LOGIN_EMPTY_EMAIL_SCHEMA = "schemas/login/empty-email.json"; + private static final String LOGIN_EMPTY_PASSWORD_SCHEMA = "schemas/login/empty-password.json"; + + static Stream provideEmptyLoginFieldsForBadRequest() { + return Stream.of( + Arguments.of( + "Should return Bad Request when email is empty", + LOGIN_EMPTY_EMAIL_SCHEMA, + LoginProvider.getLoginRequestWithEmptyEmail() + ), + Arguments.of( + "Should return Bad Request when password is empty", + LOGIN_EMPTY_PASSWORD_SCHEMA, + LoginProvider.getLoginRequestWithEmptyPassword() + ) + ); + } + + @Test + @DisplayName("Should return unauthorized when invalid credentials are provided") + void shouldReturnUnauthorizedWhenCredentialsAreInvalid() { + // Arrange + LoginRequest request = LoginProvider.getLoginRequestWithUnauthorizedCredentials(); + + // Act + ApiResponse response = loginService.login(request); + + // Assert + response.shouldBeUnauthorized() + .shouldMatchJsonSchemaInClasspath(LOGIN_UNAUTHORIZED_SCHEMA); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("provideEmptyLoginFieldsForBadRequest") + void shouldReturnBadRequestForEmptyFields(String testName, String expectedSchema, LoginRequest request) { + // Act + ApiResponse response = loginService.login(request); + + // Assert + response.shouldBeBadRequest() + .shouldMatchJsonSchemaInClasspath(expectedSchema); + } + + } + +} diff --git a/src/test/java/io/github/felseje/apitestautomation/testdata/LoginProvider.java b/src/test/java/io/github/felseje/apitestautomation/testdata/LoginProvider.java new file mode 100644 index 0000000..a647f43 --- /dev/null +++ b/src/test/java/io/github/felseje/apitestautomation/testdata/LoginProvider.java @@ -0,0 +1,29 @@ +package io.github.felseje.apitestautomation.testdata; + +import io.github.felseje.apitestautomation.client.login.dto.request.LoginRequest; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class LoginProvider { + + private static final String VALID_EMAIL = "fulano@qa.com"; + private static final String VALID_PASSWORD = "teste"; + + public static LoginRequest getValidLoginRequest() { + return new LoginRequest(VALID_EMAIL, VALID_PASSWORD); + } + + public static LoginRequest getLoginRequestWithUnauthorizedCredentials() { + return new LoginRequest("unauth@mail.com", "p4ssw0rd"); + } + + public static LoginRequest getLoginRequestWithEmptyEmail() { + return new LoginRequest("", "p4ssw0rd"); + } + + public static LoginRequest getLoginRequestWithEmptyPassword() { + return new LoginRequest("rTyxUuv@qa.com", ""); + } + +} diff --git a/src/test/resources/schemas/login/empty-email.json b/src/test/resources/schemas/login/empty-email.json new file mode 100644 index 0000000..b5569eb --- /dev/null +++ b/src/test/resources/schemas/login/empty-email.json @@ -0,0 +1,13 @@ +{ + "type": "object", + "required": [ + "email" + ], + "additionalProperties": false, + "properties": { + "email": { + "type": "string", + "const": "email não pode ficar em branco" + } + } +} \ No newline at end of file diff --git a/src/test/resources/schemas/login/empty-password.json b/src/test/resources/schemas/login/empty-password.json new file mode 100644 index 0000000..a25f85e --- /dev/null +++ b/src/test/resources/schemas/login/empty-password.json @@ -0,0 +1,13 @@ +{ + "type": "object", + "required": [ + "password" + ], + "additionalProperties": false, + "properties": { + "password": { + "type": "string", + "const": "password não pode ficar em branco" + } + } +} \ No newline at end of file diff --git a/src/test/resources/schemas/login/success.json b/src/test/resources/schemas/login/success.json new file mode 100644 index 0000000..89c4fc5 --- /dev/null +++ b/src/test/resources/schemas/login/success.json @@ -0,0 +1,17 @@ +{ + "type": "object", + "required": [ + "message", + "authorization" + ], + "properties": { + "message": { + "type": "string", + "const": "Login realizado com sucesso" + }, + "authorization": { + "type": "string", + "pattern": "^Bearer .*" + } + } +} \ No newline at end of file diff --git a/src/test/resources/schemas/login/unauthorized.json b/src/test/resources/schemas/login/unauthorized.json new file mode 100644 index 0000000..02278b3 --- /dev/null +++ b/src/test/resources/schemas/login/unauthorized.json @@ -0,0 +1,13 @@ +{ + "type": "object", + "required": [ + "message" + ], + "additionalProperties": false, + "properties": { + "message": { + "type": "string", + "const": "Email e/ou senha inválidos" + } + } +} \ No newline at end of file From 711e74a7482ac77c6a74d80a0863638653c090b0 Mon Sep 17 00:00:00 2001 From: Felseje Date: Sat, 3 Oct 2026 12:51:54 -0300 Subject: [PATCH 2/3] Implementing tests for the user endpoint --- pom.xml | 336 ++++++++------ .../client/login/LoginClient.java | 14 +- .../login/dto/request/LoginRequest.java | 4 +- .../login/dto/response/LoginResponse.java | 4 +- .../client/user/UserClient.java | 52 +++ .../client/user/dto/UserDto.java | 22 + .../user/dto/request/CreateUserRequest.java | 16 + .../user/dto/request/UpdateUserRequest.java | 16 + .../user/dto/response/UserListResponse.java | 19 + .../user/dto/response/UserResponse.java | 31 ++ .../apitestautomation/config/Config.java | 23 +- .../config/ConfigurationManager.java | 18 +- .../core/client/AbstractClient.java | 126 +++--- .../core/request/ApiRequest.java | 23 +- .../core/request/RequestContext.java | 153 ++++--- .../core/request/RetryRequest.java | 147 +++--- .../core/request/RetryStrategy.java | 6 +- .../core/response/ApiResponse.java | 422 +++++++++++------- .../exception/ConfigurationException.java | 17 +- .../factory/RequestSpecificationFactory.java | 48 +- .../factory/ResponseSpecificationFactory.java | 10 +- .../service/login/LoginService.java | 12 +- .../service/user/UserService.java | 44 ++ .../util/ArgumentValidator.java | 33 +- .../apitestautomation/util/DataFaker.java | 40 ++ .../apitestautomation/util/Strings.java | 13 +- .../suite/FullTestSuite.java | 7 +- .../apitestautomation/test/LoginIT.java | 130 +++--- .../apitestautomation/test/UserIT.java | 373 ++++++++++++++++ .../testdata/LoginProvider.java | 28 +- .../testdata/UserProvider.java | 50 +++ .../resources/schemas/login/empty-email.json | 2 +- .../schemas/login/empty-password.json | 2 +- src/test/resources/schemas/login/success.json | 2 +- .../resources/schemas/login/unauthorized.json | 2 +- .../schemas/user/create-user-empty-body.json | 6 + 36 files changed, 1532 insertions(+), 719 deletions(-) create mode 100644 src/main/java/io/github/felseje/apitestautomation/client/user/UserClient.java create mode 100644 src/main/java/io/github/felseje/apitestautomation/client/user/dto/UserDto.java create mode 100644 src/main/java/io/github/felseje/apitestautomation/client/user/dto/request/CreateUserRequest.java create mode 100644 src/main/java/io/github/felseje/apitestautomation/client/user/dto/request/UpdateUserRequest.java create mode 100644 src/main/java/io/github/felseje/apitestautomation/client/user/dto/response/UserListResponse.java create mode 100644 src/main/java/io/github/felseje/apitestautomation/client/user/dto/response/UserResponse.java create mode 100644 src/main/java/io/github/felseje/apitestautomation/service/user/UserService.java create mode 100644 src/main/java/io/github/felseje/apitestautomation/util/DataFaker.java create mode 100644 src/test/java/io/github/felseje/apitestautomation/test/UserIT.java create mode 100644 src/test/java/io/github/felseje/apitestautomation/testdata/UserProvider.java create mode 100644 src/test/resources/schemas/user/create-user-empty-body.json diff --git a/pom.xml b/pom.xml index cfe8703..9c496f2 100644 --- a/pom.xml +++ b/pom.xml @@ -1,150 +1,190 @@ - - 4.0.0 - - io.github.felseje - java-api-test-automation-framework - 1.1.0 - - - 1.0.12 - 1.18.44 - 2.0.17 - 1.5.32 - 6.0.3 - 6.0.3 - 6.0.0 - 4.3.0 - 21 - 21 - 3.5.5 - 3.5.5 - UTF-8 - - - - - org.projectlombok - lombok - ${lombok.version} - provided - - - - org.aeonbits.owner - owner - ${owner.version} - compile - - - - org.slf4j - slf4j-api - ${slf4j.version} - compile - - - - ch.qos.logback - logback-classic - ${logback.version} - compile - - - - io.rest-assured - rest-assured - ${restassured.version} - compile - - - - io.rest-assured - json-schema-validator - ${restassured.version} - compile - - - - org.awaitility - awaitility - ${awaitility.version} - compile - - - - org.junit.jupiter - junit-jupiter - ${junit.version} - test - - - - org.junit.platform - junit-platform-suite - ${junit.platform.version} - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven.surefire.version} - - - **/*Test.java - - brief - true - - - - - org.apache.maven.plugins - maven-failsafe-plugin - ${maven.failsafe.version} - - - - integration-test - verify - - - - - - **/*IT.java - - plain - true - - - - - org.apache.maven.plugins - maven-surefire-report-plugin - ${maven.surefire.version} - - - failsafe-html-report - verify - - report-only - - - - target/failsafe-reports - - target/site/failsafe-report - - - - - - + + 4.0.0 + + + io.github.felseje + java-api-test-automation-framework + 1.1.0 + + Java API Test Automation Framework + Framework para automação de testes de API usando RestAssured e JUnit 5. + + + + + felseje + Feliphe Jesus + felseje@hotmail.com + + Quality Assurance Engineer + Maintainer + + -3 + + + + + + UTF-8 + 21 + 21 + + + 4.3.0 + 2.7.0 + 2.14.0 + 6.0.3 + 6.0.3 + 1.6.4 + 1.18.48 + 1.3.0 + 1.0.12 + 6.0.1 + 2.0.20 + + + 3.5.5 + 3.5.5 + + + + + + com.google.code.gson + gson + ${gson.version} + + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + net.datafaker + datafaker + ${datafaker.version} + + + + org.aeonbits.owner + owner + ${owner.version} + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + ch.qos.logback + logback-classic + ${logback.version} + + + + io.rest-assured + rest-assured + ${restassured.version} + + + + io.rest-assured + json-schema-validator + ${restassured.version} + + + + org.awaitility + awaitility + ${awaitility.version} + + + + org.opentest4j + opentest4j + ${opentest4j.version} + + + + org.junit.jupiter + junit-jupiter + ${junit.version} + test + + + + org.junit.platform + junit-platform-suite + ${junit.platform.version} + test + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven.surefire.version} + + + **/*Test.java + + brief + true + + + + + org.apache.maven.plugins + maven-failsafe-plugin + ${maven.failsafe.version} + + + **/*IT.java + + plain + true + + + + + integration-test + verify + + + + + + + org.apache.maven.plugins + maven-surefire-report-plugin + ${maven.surefire.version} + + + failsafe-html-report + verify + + report-only + + + target/site/failsafe-report + + target/failsafe-reports + + + + + + + \ No newline at end of file diff --git a/src/main/java/io/github/felseje/apitestautomation/client/login/LoginClient.java b/src/main/java/io/github/felseje/apitestautomation/client/login/LoginClient.java index 8d1138d..805ea51 100644 --- a/src/main/java/io/github/felseje/apitestautomation/client/login/LoginClient.java +++ b/src/main/java/io/github/felseje/apitestautomation/client/login/LoginClient.java @@ -8,12 +8,12 @@ public class LoginClient extends AbstractClient { - public Response login(LoginRequest request) { - RequestContext context = RequestContext.builder() - .body(request) - .contentType(ContentType.JSON) - .build(); - return post(context, "/login"); - } + public Response login(LoginRequest request) { + RequestContext context = RequestContext.builder() + .body(request) + .contentType(ContentType.JSON) + .build(); + return post(context, "/login"); + } } diff --git a/src/main/java/io/github/felseje/apitestautomation/client/login/dto/request/LoginRequest.java b/src/main/java/io/github/felseje/apitestautomation/client/login/dto/request/LoginRequest.java index c81e1ed..5476624 100644 --- a/src/main/java/io/github/felseje/apitestautomation/client/login/dto/request/LoginRequest.java +++ b/src/main/java/io/github/felseje/apitestautomation/client/login/dto/request/LoginRequest.java @@ -9,7 +9,7 @@ @AllArgsConstructor public class LoginRequest { - private String email; - private String password; + private String email; + private String password; } diff --git a/src/main/java/io/github/felseje/apitestautomation/client/login/dto/response/LoginResponse.java b/src/main/java/io/github/felseje/apitestautomation/client/login/dto/response/LoginResponse.java index 3752a21..98b8764 100644 --- a/src/main/java/io/github/felseje/apitestautomation/client/login/dto/response/LoginResponse.java +++ b/src/main/java/io/github/felseje/apitestautomation/client/login/dto/response/LoginResponse.java @@ -9,7 +9,7 @@ @AllArgsConstructor public class LoginResponse { - private String message; - private String authorization; + private String message; + private String authorization; } diff --git a/src/main/java/io/github/felseje/apitestautomation/client/user/UserClient.java b/src/main/java/io/github/felseje/apitestautomation/client/user/UserClient.java new file mode 100644 index 0000000..0e66067 --- /dev/null +++ b/src/main/java/io/github/felseje/apitestautomation/client/user/UserClient.java @@ -0,0 +1,52 @@ +package io.github.felseje.apitestautomation.client.user; + +import io.github.felseje.apitestautomation.client.user.dto.request.CreateUserRequest; +import io.github.felseje.apitestautomation.client.user.dto.request.UpdateUserRequest; +import io.github.felseje.apitestautomation.core.client.AbstractClient; +import io.github.felseje.apitestautomation.core.request.RequestContext; +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import java.util.Map; + +public class UserClient extends AbstractClient { + + private static final String USERS_ENDPOINT = "/usuarios"; + private static final String USERS_ID_ENDPOINT = USERS_ENDPOINT + "/{userId}"; + + public Response createUser(CreateUserRequest request) { + RequestContext requestContext = RequestContext.builder() + .contentType(ContentType.JSON) + .body(request) + .build(); + return post(requestContext, USERS_ENDPOINT); + } + + public Response getUser(String id) { + RequestContext requestContext = getUserIdContext(id); + return get(requestContext, USERS_ID_ENDPOINT); + } + + public Response getUsers(Map queryParams) { + var requestContextBuilder = RequestContext.builder(); + queryParams.forEach(requestContextBuilder::queryParam); + return get(requestContextBuilder.build(), USERS_ENDPOINT); + } + + public Response updateUser(String id, UpdateUserRequest request) { + RequestContext requestContext = RequestContext.builder() + .contentType(ContentType.JSON) + .body(request) + .pathParam("userId", id) + .build(); + return put(requestContext, USERS_ID_ENDPOINT); + } + + public Response deleteUser(String id) { + RequestContext requestContext = getUserIdContext(id); + return delete(requestContext, USERS_ID_ENDPOINT); + } + + private RequestContext getUserIdContext(final String userId) { + return RequestContext.builder().pathParam("userId", userId).build(); + } +} diff --git a/src/main/java/io/github/felseje/apitestautomation/client/user/dto/UserDto.java b/src/main/java/io/github/felseje/apitestautomation/client/user/dto/UserDto.java new file mode 100644 index 0000000..70238e9 --- /dev/null +++ b/src/main/java/io/github/felseje/apitestautomation/client/user/dto/UserDto.java @@ -0,0 +1,22 @@ +package io.github.felseje.apitestautomation.client.user.dto; + +import com.google.gson.annotations.SerializedName; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public abstract class UserDto { + + @SerializedName("nome") + private String name; + + private String email; + + private String password; + + @SerializedName("administrador") + private String administrator; +} diff --git a/src/main/java/io/github/felseje/apitestautomation/client/user/dto/request/CreateUserRequest.java b/src/main/java/io/github/felseje/apitestautomation/client/user/dto/request/CreateUserRequest.java new file mode 100644 index 0000000..99c8172 --- /dev/null +++ b/src/main/java/io/github/felseje/apitestautomation/client/user/dto/request/CreateUserRequest.java @@ -0,0 +1,16 @@ +package io.github.felseje.apitestautomation.client.user.dto.request; + +import io.github.felseje.apitestautomation.client.user.dto.UserDto; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@EqualsAndHashCode(callSuper = true) +public class CreateUserRequest extends UserDto { + + public CreateUserRequest(String name, String email, String password, String isAdmin) { + super(name, email, password, isAdmin); + } +} diff --git a/src/main/java/io/github/felseje/apitestautomation/client/user/dto/request/UpdateUserRequest.java b/src/main/java/io/github/felseje/apitestautomation/client/user/dto/request/UpdateUserRequest.java new file mode 100644 index 0000000..62a9d92 --- /dev/null +++ b/src/main/java/io/github/felseje/apitestautomation/client/user/dto/request/UpdateUserRequest.java @@ -0,0 +1,16 @@ +package io.github.felseje.apitestautomation.client.user.dto.request; + +import io.github.felseje.apitestautomation.client.user.dto.UserDto; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@EqualsAndHashCode(callSuper = true) +public class UpdateUserRequest extends UserDto { + + public UpdateUserRequest(String name, String email, String password, String isAdmin) { + super(name, email, password, isAdmin); + } +} diff --git a/src/main/java/io/github/felseje/apitestautomation/client/user/dto/response/UserListResponse.java b/src/main/java/io/github/felseje/apitestautomation/client/user/dto/response/UserListResponse.java new file mode 100644 index 0000000..58cee86 --- /dev/null +++ b/src/main/java/io/github/felseje/apitestautomation/client/user/dto/response/UserListResponse.java @@ -0,0 +1,19 @@ +package io.github.felseje.apitestautomation.client.user.dto.response; + +import com.google.gson.annotations.SerializedName; +import java.util.List; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class UserListResponse { + + @SerializedName("quantidade") + private Integer amount; + + @SerializedName("usuarios") + private List users; +} diff --git a/src/main/java/io/github/felseje/apitestautomation/client/user/dto/response/UserResponse.java b/src/main/java/io/github/felseje/apitestautomation/client/user/dto/response/UserResponse.java new file mode 100644 index 0000000..5cad328 --- /dev/null +++ b/src/main/java/io/github/felseje/apitestautomation/client/user/dto/response/UserResponse.java @@ -0,0 +1,31 @@ +package io.github.felseje.apitestautomation.client.user.dto.response; + +import com.google.gson.annotations.SerializedName; +import io.github.felseje.apitestautomation.client.user.dto.UserDto; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@EqualsAndHashCode(callSuper = true) +public class UserResponse extends UserDto { + + @SerializedName("_id") + private String id; + + private String message; + + public UserResponse(String id, String name, String email, String password, String admin) { + super(name, email, password, admin); + this.id = id; + } + + public UserResponse(String name, String email, String password, String admin) { + super(name, email, password, admin); + } + + public UserResponse(String name, String email, String password, Boolean isAdmin) { + super(name, email, password, isAdmin.toString()); + } +} diff --git a/src/main/java/io/github/felseje/apitestautomation/config/Config.java b/src/main/java/io/github/felseje/apitestautomation/config/Config.java index 1aaf269..a41e0ea 100644 --- a/src/main/java/io/github/felseje/apitestautomation/config/Config.java +++ b/src/main/java/io/github/felseje/apitestautomation/config/Config.java @@ -5,19 +5,18 @@ @Sources({"classpath:config/${env}.properties"}) public interface Config extends org.aeonbits.owner.Config { - @Key("base.url") - String baseUrl(); + @Key("base.url") + String baseUrl(); - @Key("http.connect.timeout") - @DefaultValue("5000") - int httpConnectTimeout(); + @Key("http.connect.timeout") + @DefaultValue("5000") + int httpConnectTimeout(); - @Key("http.socket.timeout") - @DefaultValue("10000") - int httpSocketTimeout(); - - @Key("http.connection-manager.timeout") - @DefaultValue("10000") - int httpConnectionManagerTimeout(); + @Key("http.socket.timeout") + @DefaultValue("10000") + int httpSocketTimeout(); + @Key("http.connection-manager.timeout") + @DefaultValue("10000") + int httpConnectionManagerTimeout(); } diff --git a/src/main/java/io/github/felseje/apitestautomation/config/ConfigurationManager.java b/src/main/java/io/github/felseje/apitestautomation/config/ConfigurationManager.java index 7a478d6..d3e3a79 100644 --- a/src/main/java/io/github/felseje/apitestautomation/config/ConfigurationManager.java +++ b/src/main/java/io/github/felseje/apitestautomation/config/ConfigurationManager.java @@ -10,15 +10,15 @@ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class ConfigurationManager { - public static Config getConfig() { - try { - String env = System.getProperty("env", "config"); - log.info("Loading properties from environment: {}", "config".equals(env) ? "standard" : env); - System.setProperty("env", env); - return ConfigCache.getOrCreate(Config.class); - } catch (Exception e) { - throw new ConfigurationException("Failed to load configuration", e); - } + public static Config getConfig() { + try { + String env = System.getProperty("env", "config"); + log.info("Loading properties from environment: {}", "config".equals(env) ? "standard" : env); + System.setProperty("env", env); + return ConfigCache.getOrCreate(Config.class); + } catch (Exception e) { + throw new ConfigurationException("Failed to load configuration", e); } + } } diff --git a/src/main/java/io/github/felseje/apitestautomation/core/client/AbstractClient.java b/src/main/java/io/github/felseje/apitestautomation/core/client/AbstractClient.java index dadd518..8dabdc6 100644 --- a/src/main/java/io/github/felseje/apitestautomation/core/client/AbstractClient.java +++ b/src/main/java/io/github/felseje/apitestautomation/core/client/AbstractClient.java @@ -13,81 +13,81 @@ public abstract class AbstractClient { - protected Response get(RequestContext context, String endpoint) { - return execute(context, Method.GET, endpoint); - } + protected Response get(RequestContext context, String endpoint) { + return execute(context, Method.GET, endpoint); + } - protected Response post(RequestContext context, String endpoint) { - return execute(context, Method.POST, endpoint); - } + protected Response post(RequestContext context, String endpoint) { + return execute(context, Method.POST, endpoint); + } - protected Response put(RequestContext context, String endpoint) { - return execute(context, Method.PUT, endpoint); - } + protected Response put(RequestContext context, String endpoint) { + return execute(context, Method.PUT, endpoint); + } - protected Response patch(RequestContext context, String endpoint) { - return execute(context, Method.PATCH, endpoint); - } + protected Response patch(RequestContext context, String endpoint) { + return execute(context, Method.PATCH, endpoint); + } + + protected Response delete(RequestContext context, String endpoint) { + return execute(context, Method.DELETE, endpoint); + } - protected Response delete(RequestContext context, String endpoint) { - return execute(context, Method.DELETE, endpoint); + protected Response head(RequestContext context, String endpoint) { + return execute(context, Method.HEAD, endpoint); + } + + protected Response options(RequestContext context, String endpoint) { + return execute(context, Method.OPTIONS, endpoint); + } + + protected Response trace(RequestContext context, String endpoint) { + return execute(context, Method.TRACE, endpoint); + } + + private Response execute(RequestContext context, Method method, String endpoint) { + RequestSpecification requestSpecification = RequestSpecificationFactory.getStandard(); + ResponseSpecification responseSpecification = ResponseSpecificationFactory.getStandard(); + + if (!Strings.isBlank(context.getBaseUrl())) { + requestSpecification.baseUri(context.getBaseUrl()); } - protected Response head(RequestContext context, String endpoint) { - return execute(context, Method.HEAD, endpoint); + if (!context.getHeaders().isEmpty()) { + requestSpecification.headers(context.getHeaders()); } - protected Response options(RequestContext context, String endpoint) { - return execute(context, Method.OPTIONS, endpoint); + if (!context.getPathParams().isEmpty()) { + requestSpecification.pathParams(context.getPathParams()); } - protected Response trace(RequestContext context, String endpoint) { - return execute(context, Method.TRACE, endpoint); + if (!context.getQueryParams().isEmpty()) { + requestSpecification.queryParams(context.getQueryParams()); } - private Response execute(RequestContext context, Method method, String endpoint) { - RequestSpecification requestSpecification = RequestSpecificationFactory.getStandard(); - ResponseSpecification responseSpecification = ResponseSpecificationFactory.getStandard(); - - if (!Strings.isBlank(context.getBaseUrl())) { - requestSpecification.baseUri(context.getBaseUrl()); - } - - if (!context.getHeaders().isEmpty()) { - requestSpecification.headers(context.getHeaders()); - } - - if (!context.getPathParams().isEmpty()) { - requestSpecification.pathParams(context.getPathParams()); - } - - if (!context.getQueryParams().isEmpty()) { - requestSpecification.queryParams(context.getQueryParams()); - } - - if (!context.getMultipartParts().isEmpty()) { - context.getMultipartParts().forEach(requestSpecification::multiPart); - } else if (!context.getFormParams().isEmpty()) { - context.getFormParams().forEach(requestSpecification::formParam); - if (context.getContentType() != null) { - requestSpecification.contentType(context.getContentType()); - } else { - requestSpecification.contentType(ContentType.URLENC); - } - } else if (context.getBody() != null) { - requestSpecification.body(context.getBody()); - if (context.getContentType() != null) { - requestSpecification.contentType(context.getContentType()); - } else { - requestSpecification.contentType(ContentType.JSON); - } - } else { - requestSpecification.noContentType(); - } - - return RestAssured.given(requestSpecification, responseSpecification) - .request(method, endpoint) - .thenReturn(); + if (!context.getMultipartParts().isEmpty()) { + context.getMultipartParts().forEach(requestSpecification::multiPart); + } else if (!context.getFormParams().isEmpty()) { + context.getFormParams().forEach(requestSpecification::formParam); + if (context.getContentType() != null) { + requestSpecification.contentType(context.getContentType()); + } else { + requestSpecification.contentType(ContentType.URLENC); + } + } else if (context.getBody() != null) { + requestSpecification.body(context.getBody()); + if (context.getContentType() != null) { + requestSpecification.contentType(context.getContentType()); + } else { + requestSpecification.contentType(ContentType.JSON); + } + } else { + requestSpecification.noContentType(); } + return RestAssured.given(requestSpecification, responseSpecification) + .request(method, endpoint) + .thenReturn(); + } + } diff --git a/src/main/java/io/github/felseje/apitestautomation/core/request/ApiRequest.java b/src/main/java/io/github/felseje/apitestautomation/core/request/ApiRequest.java index 566b7c1..55b366e 100644 --- a/src/main/java/io/github/felseje/apitestautomation/core/request/ApiRequest.java +++ b/src/main/java/io/github/felseje/apitestautomation/core/request/ApiRequest.java @@ -2,24 +2,23 @@ import io.github.felseje.apitestautomation.core.response.ApiResponse; import io.github.felseje.apitestautomation.util.ArgumentValidator; - import java.util.function.Supplier; public class ApiRequest { - private final Supplier action; + private final Supplier action; - public ApiRequest(Supplier action) { - ArgumentValidator.requireNotNull(action, "The 'action' cannot be null"); - this.action = action; - } + public ApiRequest(Supplier action) { + ArgumentValidator.requireNotNull(action, "The 'action' cannot be null"); + this.action = action; + } - public ApiResponse execute() { - return action.get(); - } + public ApiResponse execute() { + return action.get(); + } - public RetryRequest retry() { - return new RetryRequest(action); - } + public RetryRequest retry() { + return new RetryRequest(action); + } } diff --git a/src/main/java/io/github/felseje/apitestautomation/core/request/RequestContext.java b/src/main/java/io/github/felseje/apitestautomation/core/request/RequestContext.java index a58b15b..767203b 100644 --- a/src/main/java/io/github/felseje/apitestautomation/core/request/RequestContext.java +++ b/src/main/java/io/github/felseje/apitestautomation/core/request/RequestContext.java @@ -1,97 +1,96 @@ package io.github.felseje.apitestautomation.core.request; import io.restassured.http.ContentType; +import java.util.HashMap; +import java.util.Map; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; -import java.util.HashMap; -import java.util.Map; - @Getter @ToString @EqualsAndHashCode public class RequestContext { - private final String baseUrl; - private final Map headers; - private final Map queryParams; - private final Map pathParams; - private final Map multipartParts; - private final Map formParams; - private final Object body; - private final ContentType contentType; - - private RequestContext(RequestContextBuilder builder) { - this.baseUrl = builder.baseUrl; - this.contentType = builder.contentType; - this.headers = Map.copyOf(builder.headers); - this.pathParams = Map.copyOf(builder.pathParams); - this.queryParams = Map.copyOf(builder.queryParams); - this.multipartParts = Map.copyOf(builder.multipartParts); - this.formParams = Map.copyOf(builder.formParams); - this.body = builder.body; + private final String baseUrl; + private final Map headers; + private final Map queryParams; + private final Map pathParams; + private final Map multipartParts; + private final Map formParams; + private final Object body; + private final ContentType contentType; + + private RequestContext(RequestContextBuilder builder) { + this.baseUrl = builder.baseUrl; + this.contentType = builder.contentType; + this.headers = Map.copyOf(builder.headers); + this.pathParams = Map.copyOf(builder.pathParams); + this.queryParams = Map.copyOf(builder.queryParams); + this.multipartParts = Map.copyOf(builder.multipartParts); + this.formParams = Map.copyOf(builder.formParams); + this.body = builder.body; + } + + public static RequestContextBuilder builder() { + return new RequestContextBuilder(); + } + + public static class RequestContextBuilder { + + private final Map headers = new HashMap<>(); + private final Map queryParams = new HashMap<>(); + private final Map pathParams = new HashMap<>(); + private final Map multipartParts = new HashMap<>(); + private final Map formParams = new HashMap<>(); + private String baseUrl; + private ContentType contentType; + private Object body; + + public RequestContextBuilder baseUrl(String baseUrl) { + this.baseUrl = baseUrl; + return this; } - public static RequestContextBuilder builder() { - return new RequestContextBuilder(); + public RequestContextBuilder header(String key, Object value) { + headers.put(key, value); + return this; } - public static class RequestContextBuilder { - - private final Map headers = new HashMap<>(); - private final Map queryParams = new HashMap<>(); - private final Map pathParams = new HashMap<>(); - private final Map multipartParts = new HashMap<>(); - private final Map formParams = new HashMap<>(); - private String baseUrl; - private ContentType contentType; - private Object body; - - public RequestContextBuilder baseUrl(String baseUrl) { - this.baseUrl = baseUrl; - return this; - } - - public RequestContextBuilder header(String key, Object value) { - headers.put(key, value); - return this; - } - - public RequestContextBuilder queryParam(String key, Object value) { - queryParams.put(key, value); - return this; - } - - public RequestContextBuilder pathParam(String key, Object value) { - pathParams.put(key, value); - return this; - } - - public RequestContextBuilder multipartPart(String key, Object value) { - multipartParts.put(key, value); - return this; - } - - public RequestContextBuilder formParam(String key, Object value) { - formParams.put(key, value); - return this; - } - - public RequestContextBuilder body(Object body) { - this.body = body; - return this; - } - - public RequestContextBuilder contentType(ContentType contentType) { - this.contentType = contentType; - return this; - } - - public RequestContext build() { - return new RequestContext(this); - } + public RequestContextBuilder queryParam(String key, Object value) { + queryParams.put(key, value); + return this; + } + + public RequestContextBuilder pathParam(String key, Object value) { + pathParams.put(key, value); + return this; + } + public RequestContextBuilder multipartPart(String key, Object value) { + multipartParts.put(key, value); + return this; } + public RequestContextBuilder formParam(String key, Object value) { + formParams.put(key, value); + return this; + } + + public RequestContextBuilder body(Object body) { + this.body = body; + return this; + } + + public RequestContextBuilder contentType(ContentType contentType) { + this.contentType = contentType; + return this; + } + + public RequestContext build() { + return new RequestContext(this); + } + + } + } diff --git a/src/main/java/io/github/felseje/apitestautomation/core/request/RetryRequest.java b/src/main/java/io/github/felseje/apitestautomation/core/request/RetryRequest.java index 407a91a..0d7c6b8 100644 --- a/src/main/java/io/github/felseje/apitestautomation/core/request/RetryRequest.java +++ b/src/main/java/io/github/felseje/apitestautomation/core/request/RetryRequest.java @@ -2,95 +2,94 @@ import io.github.felseje.apitestautomation.core.response.ApiResponse; import io.github.felseje.apitestautomation.util.ArgumentValidator; -import org.awaitility.Awaitility; - import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; import java.util.function.Supplier; +import org.awaitility.Awaitility; public class RetryRequest { - private static final String NULL_TIME_UNIT_ERROR = "The 'unit' cannot be null"; + private static final String NULL_TIME_UNIT_ERROR = "The 'unit' cannot be null"; - private final Supplier action; - private Duration timeout = Duration.ofSeconds(10); - private Duration poll = Duration.ofMillis(500); - private RetryStrategy strategy = RetryStrategy.AT_MOST; - private Duration minDuration; - private Duration maxDuration; + private final Supplier action; + private Duration timeout = Duration.ofSeconds(10); + private Duration poll = Duration.ofMillis(500); + private RetryStrategy strategy = RetryStrategy.AT_MOST; + private Duration minDuration; + private Duration maxDuration; - public RetryRequest(Supplier action) { - ArgumentValidator.requireNotNull(action, "The 'action' cannot be null"); - this.action = action; - } + public RetryRequest(Supplier action) { + ArgumentValidator.requireNotNull(action, "The 'action' cannot be null"); + this.action = action; + } - public RetryRequest atMost(long time, TimeUnit unit) { - ArgumentValidator.requireNotNull(unit, NULL_TIME_UNIT_ERROR); - this.strategy = RetryStrategy.AT_MOST; - this.timeout = Duration.ofMillis(unit.toMillis(time)); - return this; - } + public RetryRequest atMost(long time, TimeUnit unit) { + ArgumentValidator.requireNotNull(unit, NULL_TIME_UNIT_ERROR); + this.strategy = RetryStrategy.AT_MOST; + this.timeout = Duration.ofMillis(unit.toMillis(time)); + return this; + } - public RetryRequest atLeast(long time, TimeUnit unit) { - ArgumentValidator.requireNotNull(unit, NULL_TIME_UNIT_ERROR); - this.strategy = RetryStrategy.AT_LEAST; - this.minDuration = Duration.ofMillis(unit.toMillis(time)); - this.timeout = Duration.ofMillis(unit.toMillis(time)); - return this; - } + public RetryRequest atLeast(long time, TimeUnit unit) { + ArgumentValidator.requireNotNull(unit, NULL_TIME_UNIT_ERROR); + this.strategy = RetryStrategy.AT_LEAST; + this.minDuration = Duration.ofMillis(unit.toMillis(time)); + this.timeout = Duration.ofMillis(unit.toMillis(time)); + return this; + } - public RetryRequest between(long minTime, long maxTime, TimeUnit unit) { - ArgumentValidator.requireNotNull(unit, NULL_TIME_UNIT_ERROR); - this.strategy = RetryStrategy.BETWEEN; - this.minDuration = Duration.ofMillis(unit.toMillis(minTime)); - this.maxDuration = Duration.ofMillis(unit.toMillis(maxTime)); - return this; - } + public RetryRequest between(long minTime, long maxTime, TimeUnit unit) { + ArgumentValidator.requireNotNull(unit, NULL_TIME_UNIT_ERROR); + this.strategy = RetryStrategy.BETWEEN; + this.minDuration = Duration.ofMillis(unit.toMillis(minTime)); + this.maxDuration = Duration.ofMillis(unit.toMillis(maxTime)); + return this; + } - public RetryRequest pollEvery(long time, TimeUnit unit) { - ArgumentValidator.requireNotNull(unit, "The 'unit' cannot be null"); - this.poll = Duration.ofMillis(unit.toMillis(time)); - return this; - } + public RetryRequest pollEvery(long time, TimeUnit unit) { + ArgumentValidator.requireNotNull(unit, "The 'unit' cannot be null"); + this.poll = Duration.ofMillis(unit.toMillis(time)); + return this; + } - public ApiResponse until(Predicate condition) { - ArgumentValidator.requireNotNull(condition, "The 'condition' cannot be null"); - AtomicReference last = new AtomicReference<>(); - switch (strategy) { - case AT_MOST -> Awaitility.await() - .atMost(timeout) - .pollInterval(poll) - .ignoreExceptions() - .until(() -> { - ApiResponse response = action.get(); - last.set(response); - return condition.test(response); - }); - case AT_LEAST -> { - Awaitility.await() - .atLeast(minDuration) - .pollInterval(poll) - .ignoreExceptions() - .until(() -> { - ApiResponse response = action.get(); - last.set(response); - return condition.test(response); - }); - } - case BETWEEN -> Awaitility.await() - .atLeast(minDuration) - .atMost(maxDuration) - .pollInterval(poll) - .ignoreExceptions() - .until(() -> { - ApiResponse response = action.get(); - last.set(response); - return condition.test(response); - }); - } - return last.get(); + public ApiResponse until(Predicate condition) { + ArgumentValidator.requireNotNull(condition, "The 'condition' cannot be null"); + AtomicReference last = new AtomicReference<>(); + switch (strategy) { + case AT_MOST -> Awaitility.await() + .atMost(timeout) + .pollInterval(poll) + .ignoreExceptions() + .until(() -> { + ApiResponse response = action.get(); + last.set(response); + return condition.test(response); + }); + case AT_LEAST -> { + Awaitility.await() + .atLeast(minDuration) + .pollInterval(poll) + .ignoreExceptions() + .until(() -> { + ApiResponse response = action.get(); + last.set(response); + return condition.test(response); + }); + } + case BETWEEN -> Awaitility.await() + .atLeast(minDuration) + .atMost(maxDuration) + .pollInterval(poll) + .ignoreExceptions() + .until(() -> { + ApiResponse response = action.get(); + last.set(response); + return condition.test(response); + }); } + return last.get(); + } } diff --git a/src/main/java/io/github/felseje/apitestautomation/core/request/RetryStrategy.java b/src/main/java/io/github/felseje/apitestautomation/core/request/RetryStrategy.java index 1040813..d6b1fd8 100644 --- a/src/main/java/io/github/felseje/apitestautomation/core/request/RetryStrategy.java +++ b/src/main/java/io/github/felseje/apitestautomation/core/request/RetryStrategy.java @@ -1,7 +1,7 @@ package io.github.felseje.apitestautomation.core.request; public enum RetryStrategy { - AT_MOST, - AT_LEAST, - BETWEEN + AT_MOST, + AT_LEAST, + BETWEEN } diff --git a/src/main/java/io/github/felseje/apitestautomation/core/response/ApiResponse.java b/src/main/java/io/github/felseje/apitestautomation/core/response/ApiResponse.java index fa3ccd1..ddc34e1 100644 --- a/src/main/java/io/github/felseje/apitestautomation/core/response/ApiResponse.java +++ b/src/main/java/io/github/felseje/apitestautomation/core/response/ApiResponse.java @@ -1,180 +1,272 @@ package io.github.felseje.apitestautomation.core.response; +import static org.apache.http.HttpStatus.SC_ACCEPTED; +import static org.apache.http.HttpStatus.SC_BAD_GATEWAY; +import static org.apache.http.HttpStatus.SC_BAD_REQUEST; +import static org.apache.http.HttpStatus.SC_CREATED; +import static org.apache.http.HttpStatus.SC_FORBIDDEN; +import static org.apache.http.HttpStatus.SC_GATEWAY_TIMEOUT; +import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR; +import static org.apache.http.HttpStatus.SC_NOT_FOUND; +import static org.apache.http.HttpStatus.SC_NO_CONTENT; +import static org.apache.http.HttpStatus.SC_OK; +import static org.apache.http.HttpStatus.SC_SERVICE_UNAVAILABLE; +import static org.apache.http.HttpStatus.SC_UNAUTHORIZED; +import static org.apache.http.HttpStatus.SC_UNPROCESSABLE_ENTITY; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.hasXPath; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.hamcrest.Matchers.matchesPattern; + import io.github.felseje.apitestautomation.util.ArgumentValidator; import io.restassured.common.mapper.TypeRef; import io.restassured.module.jsv.JsonSchemaValidator; import io.restassured.response.Response; -import lombok.RequiredArgsConstructor; - import java.util.List; - -import static org.apache.http.HttpStatus.*; -import static org.hamcrest.Matchers.*; +import java.util.function.Consumer; +import lombok.RequiredArgsConstructor; +import org.hamcrest.Matcher; +import org.opentest4j.TestAbortedException; @RequiredArgsConstructor public class ApiResponse { - private static final int SC_TOO_MANY_REQUESTS = 429; - private final Response response; + private static final int SC_TOO_MANY_REQUESTS = 429; + private final Response response; - public ApiResponse shouldHaveStatus(int expectedStatusCode) { - response.then() - .assertThat() - .statusCode(expectedStatusCode); - return this; - } - - public ApiResponse shouldBeOk() { - return shouldHaveStatus(SC_OK); - } + public ApiResponse assumeThat(Consumer consumer, String message) { + ArgumentValidator.requireNotNull(consumer, "Consumer cannot be null"); + ArgumentValidator.requireNotBlank(message, "Message cannot be blank"); - public ApiResponse shouldBeCreated() { - return shouldHaveStatus(SC_CREATED); + try { + consumer.accept(this); + } catch (AssertionError e) { + throw new TestAbortedException(message); } - - public ApiResponse shouldBeAccepted() { - return shouldHaveStatus(SC_ACCEPTED); - } - - public ApiResponse shouldBeNoContent() { - return shouldHaveStatus(SC_NO_CONTENT); - } - - public ApiResponse shouldBeBadRequest() { - return shouldHaveStatus(SC_BAD_REQUEST); - } - - public ApiResponse shouldBeUnauthorized() { - return shouldHaveStatus(SC_UNAUTHORIZED); - } - - public ApiResponse shouldBeForbidden() { - return shouldHaveStatus(SC_FORBIDDEN); - } - - public ApiResponse shouldBeNotFound() { - return shouldHaveStatus(SC_NOT_FOUND); - } - - public ApiResponse shouldBeUnprocessableEntity() { - return shouldHaveStatus(SC_UNPROCESSABLE_ENTITY); - } - - public ApiResponse shouldBeTooManyRequests() { - return shouldHaveStatus(SC_TOO_MANY_REQUESTS); - } - - public ApiResponse shouldBeInternalServerError() { - return shouldHaveStatus(SC_INTERNAL_SERVER_ERROR); - } - - public ApiResponse shouldBeBadGateway() { - return shouldHaveStatus(SC_BAD_GATEWAY); - } - - public ApiResponse shouldBeServiceUnavailable() { - return shouldHaveStatus(SC_SERVICE_UNAVAILABLE); - } - - public ApiResponse shouldBeGatewayTimeout() { - return shouldHaveStatus(SC_GATEWAY_TIMEOUT); - } - - public ApiResponse shouldHaveJsonField(String path, Object value) { - ArgumentValidator.requireNotBlank(path, "Json path cannot be blank"); - response.then() - .assertThat() - .body(path, equalTo(value)); - return this; - } - - public ApiResponse shouldHaveHeader(String headerName, String expectedValue) { - ArgumentValidator.requireNotBlank(headerName, "Header name cannot be blank"); - ArgumentValidator.requireNotBlank(expectedValue, "Expected header value cannot be blank"); - response.then() - .assertThat() - .header(headerName, equalTo(expectedValue)); - return this; - } - - public ApiResponse shouldHaveHeaderContaining(String headerName, String expectedSubstring) { - ArgumentValidator.requireNotBlank(headerName, "Header name cannot be blank"); - ArgumentValidator.requireNotBlank(expectedSubstring, "Expected substring cannot be blank"); - response.then() - .assertThat() - .header(headerName, containsString(expectedSubstring)); - return this; - } - - public ApiResponse shouldHaveHeaderMatching(String headerName, String regex) { - ArgumentValidator.requireNotBlank(headerName, "Header name cannot be blank"); - ArgumentValidator.requireNotBlank(regex, "Regex cannot be blank"); - response.then() - .assertThat() - .header(headerName, matchesPattern(regex)); - return this; - } - - public ApiResponse shouldHaveXmlField(String xpath, String value) { - ArgumentValidator.requireNotBlank(xpath, "Xml path cannot be blank"); - response.then() - .assertThat() - .body(hasXPath(xpath, equalTo(value))); - return this; - } - - public ApiResponse shouldMatchJsonSchema(String schemaJson) { - ArgumentValidator.requireNotBlank(schemaJson, "Schema JSON cannot be blank"); - response.then() - .assertThat() - .body(JsonSchemaValidator.matchesJsonSchema(schemaJson)); - return this; - } - - public ApiResponse shouldMatchJsonSchemaInClasspath(String classpathResource) { - ArgumentValidator.requireNotBlank(classpathResource, "Classpath resource cannot be blank"); - response.then() - .assertThat() - .body(JsonSchemaValidator.matchesJsonSchemaInClasspath(classpathResource)); - return this; - } - - public boolean isInformational() { - return isStatusCodeInRange(100, 200); - } - - public boolean isSuccess() { - return isStatusCodeInRange(200, 300); - } - - public boolean isRedirection() { - return isStatusCodeInRange(300, 400); - } - - public boolean isClientError() { - return isStatusCodeInRange(400, 500); - } - - public boolean isServerError() { - return isStatusCodeInRange(500, 600); - } - - public boolean isStatusCodeInRange(int fromInclusive, int toExclusive) { - int statusCode = response.getStatusCode(); - return statusCode >= fromInclusive && statusCode < toExclusive; - } - - public Response raw() { - return response; - } - - public T as(Class clazz) { - return response.as(clazz); - } - - public List asList(Class clazz) { - return response.as(new TypeRef>() { - }); - } - + return this; + } + + public ApiResponse assumeStatusCode(int statusCode) { + return assumeThat( + consumer -> consumer.shouldHaveStatus(statusCode), + "The status code is not equal to expected" + ); + } + + public ApiResponse shouldHaveStatus(int expectedStatusCode) { + response.then() + .assertThat() + .statusCode(expectedStatusCode); + return this; + } + + public ApiResponse shouldBeOk() { + return shouldHaveStatus(SC_OK); + } + + public ApiResponse shouldBeCreated() { + return shouldHaveStatus(SC_CREATED); + } + + public ApiResponse shouldBeAccepted() { + return shouldHaveStatus(SC_ACCEPTED); + } + + public ApiResponse shouldBeNoContent() { + return shouldHaveStatus(SC_NO_CONTENT); + } + + public ApiResponse shouldBeBadRequest() { + return shouldHaveStatus(SC_BAD_REQUEST); + } + + public ApiResponse shouldBeUnauthorized() { + return shouldHaveStatus(SC_UNAUTHORIZED); + } + + public ApiResponse shouldBeForbidden() { + return shouldHaveStatus(SC_FORBIDDEN); + } + + public ApiResponse shouldBeNotFound() { + return shouldHaveStatus(SC_NOT_FOUND); + } + + public ApiResponse shouldBeUnprocessableEntity() { + return shouldHaveStatus(SC_UNPROCESSABLE_ENTITY); + } + + public ApiResponse shouldBeTooManyRequests() { + return shouldHaveStatus(SC_TOO_MANY_REQUESTS); + } + + public ApiResponse shouldBeInternalServerError() { + return shouldHaveStatus(SC_INTERNAL_SERVER_ERROR); + } + + public ApiResponse shouldBeBadGateway() { + return shouldHaveStatus(SC_BAD_GATEWAY); + } + + public ApiResponse shouldBeServiceUnavailable() { + return shouldHaveStatus(SC_SERVICE_UNAVAILABLE); + } + + public ApiResponse shouldBeGatewayTimeout() { + return shouldHaveStatus(SC_GATEWAY_TIMEOUT); + } + + public ApiResponse shouldHaveJsonField(String path, Object value) { + return assertJsonField(path, equalTo(value)); + + } + + public > ApiResponse shouldHaveJsonFieldGreaterThan( + String path, + T value + ) { + return assertJsonField(path, greaterThan(value)); + } + + public > ApiResponse shouldHaveJsonFieldLessThan( + String path, + T value + ) { + return assertJsonField(path, lessThan(value)); + } + + public > ApiResponse shouldHaveJsonFieldBetweenExclusive( + String path, + T minValue, + T maxValue + ) { + return assertJsonField(path, allOf( + greaterThan(minValue), + lessThan(maxValue) + )); + } + + public > ApiResponse shouldHaveJsonFieldBetweenInclusive( + String path, + T minValue, + T maxValue + ) { + return assertJsonField(path, allOf( + greaterThanOrEqualTo(minValue), + lessThanOrEqualTo(maxValue) + )); + } + + public ApiResponse shouldContainJsonField(String path) { + final int lastDot = path.lastIndexOf('.'); + final String parentPath = lastDot > 0 ? path.substring(0, lastDot) : "$"; + final String key = path.substring(lastDot + 1); + return assertJsonField(parentPath, hasKey(key)); + } + + public ApiResponse shouldHaveHeader(String headerName, String expectedValue) { + ArgumentValidator.requireNotBlank(expectedValue, "Expected header value cannot be blank"); + return assertHeader(headerName, equalTo(expectedValue)); + } + + public ApiResponse shouldHaveHeaderContaining(String headerName, String expectedSubstring) { + ArgumentValidator.requireNotBlank(expectedSubstring, "Expected substring cannot be blank"); + return assertHeader(headerName, containsString(expectedSubstring)); + } + + public ApiResponse shouldHaveHeaderMatching(String headerName, String regex) { + ArgumentValidator.requireNotBlank(regex, "Regex cannot be blank"); + return assertHeader(headerName, matchesPattern(regex)); + } + + public ApiResponse shouldHaveXmlField(String xpath, String value) { + ArgumentValidator.requireNotBlank(xpath, "Xml path cannot be blank"); + response.then() + .assertThat() + .body(hasXPath(xpath, equalTo(value))); + return this; + } + + public ApiResponse shouldMatchJsonSchema(String schemaJson) { + ArgumentValidator.requireNotBlank(schemaJson, "Schema JSON cannot be blank"); + response.then() + .assertThat() + .body(JsonSchemaValidator.matchesJsonSchema(schemaJson)); + return this; + } + + public ApiResponse shouldMatchJsonSchemaInClasspath(String classpathResource) { + ArgumentValidator.requireNotBlank(classpathResource, "Classpath resource cannot be blank"); + response.then() + .assertThat() + .body(JsonSchemaValidator.matchesJsonSchemaInClasspath(classpathResource)); + return this; + } + + public T getJsonFieldValue(String path) { + shouldContainJsonField(path); + return response.then() + .extract() + .path(path); + } + + public boolean isInformational() { + return isStatusCodeInRange(100, 200); + } + + public boolean isSuccess() { + return isStatusCodeInRange(200, 300); + } + + public boolean isRedirection() { + return isStatusCodeInRange(300, 400); + } + + public boolean isClientError() { + return isStatusCodeInRange(400, 500); + } + + public boolean isServerError() { + return isStatusCodeInRange(500, 600); + } + + public boolean isStatusCodeInRange(int fromInclusive, int toExclusive) { + int statusCode = response.getStatusCode(); + return statusCode >= fromInclusive && statusCode < toExclusive; + } + + public Response raw() { + return response; + } + + public T as(Class clazz) { + return response.as(clazz); + } + + public List asList(Class clazz) { + return response.as(new TypeRef>() { + }); + } + + private ApiResponse assertJsonField(String path, Matcher matcher) { + ArgumentValidator.requireNotBlank(path, "Json path cannot be blank"); + response.then() + .assertThat() + .body(path, matcher); + return this; + } + + private ApiResponse assertHeader(String headerName, Matcher matcher) { + ArgumentValidator.requireNotBlank(headerName, "Header name cannot be blank"); + response.then() + .assertThat() + .header(headerName, matcher); + return this; + } } diff --git a/src/main/java/io/github/felseje/apitestautomation/exception/ConfigurationException.java b/src/main/java/io/github/felseje/apitestautomation/exception/ConfigurationException.java index c36a95c..b6a968a 100644 --- a/src/main/java/io/github/felseje/apitestautomation/exception/ConfigurationException.java +++ b/src/main/java/io/github/felseje/apitestautomation/exception/ConfigurationException.java @@ -1,14 +1,15 @@ package io.github.felseje.apitestautomation.exception; public class ConfigurationException extends RuntimeException { - public ConfigurationException() { - } - public ConfigurationException(String message) { - super(message); - } + public ConfigurationException() { + } - public ConfigurationException(String message, Throwable cause) { - super(message, cause); - } + public ConfigurationException(String message) { + super(message); + } + + public ConfigurationException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/src/main/java/io/github/felseje/apitestautomation/factory/RequestSpecificationFactory.java b/src/main/java/io/github/felseje/apitestautomation/factory/RequestSpecificationFactory.java index f3c8a9d..fe6f50f 100644 --- a/src/main/java/io/github/felseje/apitestautomation/factory/RequestSpecificationFactory.java +++ b/src/main/java/io/github/felseje/apitestautomation/factory/RequestSpecificationFactory.java @@ -5,8 +5,10 @@ import io.github.felseje.apitestautomation.util.Strings; import io.restassured.builder.RequestSpecBuilder; import io.restassured.config.HttpClientConfig; +import io.restassured.config.ObjectMapperConfig; import io.restassured.config.RestAssuredConfig; import io.restassured.filter.log.LogDetail; +import io.restassured.mapper.ObjectMapperType; import io.restassured.specification.RequestSpecification; import lombok.AccessLevel; import lombok.NoArgsConstructor; @@ -14,28 +16,32 @@ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class RequestSpecificationFactory { - public static RequestSpecification getStandard() { - Config config = ConfigurationManager.getConfig(); - RestAssuredConfig restAssuredConfig = new RestAssuredConfig().httpClient(getHttpClientConfig(config)); - RequestSpecBuilder builder = new RequestSpecBuilder() - .setConfig(restAssuredConfig) - .setRelaxedHTTPSValidation() - .log(LogDetail.METHOD) - .log(LogDetail.URI) - .log(LogDetail.HEADERS) - .log(LogDetail.PARAMS) - .log(LogDetail.BODY); - if (!Strings.isBlank(config.baseUrl())) { - builder.setBaseUri(config.baseUrl()); - } - return builder.build(); + public static RequestSpecification getStandard() { + Config config = ConfigurationManager.getConfig(); + ObjectMapperConfig objMapperCfg = ObjectMapperConfig.objectMapperConfig() + .defaultObjectMapperType(ObjectMapperType.GSON); + RestAssuredConfig restAssuredConfig = new RestAssuredConfig() + .httpClient(getHttpClientConfig(config)) + .objectMapperConfig(objMapperCfg); + RequestSpecBuilder builder = new RequestSpecBuilder() + .setConfig(restAssuredConfig) + .setRelaxedHTTPSValidation() + .log(LogDetail.METHOD) + .log(LogDetail.URI) + .log(LogDetail.HEADERS) + .log(LogDetail.PARAMS) + .log(LogDetail.BODY); + if (!Strings.isBlank(config.baseUrl())) { + builder.setBaseUri(config.baseUrl()); } + return builder.build(); + } - private static HttpClientConfig getHttpClientConfig(Config config) { - return new HttpClientConfig() - .setParam("http.socket.timeout", config.httpSocketTimeout()) - .setParam("http.connect.timeout", config.httpConnectTimeout()) - .setParam("http.connection-manager.timeout", config.httpConnectionManagerTimeout()); - } + private static HttpClientConfig getHttpClientConfig(Config config) { + return new HttpClientConfig() + .setParam("http.socket.timeout", config.httpSocketTimeout()) + .setParam("http.connect.timeout", config.httpConnectTimeout()) + .setParam("http.connection-manager.timeout", config.httpConnectionManagerTimeout()); + } } diff --git a/src/main/java/io/github/felseje/apitestautomation/factory/ResponseSpecificationFactory.java b/src/main/java/io/github/felseje/apitestautomation/factory/ResponseSpecificationFactory.java index a33e35f..d2b776d 100644 --- a/src/main/java/io/github/felseje/apitestautomation/factory/ResponseSpecificationFactory.java +++ b/src/main/java/io/github/felseje/apitestautomation/factory/ResponseSpecificationFactory.java @@ -9,10 +9,10 @@ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class ResponseSpecificationFactory { - public static ResponseSpecification getStandard() { - return new ResponseSpecBuilder() - .log(LogDetail.ALL) - .build(); - } + public static ResponseSpecification getStandard() { + return new ResponseSpecBuilder() + .log(LogDetail.ALL) + .build(); + } } diff --git a/src/main/java/io/github/felseje/apitestautomation/service/login/LoginService.java b/src/main/java/io/github/felseje/apitestautomation/service/login/LoginService.java index 533773b..5b7b455 100644 --- a/src/main/java/io/github/felseje/apitestautomation/service/login/LoginService.java +++ b/src/main/java/io/github/felseje/apitestautomation/service/login/LoginService.java @@ -10,12 +10,12 @@ @RequiredArgsConstructor public class LoginService { - private final LoginClient loginClient; + private final LoginClient loginClient; - public ApiResponse login(LoginRequest request) { - ArgumentValidator.requireNotNull(request, "The login request cannot be null"); - Response response = loginClient.login(request); - return new ApiResponse(response); - } + public ApiResponse login(LoginRequest request) { + ArgumentValidator.requireNotNull(request, "The login request cannot be null"); + Response response = loginClient.login(request); + return new ApiResponse(response); + } } diff --git a/src/main/java/io/github/felseje/apitestautomation/service/user/UserService.java b/src/main/java/io/github/felseje/apitestautomation/service/user/UserService.java new file mode 100644 index 0000000..9ab09d9 --- /dev/null +++ b/src/main/java/io/github/felseje/apitestautomation/service/user/UserService.java @@ -0,0 +1,44 @@ +package io.github.felseje.apitestautomation.service.user; + +import io.github.felseje.apitestautomation.client.user.UserClient; +import io.github.felseje.apitestautomation.client.user.dto.request.CreateUserRequest; +import io.github.felseje.apitestautomation.client.user.dto.request.UpdateUserRequest; +import io.github.felseje.apitestautomation.core.response.ApiResponse; +import io.github.felseje.apitestautomation.util.ArgumentValidator; +import io.restassured.response.Response; +import java.util.Map; +import lombok.RequiredArgsConstructor; + +@RequiredArgsConstructor +public class UserService { + + private final UserClient userClient; + + public ApiResponse createUser(CreateUserRequest requestBody) { + ArgumentValidator.requireNotNull(requestBody, "The request body cannot be null"); + Response response = userClient.createUser(requestBody); + return new ApiResponse(response); + } + + public ApiResponse readUser(String userId) { + Response response = userClient.getUser(userId); + return new ApiResponse(response); + } + + public ApiResponse readAllUsers(Map queryParams) { + ArgumentValidator.requireNotNull(queryParams, "The query params cannot be null"); + Response response = userClient.getUsers(queryParams); + return new ApiResponse(response); + } + + public ApiResponse updateUser(String userId, UpdateUserRequest requestBody) { + ArgumentValidator.requireNotNull(requestBody, "The request body cannot be null"); + Response response = userClient.updateUser(userId, requestBody); + return new ApiResponse(response); + } + + public ApiResponse deleteUser(String userId) { + Response response = userClient.deleteUser(userId); + return new ApiResponse(response); + } +} diff --git a/src/main/java/io/github/felseje/apitestautomation/util/ArgumentValidator.java b/src/main/java/io/github/felseje/apitestautomation/util/ArgumentValidator.java index 43a28e4..fd3d3d9 100644 --- a/src/main/java/io/github/felseje/apitestautomation/util/ArgumentValidator.java +++ b/src/main/java/io/github/felseje/apitestautomation/util/ArgumentValidator.java @@ -6,25 +6,24 @@ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class ArgumentValidator { - private static final String DEFAULT_NULL_MESSAGE = "Argument cannot be null"; - private static final String DEFAULT_BLANK_MESSAGE = "Argument cannot be blank"; + private static final String DEFAULT_NULL_MESSAGE = "Argument cannot be null"; + private static final String DEFAULT_BLANK_MESSAGE = "Argument cannot be blank"; - public static void requireNotNull(Object argument, String errorMessage) { - if (argument != null) { - return; - } - throw new IllegalArgumentException( - Strings.isBlank(errorMessage) ? DEFAULT_NULL_MESSAGE : errorMessage - ); + public static void requireNotNull(Object argument, String errorMessage) { + if (argument != null) { + return; } + throw new IllegalArgumentException( + Strings.isBlank(errorMessage) ? DEFAULT_NULL_MESSAGE : errorMessage + ); + } - public static void requireNotBlank(String argument, String errorMessage) { - if (!Strings.isBlank(argument)) { - return; - } - throw new IllegalArgumentException( - Strings.isBlank(errorMessage) ? DEFAULT_BLANK_MESSAGE : errorMessage - ); + public static void requireNotBlank(String argument, String errorMessage) { + if (!Strings.isBlank(argument)) { + return; } - + throw new IllegalArgumentException( + Strings.isBlank(errorMessage) ? DEFAULT_BLANK_MESSAGE : errorMessage + ); + } } diff --git a/src/main/java/io/github/felseje/apitestautomation/util/DataFaker.java b/src/main/java/io/github/felseje/apitestautomation/util/DataFaker.java new file mode 100644 index 0000000..dbe79f4 --- /dev/null +++ b/src/main/java/io/github/felseje/apitestautomation/util/DataFaker.java @@ -0,0 +1,40 @@ +package io.github.felseje.apitestautomation.util; + +import java.util.Locale; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import net.datafaker.Faker; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class DataFaker { + + private static final Faker FAKER = new Faker(Locale.of("pt", "BR")); + + public static String getFirstName() { + return FAKER.name().firstName(); + } + + public static String getLastName() { + return FAKER.name().lastName(); + } + + public static String getFullName() { + return FAKER.name().fullName(); + } + + public static String getUsername() { + return FAKER.credentials().username(); + } + + public static String getEmail() { + return FAKER.internet().emailAddress(); + } + + public static String getPassword() { + return FAKER.credentials().password(); + } + + public static String getRandomAlphanumericString(int length) { + return FAKER.regexify("[a-zA-Z0-9]{" + length + "}"); + } +} diff --git a/src/main/java/io/github/felseje/apitestautomation/util/Strings.java b/src/main/java/io/github/felseje/apitestautomation/util/Strings.java index c54a3bb..426dcf7 100644 --- a/src/main/java/io/github/felseje/apitestautomation/util/Strings.java +++ b/src/main/java/io/github/felseje/apitestautomation/util/Strings.java @@ -1,13 +1,20 @@ package io.github.felseje.apitestautomation.util; +import java.text.Normalizer; import lombok.AccessLevel; import lombok.NoArgsConstructor; @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class Strings { - public static boolean isBlank(String value) { - return value == null || value.isBlank(); - } + public static boolean isBlank(String value) { + return value == null || value.isBlank(); + } + + public static String normalize(String string) { + return Normalizer.normalize(string, Normalizer.Form.NFD) + .replaceAll("\\p{M}", "") + .replaceAll("[^a-zA-Z0-9]", ""); + } } diff --git a/src/test/java/io/github/felseje/apitestautomation/suite/FullTestSuite.java b/src/test/java/io/github/felseje/apitestautomation/suite/FullTestSuite.java index 9bf0aa3..d0976e9 100644 --- a/src/test/java/io/github/felseje/apitestautomation/suite/FullTestSuite.java +++ b/src/test/java/io/github/felseje/apitestautomation/suite/FullTestSuite.java @@ -1,6 +1,7 @@ package io.github.felseje.apitestautomation.suite; import io.github.felseje.apitestautomation.test.LoginIT; +import io.github.felseje.apitestautomation.test.UserIT; import org.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; import org.junit.platform.suite.api.SuiteDisplayName; @@ -8,7 +9,9 @@ @Suite @SuiteDisplayName("Full Test Suite") @SelectClasses({ - LoginIT.class + LoginIT.class, + UserIT.class }) -public class FullTestSuite { +class FullTestSuite { + } diff --git a/src/test/java/io/github/felseje/apitestautomation/test/LoginIT.java b/src/test/java/io/github/felseje/apitestautomation/test/LoginIT.java index 3e0400a..ea74690 100644 --- a/src/test/java/io/github/felseje/apitestautomation/test/LoginIT.java +++ b/src/test/java/io/github/felseje/apitestautomation/test/LoginIT.java @@ -5,6 +5,7 @@ import io.github.felseje.apitestautomation.core.response.ApiResponse; import io.github.felseje.apitestautomation.service.login.LoginService; import io.github.felseje.apitestautomation.testdata.LoginProvider; +import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Tag; @@ -13,84 +14,83 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.util.stream.Stream; - @Tag("login") @DisplayName("Login Tests") public class LoginIT { - private final LoginService loginService = new LoginService(new LoginClient()); + private final LoginService loginService = new LoginService(new LoginClient()); - @Nested - @DisplayName("Successful login scenarios") - public class SuccessfulLogin { + @Nested + @DisplayName("Successful login scenarios") + public class SuccessfulLogin { - private static final String LOGIN_SUCCESS_SCHEMA = "schemas/login/success.json"; + private static final String LOGIN_SUCCESS_SCHEMA = "schemas/login/success.json"; - @Test - @DisplayName("Should authenticate successfully when valid credentials are provided") - void shouldAuthenticateSuccessfully() { - // Arrange - LoginRequest request = LoginProvider.getValidLoginRequest(); + @Test + @DisplayName("Should authenticate successfully when valid credentials are provided") + void shouldAuthenticateSuccessfully() { + // Arrange + LoginRequest request = LoginProvider.getValidLoginRequest(); - // Act - ApiResponse response = loginService.login(request); + // Act + ApiResponse response = loginService.login(request); - // Assert - response.shouldBeOk() - .shouldMatchJsonSchemaInClasspath(LOGIN_SUCCESS_SCHEMA); - } + // Assert + response.shouldBeOk() + .shouldMatchJsonSchemaInClasspath(LOGIN_SUCCESS_SCHEMA); + } + } + + @Nested + @DisplayName("Failed login scenarios") + public class FailedLogin { + + private static final String LOGIN_UNAUTHORIZED_SCHEMA = "schemas/login/unauthorized.json"; + private static final String LOGIN_EMPTY_EMAIL_SCHEMA = "schemas/login/empty-email.json"; + private static final String LOGIN_EMPTY_PASSWORD_SCHEMA = "schemas/login/empty-password.json"; + + static Stream provideEmptyLoginFieldsForBadRequest() { + return Stream.of( + Arguments.of( + "Should return Bad Request when email is empty", + LOGIN_EMPTY_EMAIL_SCHEMA, + LoginProvider.getLoginRequestWithEmptyEmail() + ), + Arguments.of( + "Should return Bad Request when password is empty", + LOGIN_EMPTY_PASSWORD_SCHEMA, + LoginProvider.getLoginRequestWithEmptyPassword() + ) + ); } - @Nested - @DisplayName("Failed login scenarios") - public class FailedLogin { - - private static final String LOGIN_UNAUTHORIZED_SCHEMA = "schemas/login/unauthorized.json"; - private static final String LOGIN_EMPTY_EMAIL_SCHEMA = "schemas/login/empty-email.json"; - private static final String LOGIN_EMPTY_PASSWORD_SCHEMA = "schemas/login/empty-password.json"; - - static Stream provideEmptyLoginFieldsForBadRequest() { - return Stream.of( - Arguments.of( - "Should return Bad Request when email is empty", - LOGIN_EMPTY_EMAIL_SCHEMA, - LoginProvider.getLoginRequestWithEmptyEmail() - ), - Arguments.of( - "Should return Bad Request when password is empty", - LOGIN_EMPTY_PASSWORD_SCHEMA, - LoginProvider.getLoginRequestWithEmptyPassword() - ) - ); - } - - @Test - @DisplayName("Should return unauthorized when invalid credentials are provided") - void shouldReturnUnauthorizedWhenCredentialsAreInvalid() { - // Arrange - LoginRequest request = LoginProvider.getLoginRequestWithUnauthorizedCredentials(); - - // Act - ApiResponse response = loginService.login(request); - - // Assert - response.shouldBeUnauthorized() - .shouldMatchJsonSchemaInClasspath(LOGIN_UNAUTHORIZED_SCHEMA); - } - - @ParameterizedTest(name = "{0}") - @MethodSource("provideEmptyLoginFieldsForBadRequest") - void shouldReturnBadRequestForEmptyFields(String testName, String expectedSchema, LoginRequest request) { - // Act - ApiResponse response = loginService.login(request); - - // Assert - response.shouldBeBadRequest() - .shouldMatchJsonSchemaInClasspath(expectedSchema); - } + @Test + @DisplayName("Should return unauthorized when invalid credentials are provided") + void shouldReturnUnauthorizedWhenCredentialsAreInvalid() { + // Arrange + LoginRequest request = LoginProvider.getLoginRequestWithUnauthorizedCredentials(); + + // Act + ApiResponse response = loginService.login(request); + // Assert + response.shouldBeUnauthorized() + .shouldMatchJsonSchemaInClasspath(LOGIN_UNAUTHORIZED_SCHEMA); } + @ParameterizedTest(name = "{0}") + @MethodSource("provideEmptyLoginFieldsForBadRequest") + void shouldReturnBadRequestForEmptyFields(String testName, String expectedSchema, + LoginRequest request) { + // Act + ApiResponse response = loginService.login(request); + + // Assert + response.shouldBeBadRequest() + .shouldMatchJsonSchemaInClasspath(expectedSchema); + } + + } + } diff --git a/src/test/java/io/github/felseje/apitestautomation/test/UserIT.java b/src/test/java/io/github/felseje/apitestautomation/test/UserIT.java new file mode 100644 index 0000000..c3f733e --- /dev/null +++ b/src/test/java/io/github/felseje/apitestautomation/test/UserIT.java @@ -0,0 +1,373 @@ +package io.github.felseje.apitestautomation.test; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import io.github.felseje.apitestautomation.client.user.UserClient; +import io.github.felseje.apitestautomation.client.user.dto.request.CreateUserRequest; +import io.github.felseje.apitestautomation.client.user.dto.request.UpdateUserRequest; +import io.github.felseje.apitestautomation.client.user.dto.response.UserListResponse; +import io.github.felseje.apitestautomation.client.user.dto.response.UserResponse; +import io.github.felseje.apitestautomation.core.response.ApiResponse; +import io.github.felseje.apitestautomation.service.user.UserService; +import io.github.felseje.apitestautomation.testdata.UserProvider; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import java.util.stream.Stream; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +@Tag("user") +@DisplayName("User Tests") +public class UserIT { + + private final UserService userService = new UserService(new UserClient()); + + @Nested + @DisplayName("Success user scenarios") + class SuccessUserScenarios { + + @Test + @DisplayName("Should create user successfully when all required fields are valid") + void shouldCreateUserSuccessfully() { + // Arrange + CreateUserRequest request = UserProvider.getValidCreateUserRequest(); + + // Act + ApiResponse apiResponse = userService.createUser(request); + + // Assert + String userId = apiResponse.shouldBeCreated() + .shouldHaveJsonField("message", "Cadastro realizado com sucesso") + .shouldContainJsonField("_id") + .getJsonFieldValue("_id"); + UserResponse createdUser = userService.readUser(userId) + .shouldBeOk() + .as(UserResponse.class); + assertAll("User fields must match request", + () -> assertEquals(userId, createdUser.getId(), "User id mismatch"), + () -> assertEquals(request.getName(), createdUser.getName(), "User name mismatch"), + () -> assertEquals(request.getEmail(), createdUser.getEmail(), "User email mismatch"), + () -> assertEquals(request.getPassword(), createdUser.getPassword(), + "User password mismatch"), + () -> assertEquals(request.getAdministrator(), createdUser.getAdministrator(), + "User administrator mismatch") + ); + } + + @Test + @DisplayName("Should read user by ID successfully when user exists") + void shouldReadUserByIdSuccessfully() { + // Arrange + String userId = "0uxuPY0cbmQhpEz1"; + + // Act + ApiResponse apiResponse = userService.readUser(userId); + + // Assert + UserResponse user = apiResponse.shouldBeOk() + .as(UserResponse.class); + assertAll( + () -> assertEquals("Fulano da Silva", user.getName(), "User name mismatch"), + () -> assertEquals("fulano@qa.com", user.getEmail(), "User email mismatch"), + () -> assertEquals("teste", user.getPassword(), "User password mismatch"), + () -> assertEquals("true", user.getAdministrator(), "User administrator mismatch"), + () -> assertEquals("0uxuPY0cbmQhpEz1", user.getId(), "User id mismatch") + ); + } + + @Test + @DisplayName("Should read all users successfully") + void shouldReadAllUsersSuccessfully() { + // Arrange + Map queryParams = Map.of(); + + // Act + ApiResponse apiResponse = userService.readAllUsers(queryParams); + + // Assert + List users = apiResponse.shouldBeOk() + .shouldHaveJsonFieldGreaterThan("quantidade", 1) + .getJsonFieldValue("usuarios"); + assertFalse(users.isEmpty()); + } + + @Test + @DisplayName("Should filter users by query params successfully") + void shouldFilterUsersByQueryParamsSuccessfully() { + // Arrange + Map queryParams = Map.of("nome", "Fulano da Silva"); + + // Act + ApiResponse apiResponse = userService.readAllUsers(queryParams); + + // Assert + UserListResponse users = apiResponse.shouldBeOk() + .shouldHaveJsonField("quantidade", 1) + .as(UserListResponse.class); + UserResponse user = users.getUsers().getFirst(); + assertAll( + () -> assertEquals("Fulano da Silva", user.getName(), "User name mismatch"), + () -> assertEquals("fulano@qa.com", user.getEmail(), "User email mismatch"), + () -> assertEquals("teste", user.getPassword(), "User password mismatch"), + () -> assertEquals("true", user.getAdministrator(), "User administrator mismatch"), + () -> assertEquals("0uxuPY0cbmQhpEz1", user.getId(), "User id mismatch") + ); + } + + @Test + @DisplayName("Should update user successfully when user exists") + void shouldUpdateUserSuccessfully() { + // Arrange + CreateUserRequest createRequest = UserProvider.getValidCreateUserRequest(); + UserResponse user = userService.createUser(createRequest) + .assumeStatusCode(201) + .as(UserResponse.class); + UpdateUserRequest updateRequest = new UpdateUserRequest( + createRequest.getName(), + createRequest.getEmail(), + "P4ssw0rd", + createRequest.getAdministrator() + ); + + // Act + ApiResponse apiResponse = userService.updateUser(user.getId(), updateRequest); + + // Assert + apiResponse.shouldBeOk() + .shouldHaveJsonField("message", "Registro alterado com sucesso"); + UserResponse createdUser = userService.readUser(user.getId()) + .shouldBeOk() + .as(UserResponse.class); + assertAll("User fields must match request", + () -> assertEquals(user.getId(), createdUser.getId(), "User id mismatch"), + () -> assertEquals(updateRequest.getName(), createdUser.getName(), "User name mismatch"), + () -> assertEquals(updateRequest.getEmail(), createdUser.getEmail(), + "User email mismatch"), + () -> assertEquals(updateRequest.getPassword(), createdUser.getPassword(), + "User password mismatch"), + () -> assertEquals(updateRequest.getAdministrator(), createdUser.getAdministrator(), + "User administrator mismatch") + ); + } + + @Test + @DisplayName("Should create user via PUT when ID does not exist") + void shouldCreateUserViaPutWhenIdDoesNotExist() { + // Arrange + String userId = UserProvider.getValidRandomUserId(); + UpdateUserRequest updateRequest = UserProvider.getValidUpdateUserRequest(); + + // Act + ApiResponse apiResponse = userService.updateUser(userId, updateRequest); + + // Assert + String createdId = apiResponse.shouldBeCreated() + .shouldHaveJsonField("message", "Cadastro realizado com sucesso") + .getJsonFieldValue("_id"); + UserResponse createdUser = userService.readUser(createdId) + .shouldBeOk() + .as(UserResponse.class); + assertAll("User fields must match request", + () -> assertEquals(createdId, createdUser.getId(), "User id mismatch"), + () -> assertEquals(updateRequest.getName(), createdUser.getName(), "User name mismatch"), + () -> assertEquals(updateRequest.getEmail(), createdUser.getEmail(), + "User email mismatch"), + () -> assertEquals(updateRequest.getPassword(), createdUser.getPassword(), + "User password mismatch"), + () -> assertEquals(updateRequest.getAdministrator(), createdUser.getAdministrator(), + "User administrator mismatch") + ); + } + + @Test + @DisplayName("Should delete user successfully when user exists and has no cart") + void shouldDeleteUserSuccessfully() { + // Arrange + CreateUserRequest createRequest = UserProvider.getValidCreateUserRequest(); + String userId = userService.createUser(createRequest) + .assumeStatusCode(201) + .getJsonFieldValue("_id"); + // Act + ApiResponse apiResponse = userService.deleteUser(userId); + + // Assert + apiResponse.shouldBeOk() + .shouldHaveJsonField("message", "Registro excluído com sucesso"); + userService.readUser(userId) + .shouldBeBadRequest() + .shouldHaveJsonField("message", "Usuário não encontrado"); + } + } + + @Nested + @DisplayName("Failure user scenarios") + class FailureUserScenarios { + + static Stream invalidCreateUserRequests() { + return Stream.of( + scenario( + "blank name", + r -> r.setName(""), + "nome", + "nome não pode ficar em branco" + ), + scenario( + "blank email", + r -> r.setEmail(""), + "email", + "email não pode ficar em branco" + ), + scenario( + "blank password", + r -> r.setPassword(""), + "password", + "password não pode ficar em branco" + ), + scenario( + "blank administrator", + r -> r.setAdministrator(""), + "administrador", + "administrador deve ser 'true' ou 'false'" + ) + ); + } + + private static Arguments scenario( + String description, + Consumer invalidation, + String jsonField, + String expectedMessage) { + return Arguments.of(description, invalidation, jsonField, expectedMessage); + } + + @Test + @DisplayName("Should return 400 Bad Request when creating user with duplicate email") + void shouldFailToCreateUserWithDuplicateEmail() { + // Arrange + CreateUserRequest firstUser = UserProvider.getValidCreateUserRequest(); + CreateUserRequest secondUser = UserProvider.getValidCreateUserRequest(); + secondUser.setEmail(firstUser.getEmail()); + userService.createUser(firstUser).assumeStatusCode(201); + + // Act + ApiResponse apiResponse = userService.createUser(secondUser); + + // Assert + apiResponse.shouldBeBadRequest() + .shouldHaveJsonField("message", "Este email já está sendo usado"); + } + + @ParameterizedTest(name = "[{index}] {0}") + @MethodSource("invalidCreateUserRequests") + @DisplayName("Should return 400 Bad Request when creating user with missing required fields") + void shouldFailToCreateUserWithMissingRequiredFields( + String scenario, + Consumer invalidation, + String jsonField, + String expectedMessage + ) { + // Arrange + CreateUserRequest request = UserProvider.getValidCreateUserRequest(); + invalidation.accept(request); + + // Act + ApiResponse apiResponse = userService.createUser(request); + + // Assert + apiResponse.shouldBeBadRequest() + .shouldHaveJsonField(jsonField, expectedMessage); + } + + @Test + @DisplayName("Should return 400 Bad Request when reading user with non-existent ID") + void shouldFailToReadUserWithNonExistentId() { + // Arrange + String userId = "N0Na3X1S73N7a1Da"; + + // Act + ApiResponse apiResponse = userService.readUser(userId); + + // Assert + apiResponse.shouldBeBadRequest() + .shouldHaveJsonField("message", "Usuário não encontrado"); + } + + @Test + @DisplayName("Should return 400 Bad Request when updating user with duplicate email") + void shouldFailToUpdateUserWithDuplicateEmail() { + // Arrange + CreateUserRequest firstUserData = UserProvider.getValidCreateUserRequest(); + CreateUserRequest secondUserData = UserProvider.getValidCreateUserRequest(); + userService.createUser(firstUserData) + .assumeStatusCode(201); + String secondUserId = userService.createUser(secondUserData) + .assumeStatusCode(201) + .getJsonFieldValue("_id"); + UpdateUserRequest updateRequest = new UpdateUserRequest( + secondUserData.getName(), + firstUserData.getEmail(), + secondUserData.getPassword(), + secondUserData.getAdministrator() + ); + + // Act + ApiResponse apiResponse = userService.updateUser(secondUserId, updateRequest); + + // Assert + apiResponse.shouldBeBadRequest() + .shouldHaveJsonField("message", "Este email já está sendo usado"); + } + + @Test + @DisplayName("Should return 400 Bad Request when updating user with invalid body") + void shouldFailToUpdateUserWithInvalidBody() { + // Arrange + String userId = "0uxuPY0cbmQhpEz1"; + UpdateUserRequest updateRequest = new UpdateUserRequest(); + + // Act + ApiResponse apiResponse = userService.updateUser(userId, updateRequest); + + // Assert + apiResponse.shouldBeBadRequest() + .shouldMatchJsonSchemaInClasspath("schemas/user/create-user-empty-body.json"); + } + + @Test + @DisplayName("Should return 200 OK with no records deleted message when deleting non-existent user") + void shouldReturnNoRecordsDeletedWhenDeletingNonExistentUser() { + // Arrange + String userId = "0uxuPY0cbmQhpEz2"; + + // Act + ApiResponse apiResponse = userService.deleteUser(userId); + + // Assert + apiResponse.shouldBeOk() + .shouldHaveJsonField("message", "Nenhum registro excluído"); + } + + @Test + @DisplayName("Should return 400 Bad Request when deleting user with an active cart") + void shouldFailToDeleteUserWithActiveCart() { + // Arrange + String userId = "0uxuPY0cbmQhpEz1"; + + // Act + ApiResponse apiResponse = userService.deleteUser(userId); + + // Assert + apiResponse.shouldBeBadRequest() + .shouldHaveJsonField("message", + "Não é permitido excluir usuário com carrinho cadastrado"); + } + } +} \ No newline at end of file diff --git a/src/test/java/io/github/felseje/apitestautomation/testdata/LoginProvider.java b/src/test/java/io/github/felseje/apitestautomation/testdata/LoginProvider.java index a647f43..3ba0824 100644 --- a/src/test/java/io/github/felseje/apitestautomation/testdata/LoginProvider.java +++ b/src/test/java/io/github/felseje/apitestautomation/testdata/LoginProvider.java @@ -7,23 +7,23 @@ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class LoginProvider { - private static final String VALID_EMAIL = "fulano@qa.com"; - private static final String VALID_PASSWORD = "teste"; + private static final String VALID_EMAIL = "fulano@qa.com"; + private static final String VALID_PASSWORD = "teste"; - public static LoginRequest getValidLoginRequest() { - return new LoginRequest(VALID_EMAIL, VALID_PASSWORD); - } + public static LoginRequest getValidLoginRequest() { + return new LoginRequest(VALID_EMAIL, VALID_PASSWORD); + } - public static LoginRequest getLoginRequestWithUnauthorizedCredentials() { - return new LoginRequest("unauth@mail.com", "p4ssw0rd"); - } + public static LoginRequest getLoginRequestWithUnauthorizedCredentials() { + return new LoginRequest("unauth@mail.com", "p4ssw0rd"); + } - public static LoginRequest getLoginRequestWithEmptyEmail() { - return new LoginRequest("", "p4ssw0rd"); - } + public static LoginRequest getLoginRequestWithEmptyEmail() { + return new LoginRequest("", "p4ssw0rd"); + } - public static LoginRequest getLoginRequestWithEmptyPassword() { - return new LoginRequest("rTyxUuv@qa.com", ""); - } + public static LoginRequest getLoginRequestWithEmptyPassword() { + return new LoginRequest("rTyxUuv@qa.com", ""); + } } diff --git a/src/test/java/io/github/felseje/apitestautomation/testdata/UserProvider.java b/src/test/java/io/github/felseje/apitestautomation/testdata/UserProvider.java new file mode 100644 index 0000000..485fe96 --- /dev/null +++ b/src/test/java/io/github/felseje/apitestautomation/testdata/UserProvider.java @@ -0,0 +1,50 @@ +package io.github.felseje.apitestautomation.testdata; + +import io.github.felseje.apitestautomation.client.user.dto.UserDto; +import io.github.felseje.apitestautomation.client.user.dto.request.CreateUserRequest; +import io.github.felseje.apitestautomation.client.user.dto.request.UpdateUserRequest; +import io.github.felseje.apitestautomation.util.DataFaker; +import io.github.felseje.apitestautomation.util.Strings; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class UserProvider { + + public static CreateUserRequest getValidCreateUserRequest() { + return createUser(CreateUserRequest::new); + } + + public static UpdateUserRequest getValidUpdateUserRequest() { + return createUser(UpdateUserRequest::new); + } + + public static String getValidRandomUserId() { + return "T3sT" + DataFaker.getRandomAlphanumericString(12); + } + + private static T createUser( + QuadFunction constructor + ) { + final String firstName = DataFaker.getFirstName(); + final String lastName = DataFaker.getLastName(); + final String username = + Strings.normalize(firstName + lastName).toLowerCase(); + final String email = + username + "@" + DataFaker.getEmail().split("@")[1]; + final String password = DataFaker.getPassword(); + + return constructor.apply( + firstName + " " + lastName, + email, + password, + "false" + ); + } + + @FunctionalInterface + private interface QuadFunction { + + R apply(A a, B b, C c, D d); + } +} diff --git a/src/test/resources/schemas/login/empty-email.json b/src/test/resources/schemas/login/empty-email.json index b5569eb..1f64e30 100644 --- a/src/test/resources/schemas/login/empty-email.json +++ b/src/test/resources/schemas/login/empty-email.json @@ -10,4 +10,4 @@ "const": "email não pode ficar em branco" } } -} \ No newline at end of file +} diff --git a/src/test/resources/schemas/login/empty-password.json b/src/test/resources/schemas/login/empty-password.json index a25f85e..070a76c 100644 --- a/src/test/resources/schemas/login/empty-password.json +++ b/src/test/resources/schemas/login/empty-password.json @@ -10,4 +10,4 @@ "const": "password não pode ficar em branco" } } -} \ No newline at end of file +} diff --git a/src/test/resources/schemas/login/success.json b/src/test/resources/schemas/login/success.json index 89c4fc5..a65317a 100644 --- a/src/test/resources/schemas/login/success.json +++ b/src/test/resources/schemas/login/success.json @@ -14,4 +14,4 @@ "pattern": "^Bearer .*" } } -} \ No newline at end of file +} diff --git a/src/test/resources/schemas/login/unauthorized.json b/src/test/resources/schemas/login/unauthorized.json index 02278b3..998b1e2 100644 --- a/src/test/resources/schemas/login/unauthorized.json +++ b/src/test/resources/schemas/login/unauthorized.json @@ -10,4 +10,4 @@ "const": "Email e/ou senha inválidos" } } -} \ No newline at end of file +} diff --git a/src/test/resources/schemas/user/create-user-empty-body.json b/src/test/resources/schemas/user/create-user-empty-body.json new file mode 100644 index 0000000..a022acc --- /dev/null +++ b/src/test/resources/schemas/user/create-user-empty-body.json @@ -0,0 +1,6 @@ +{ + "nome": "nome é obrigatório", + "email": "email é obrigatório", + "password": "password é obrigatório", + "administrador": "administrador é obrigatório" +} From dc3f19db8fcc1c31101e719b8bf9fdc3fabf7483 Mon Sep 17 00:00:00 2001 From: Felseje Date: Sat, 3 Oct 2026 23:48:46 -0300 Subject: [PATCH 3/3] Implementing tests for the user endpoint --- .github/workflows/maven-ci.yml | 40 ++++++++++++------- .../apitestautomation/test/LoginIT.java | 4 +- .../testdata/LoginProvider.java | 9 +++-- .../schemas/user/create-user-empty-body.json | 30 ++++++++++++-- 4 files changed, 58 insertions(+), 25 deletions(-) diff --git a/.github/workflows/maven-ci.yml b/.github/workflows/maven-ci.yml index a17a859..fccb3e1 100644 --- a/.github/workflows/maven-ci.yml +++ b/.github/workflows/maven-ci.yml @@ -10,39 +10,49 @@ on: - main - example +permissions: + contents: read + checks: write + jobs: - build: + integration-tests: runs-on: ubuntu-latest steps: - name: Checkout Repo - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Setup Java 21 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: temurin java-version: '21' + cache: maven - - name: Cache Maven Dependencies - uses: actions/cache@v3 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven- - - - name: Build and Run Tests + - name: Run Integration Tests (Failsafe) run: mvn clean verify + - name: Test Report + uses: dorny/test-reporter@v1 + if: always() + with: + name: API Integration Tests + path: target/failsafe-reports/TEST-*.xml + reporter: java-junit + fail-on-error: false + - name: Upload Failsafe HTML Report uses: actions/upload-artifact@v4 + if: always() with: name: failsafe-html-report - path: target/site/failsafe-report + path: target/site + if-no-files-found: ignore - name: Upload Raw Test Results uses: actions/upload-artifact@v4 + if: always() with: - name: surefire-reports - path: target/surefire-reports \ No newline at end of file + name: failsafe-reports + path: target/failsafe-reports + if-no-files-found: ignore \ No newline at end of file diff --git a/src/test/java/io/github/felseje/apitestautomation/test/LoginIT.java b/src/test/java/io/github/felseje/apitestautomation/test/LoginIT.java index ea74690..c18a019 100644 --- a/src/test/java/io/github/felseje/apitestautomation/test/LoginIT.java +++ b/src/test/java/io/github/felseje/apitestautomation/test/LoginIT.java @@ -22,7 +22,7 @@ public class LoginIT { @Nested @DisplayName("Successful login scenarios") - public class SuccessfulLogin { + class SuccessfulLogin { private static final String LOGIN_SUCCESS_SCHEMA = "schemas/login/success.json"; @@ -44,7 +44,7 @@ void shouldAuthenticateSuccessfully() { @Nested @DisplayName("Failed login scenarios") - public class FailedLogin { + class FailedLogin { private static final String LOGIN_UNAUTHORIZED_SCHEMA = "schemas/login/unauthorized.json"; private static final String LOGIN_EMPTY_EMAIL_SCHEMA = "schemas/login/empty-email.json"; diff --git a/src/test/java/io/github/felseje/apitestautomation/testdata/LoginProvider.java b/src/test/java/io/github/felseje/apitestautomation/testdata/LoginProvider.java index 3ba0824..b550f63 100644 --- a/src/test/java/io/github/felseje/apitestautomation/testdata/LoginProvider.java +++ b/src/test/java/io/github/felseje/apitestautomation/testdata/LoginProvider.java @@ -9,21 +9,22 @@ public final class LoginProvider { private static final String VALID_EMAIL = "fulano@qa.com"; private static final String VALID_PASSWORD = "teste"; + private static final String UNKNOWN_EMAIL = "unauth@mail.com"; + private static final String ANY_PASSWORD = "p4ssw0rd"; public static LoginRequest getValidLoginRequest() { return new LoginRequest(VALID_EMAIL, VALID_PASSWORD); } public static LoginRequest getLoginRequestWithUnauthorizedCredentials() { - return new LoginRequest("unauth@mail.com", "p4ssw0rd"); + return new LoginRequest(UNKNOWN_EMAIL, ANY_PASSWORD); } public static LoginRequest getLoginRequestWithEmptyEmail() { - return new LoginRequest("", "p4ssw0rd"); + return new LoginRequest("", VALID_PASSWORD); } public static LoginRequest getLoginRequestWithEmptyPassword() { - return new LoginRequest("rTyxUuv@qa.com", ""); + return new LoginRequest(VALID_EMAIL, ""); } - } diff --git a/src/test/resources/schemas/user/create-user-empty-body.json b/src/test/resources/schemas/user/create-user-empty-body.json index a022acc..901ef8d 100644 --- a/src/test/resources/schemas/user/create-user-empty-body.json +++ b/src/test/resources/schemas/user/create-user-empty-body.json @@ -1,6 +1,28 @@ { - "nome": "nome é obrigatório", - "email": "email é obrigatório", - "password": "password é obrigatório", - "administrador": "administrador é obrigatório" + "type": "object", + "properties": { + "nome": { + "type": "string", + "const": "nome é obrigatório" + }, + "email": { + "type": "string", + "const": "email é obrigatório" + }, + "password": { + "type": "string", + "const": "password é obrigatório" + }, + "administrador": { + "type": "string", + "const": "administrador é obrigatório" + } + }, + "required": [ + "nome", + "email", + "password", + "administrador" + ], + "additionalProperties": false }