Skip to content

Commit

Permalink
Format request/response JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
bpross-52n committed Dec 7, 2023
1 parent 0f014f2 commit 684cf27
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -505,10 +505,13 @@ public void addAttributesOnTestFailure(ITestResult result) {
} else if(rspEntity instanceof String) {
response = response.append((String)rspEntity);
}
String responseString = JsonUtils.prettifyString(response.toString());
if (response.length() > MAX_RSP_ATTR_LENGTH) {
response = new StringBuilder();
response.append(responseString);
response.delete(MAX_RSP_ATTR_LENGTH, response.length());
}
result.setAttribute(RSP_ATTR, response.toString());
result.setAttribute(RSP_ATTR, responseString);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@

import org.apache.commons.io.IOUtils;

import com.fasterxml.jackson.databind.ObjectMapper;

import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
Expand All @@ -31,6 +33,8 @@
*/
public class JsonUtils {

private static ObjectMapper objectMapper;

private JsonUtils() {
}

Expand Down Expand Up @@ -346,7 +350,26 @@ public static String inputStreamToString(InputStream inputStream) throws IOExcep
StringWriter writer = new StringWriter();
String encoding = StandardCharsets.UTF_8.name();
IOUtils.copy(inputStream, writer, encoding);
return writer.toString();
return prettifyString(writer.toString());
}

public static String prettifyString(String string) {
ObjectMapper objectMapper = getObjectMapper();
try {
Object jsonObject = objectMapper.readValue(string, Object.class);
String prettyJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
return prettyJson;
} catch (Exception e) {
//String was not JSON
return string;
}
}

private static ObjectMapper getObjectMapper() {
if(objectMapper == null) {
objectMapper = new ObjectMapper();
}
return objectMapper;
}

private static boolean isSameMediaType( String mediaType1, String mediaType2 ) {
Expand Down

0 comments on commit 684cf27

Please sign in to comment.