horizon-test: Base API layers & Test Cases implementation.

main
abdullah.masood 2025-11-26 21:37:10 +05:00
parent a08867560c
commit 823c84c95d
11 changed files with 342 additions and 31 deletions

22
.gitignore vendored
View File

@ -12,27 +12,5 @@ target/
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

15
pom.xml
View File

@ -20,6 +20,7 @@
<extent.reports.versions>5.1.2</extent.reports.versions>
<slf4j.version>2.0.13</slf4j.version>
<logback.version>1.5.6</logback.version>
<restassured.version>5.5.6</restassured.version>
</properties>
<dependencies>
@ -112,6 +113,20 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>${restassured.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hamcrest/hamcrest -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,90 @@
package com.utopiadeals.api;
import com.google.gson.JsonObject;
import io.restassured.RestAssured;
import io.restassured.filter.log.LogDetail;
import io.restassured.response.Response;
import io.restassured.response.ResponseBody;
import io.restassured.specification.RequestSpecification;
public class RestWebCall {
private RequestSpecification requestSpec;
private String bearerToken;
public RestWebCall(String baseURL, String email, String password) {
RestAssured.urlEncodingEnabled = true;
RestAssured.baseURI = baseURL;
requestSpec = RestAssured.given();
requestSpec.header("Content-Type", "application/json");
this.bearerToken = authorize(email, password);
requestSpec.header("Authorization", "Bearer " + bearerToken);
}
public RestWebCall(String baseURL) {
RestAssured.urlEncodingEnabled = true;
RestAssured.baseURI = baseURL;
requestSpec = RestAssured.given();
requestSpec.header("Content-Type", "application/json");
}
private String authorize(String email, String password) {
// Attempt 1: JSON with {email,password}
JsonObject jsonEmail = new JsonObject();
jsonEmail.addProperty("email", email);
jsonEmail.addProperty("password", password);
Response res = RestAssured
.given()
.relaxedHTTPSValidation()
.contentType("application/json")
.log().ifValidationFails(LogDetail.ALL)
.body(jsonEmail.toString())
.post("/api/auth/login");
int status = res.getStatusCode();
if (status == 200) {
ResponseBody body = res.getBody();
String authToken = body.jsonPath().get("accessToken").toString();
if (authToken == null || authToken.isEmpty()) {
throw new RuntimeException("Login succeeded but token not found. Response: " + body.asString());
}
return authToken;
}
throw new RuntimeException("Login failed. Unable to extract Access Token");
}
public Response get(String endPoint) {
return requestSpec.get(endPoint);
}
public Response get(String endPoint, String queryParam, String queryParamValue) {
return requestSpec.queryParam(queryParam, queryParamValue).get(endPoint);
}
public Response post(String endPoint, String payLoad) {
requestSpec.body(payLoad);
return requestSpec.post(endPoint);
}
public Response post(String endPoint, String payLoad, String parameterName, String parameterValue) {
requestSpec.body(payLoad);
return requestSpec.pathParams(parameterName, parameterValue).post(endPoint);
}
public Response put(String endPoint, String payLoad) {
requestSpec.body(payLoad);
return requestSpec.put(endPoint);
}
public Response delete(String endPoint) {
return requestSpec.delete(endPoint);
}
public String getBearerToken() {
return bearerToken;
}
}

View File

@ -49,8 +49,8 @@ public class ExtentReportExtension implements BeforeAllCallback, AfterAllCallbac
@Override
public void beforeEach(ExtensionContext context) throws Exception {
String testName = context.getDisplayName();
String className = context.getTestClass().map(Class::getSimpleName).orElse("Unknown");
String testName = context.getTestMethod().map(m -> m.getName()).orElse("Unknown Test");
ExtentTest extentTest = extent.createTest(testName)
.assignCategory(className);

View File

@ -22,5 +22,17 @@ public class Constants {
public static String getTestDataPath() {
return props.getString("test.data.path");
}
public static String getApiBaseUrl() {
return props.getString("api.base.url");
}
public static String getApiTestUserName(){
return props.getString("api.test.username");
}
public static String getApiTestPassword(){
return props.getString("api.test.password");
}
}

View File

@ -0,0 +1,75 @@
package apitestsuites;
import com.utopiadeals.api.RestWebCall;
import com.utopiadeals.utils.config.Constants;
import io.restassured.response.Response;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
@Tag("access-mgmt-api")
public class AccessManagementApiTest {
private static final String BASE_URL = Constants.getApiBaseUrl();
private static final String USERS_ENDPOINT = "/api/access-management/users";
private RestWebCall apiClient;
private static String emailId = "";
private static Integer userId;
@Test
public void addUser_WithValidData_ShouldReturnSuccess() {
// Arrange
apiClient = new RestWebCall(BASE_URL, Constants.getApiTestUserName(), Constants.getApiTestPassword());
emailId = "new.user+" + System.currentTimeMillis() + "@example.com";
String requestBody = """
{
"email": "%s",
"firstName": "Test",
"lastName": "User0081",
"enabled": true,
"roles": [
0
],
"permissions": [
0
]
}
""".formatted(emailId);
/*End Point for Add / update user is same. To add user the API expects user id as 0.*/
// Act
Response response = apiClient.post(USERS_ENDPOINT + "/0", requestBody);
// Assert
assertThat(response.getStatusCode(), is(200));
assertThat(response.getBody().asString(), equalTo("success"));
}
@Test
public void getUsers_WithValidEmailId_ShouldReturnSuccess() {
// Act
apiClient = new RestWebCall(BASE_URL, Constants.getApiTestUserName(), Constants.getApiTestPassword());
Response response = apiClient.get(USERS_ENDPOINT, "size", "100");
assertThat(response.getStatusCode(), is(200));
List<String> emails = response.jsonPath().getList("data.email");
assertThat(emails, hasItem(emailId));
userId = response.jsonPath().getInt("data.find { it.email == '" + emailId + "' }.id");
assertThat(userId, notNullValue());
}
@Test
public void getUsers_WithValidId_ShouldReturnSuccess() {
// Act
apiClient = new RestWebCall(BASE_URL, Constants.getApiTestUserName(), Constants.getApiTestPassword());
Response response = apiClient.get(USERS_ENDPOINT + "/" + userId);
assertThat(response.getStatusCode(), is(200));
int actualUserId = response.jsonPath().getInt("user.id");
assertThat(userId, equalTo(actualUserId));
}
}

View File

@ -0,0 +1,79 @@
package apitestsuites;
import com.utopiadeals.api.RestWebCall;
import com.utopiadeals.framework.annotations.JsonTestDataExtension;
import com.utopiadeals.utils.TestDataProvider;
import com.utopiadeals.utils.config.Constants;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
@Tag("auth-api")
public class UserAuthenticationApiTest {
private static final String BASE_URL = Constants.getApiBaseUrl();
private static final String REGISTER_ENDPOINT = "/api/auth/register";
private static RestWebCall apiClient;
@BeforeAll
public static void setUp() {
// Initialize API client (without auth for registration)
apiClient = new RestWebCall(BASE_URL);
}
@Test
public void registerUser_WithValidData_ShouldReturnSuccess() {
// Arrange
String requestBody = """
{
"email": "test.user+%d@example.com",
"password": "ValidPass123!",
"firstName": "Test",
"lastName": "User",
"fullName": "Test User"
}
""".formatted(System.currentTimeMillis());
// Act
Response response = apiClient.post(REGISTER_ENDPOINT, requestBody);
// Assert
assertThat(response.getStatusCode(), is(200));
assertThat(response.jsonPath().getString("message"), equalTo("User registered successfully"));
}
@ParameterizedTest()
@JsonTestDataExtension("dataSet-0,dataSet-1,dataSet-2,dataSet-3,dataSet-4")
public void registerUser_WithInvalidData_ShouldReturnError(TestDataProvider testDataProvider) {
String testName = testDataProvider.getString("testName");
String expectedStatus = testDataProvider.getString("expectedStatus");
String expectedError = testDataProvider.getString("expectedError");
String requestBody = """
{
"email": "%s",
"password": "%s",
"firstName": "%s",
"lastName": "%s",
"fullName": "%s"
}
""".formatted(
testDataProvider.getString("email"),
testDataProvider.getString("password"),
testDataProvider.getString("firstName"),
testDataProvider.getString("lastName"),
testDataProvider.getString("fullName")
);
// Act
Response response = apiClient.post(REGISTER_ENDPOINT, requestBody);
// Assert
assertThat(testName, response.getStatusCode(), is(expectedStatus));
assertThat(testName, response.jsonPath().getString("error"), containsString(expectedError));
}
}

View File

@ -1,11 +1,10 @@
package testsuites;
package webtestsuites;
import com.utopiadeals.framework.annotations.JsonTestDataExtension;
import com.utopiadeals.utils.TestDataProvider;
import com.utopiadeals.web.pages.LoginPage;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
public class LoginTest extends WebTestSuiteBase{

View File

@ -1,4 +1,4 @@
package testsuites;
package webtestsuites;
import com.microsoft.playwright.Page;
import com.utopiadeals.framework.BrowserContextManager;

View File

@ -8,10 +8,11 @@ env.url=${seller.cosmos.url}
#${env.browser}
#
base.url=https://sellerboard.com
api.base.url=https://api.sellerboard.com
# API Tests
api.base.url=https://cosmos-api.utopiadeals.com
api.test.username=utest@utopiadeals.com
api.test.password=utest001
# Browser Configuration
browser.name=chrome

View File

@ -8,7 +8,69 @@
},
"dataSet-1": {
"username": "abdullah@utopiadeals.com",
"password": "Utopia01"
"password": "Utopia)!"
}
}
},
"registerUser_WithValidData_ShouldReturnSuccess": {
"dataSets": {
"dataSet-0": {
"email": "test.user@example.com",
"password": "ValidPass123!",
"firstName": "Test",
"lastName": "User",
"fullName": "Test User"
}
}
},
"registerUser_WithInvalidData_ShouldReturnError": {
"dataSets": {
"dataSet-0": {
"testName": "Invalid email format",
"email": "invalid-email",
"password": "ValidPass123!",
"firstName": "Test",
"lastName": "User",
"fullName": "Test User",
"expectedStatus": "400",
"expectedError": "Invalid email format"
},
"dataSet-1": {
"testName": "Missing email",
"password": "ValidPass123!",
"firstName": "Test",
"lastName": "User",
"fullName": "Test User",
"expectedStatus": "400",
"expectedError": "Email is required"
},
"dataSet-2": {
"testName": "Weak password",
"email": "test.user@example.com",
"password": "weak",
"firstName": "Test",
"lastName": "User",
"fullName": "Test User",
"expectedStatus": "400",
"expectedError": "Password must be at least 8 characters"
},
"dataSet-3": {
"testName": "Missing first name",
"email": "test.user@example.com",
"password": "ValidPass123!",
"lastName": "User",
"fullName": "Test User",
"expectedStatus": "400",
"expectedError": "First name is required"
},
"dataSet-4": {
"testName": "Missing last name",
"email": "test.user@example.com",
"password": "ValidPass123!",
"firstName": "Test",
"fullName": "Test User",
"expectedStatus": "400",
"expectedError": "Last name is required"
}
}
}