Skip to content

Commit

Permalink
Fix: Ensure query parameters are added to requests with a body (#1634)
Browse files Browse the repository at this point in the history
* Fix: Ensure query parameters are added to requests with a body

* test file

* deleted @test from testPostRequest.java

* Fix: Ensure query parameters are added to requests with a body

---------

Co-authored-by: Kyrillos Nageh Abdelnour Flamon <kyrillosnageh@3ddx.com>
  • Loading branch information
KyrillosNageh and Kyrillos Nageh Abdelnour Flamon authored Jun 10, 2024
1 parent 3c6b582 commit 1178c36
Show file tree
Hide file tree
Showing 2 changed files with 124 additions and 34 deletions.
116 changes: 82 additions & 34 deletions src/main/java/com/shaft/api/RequestBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -264,49 +264,97 @@ public Response perform() {
*/
@Step("Perform {this.requestType} request to {this.serviceURI}{this.serviceName}")
public Response performRequest() {
String request = session.prepareRequestURL(serviceURI, urlArguments, serviceName);
RequestSpecification specs = session.prepareRequestSpecs(parameters, parametersType, requestBody, contentType, sessionCookies, sessionHeaders, sessionConfig, appendDefaultContentCharsetToContentTypeIfUndefined, urlEncodingEnabled);
String request = prepareRequestURLWithParameters();
RequestSpecification specs = prepareRequestSpecifications();

switch (this.authenticationType) {
case BASIC -> specs.auth().preemptive().basic(this.authenticationUsername, this.authenticationPassword);
case FORM -> specs.auth().form(this.authenticationUsername, this.authenticationPassword);
case NONE -> {
} //do nothing
}
setupAuthentication(specs);

Response response = null;
try {
if (requestType.equals(RestActions.RequestType.POST) || requestType.equals(RestActions.RequestType.PATCH)
|| requestType.equals(RestActions.RequestType.PUT) || requestType.equals(RestActions.RequestType.GET)
|| requestType.equals(RestActions.RequestType.DELETE)) {
response = session.sendRequest(requestType, request, specs);
} else {
RestActions.failAction(request);
}

boolean responseStatus = session.evaluateResponseStatusCode(Objects.requireNonNull(response), targetStatusCode);
String reportMessage = session.prepareReportMessage(response, targetStatusCode, requestType, serviceName,
contentType, urlArguments);
if (!Boolean.TRUE.equals(responseStatus)) {
RestActions.failAction(reportMessage, requestBody, specs, response, new AssertionError("Invalid response status code; Expected " + targetStatusCode + " but found " + response.getStatusCode() + "."));
}
if (!"".equals(reportMessage)) {
RestActions.passAction(reportMessage, requestBody, specs, response);
} else {
RestActions.failAction(reportMessage, requestBody, specs, response);
}
} catch (Exception rootCauseException) {
if (response != null) {
RestActions.failAction(request + ", Response Time: " + response.timeIn(TimeUnit.MILLISECONDS) + "ms", requestBody, specs,
response, rootCauseException);
} else {
RestActions.failAction(request, rootCauseException);
}
response = sendRequest(request, specs);
handleResponse(response, specs);
} catch (Exception e) {
handleException(request, specs, response, e);
}

session.setLastResponse(response);
return response;
}

private String prepareRequestURLWithParameters() {
String request = session.prepareRequestURL(serviceURI, urlArguments, serviceName);
if (parameters != null && parametersType == RestActions.ParametersType.QUERY) {
request = addParametersToUrl(request, parameters);
}
return request;
}

private RequestSpecification prepareRequestSpecifications() {
return session.prepareRequestSpecs(parameters, parametersType, requestBody, contentType, sessionCookies, sessionHeaders, sessionConfig, appendDefaultContentCharsetToContentTypeIfUndefined, urlEncodingEnabled);
}

private void setupAuthentication(RequestSpecification specs) {
switch (authenticationType) {
case BASIC -> specs.auth().preemptive().basic(authenticationUsername, authenticationPassword);
case FORM -> specs.auth().form(authenticationUsername, authenticationPassword);
case NONE -> {
} // Do nothing
}
}

private Response sendRequest(String request, RequestSpecification specs) {
if (!isSupportedRequestType()) {
RestActions.failAction(request, new Throwable[0]);
return null;
}
return session.sendRequest(requestType, request, specs);
}

private void handleResponse(Response response, RequestSpecification specs) {
boolean responseStatus = session.evaluateResponseStatusCode(Objects.requireNonNull(response), targetStatusCode);
String reportMessage = session.prepareReportMessage(response, targetStatusCode, requestType, serviceName, contentType, urlArguments);
if (!Boolean.TRUE.equals(responseStatus)) {
throw new AssertionError("Invalid response status code; Expected " + targetStatusCode + " but found " + response.getStatusCode() + ".");
}

if (!reportMessage.isEmpty()) {
RestActions.passAction(reportMessage, requestBody, specs, response);
} else {
RestActions.failAction(reportMessage, requestBody, specs, response, new Throwable[0]);
}
}

private void handleException(String request, RequestSpecification specs, Response response, Exception e) {
if (response != null) {
RestActions.failAction(request + ", Response Time: " + response.timeIn(TimeUnit.MILLISECONDS) + "ms", requestBody, specs, response, new Throwable[]{e});
} else {
RestActions.failAction(request, new Throwable[]{e});
}
}

private boolean isSupportedRequestType() {
return requestType == RestActions.RequestType.POST ||
requestType == RestActions.RequestType.PATCH ||
requestType == RestActions.RequestType.PUT ||
requestType == RestActions.RequestType.GET ||
requestType == RestActions.RequestType.DELETE;
}

private String addParametersToUrl(String url, List<List<Object>> parameters) {
StringBuilder urlWithParams = new StringBuilder(url);
if (!url.contains("?")) {
urlWithParams.append("?");
} else {
urlWithParams.append("&");
}
for (List<Object> param : parameters) {
urlWithParams.append(param.get(0)).append("=").append(param.get(1)).append("&");
}
// Remove the last '&'
urlWithParams.setLength(urlWithParams.length() - 1);
return urlWithParams.toString();
}

/**
* The type of your authentication method {BASIC, FORM, NONE}
*/
Expand Down
42 changes: 42 additions & 0 deletions src/test/java/com/shaft/api/testPostRequest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.shaft.api;

import com.shaft.api.RestActions;
import com.shaft.driver.SHAFT;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.Arrays;
import java.util.List;

public class testPostRequest {
SHAFT.API api = new SHAFT.API("http://localhost:5000");
String body = """
{
"title": "New Course 1",
"description": "Full description of the new course in Arabic"
}
""";
List<List<Object>> parameters = Arrays.asList(Arrays.asList("access_key", "your-access-key"));

// @Test
public void PostRequest(){

api.post("/courses")
.setRequestBody(body)
.setParameters(parameters, RestActions.ParametersType.QUERY)
.setContentType("application/json")
.perform();

/*
api.get("/courses")
.setParameters(parameters, RestActions.ParametersType.QUERY)
.setContentType("application/json")
.perform();
*/
String body = api.getResponseBody();
int st =api.getResponse().statusCode();
Assert.assertEquals(st,201);

SHAFT.Report.log(">>>>>>>>>>>>> Test result" +body);
}
}

0 comments on commit 1178c36

Please sign in to comment.