Skip to content

Commit

Permalink
Merge pull request #577 from authorjapps/issue_568_typecast_fix
Browse files Browse the repository at this point in the history
PR - Issue 568 typecast fix for 1D array or list
  • Loading branch information
authorjapps authored Jun 5, 2023
2 parents 9472fb3 + 5dcf20d commit 7a82b9b
Show file tree
Hide file tree
Showing 7 changed files with 213 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
import static org.apache.commons.lang.StringUtils.substringBetween;
import static org.jsmart.zerocode.core.engine.tokens.ZeroCodeAssertionTokens.*;
import static org.jsmart.zerocode.core.engine.tokens.ZeroCodeValueTokens.$VALUE;
import static org.jsmart.zerocode.core.utils.FieldTypeConversionUtils.digTypeCast;
import static org.jsmart.zerocode.core.utils.FieldTypeConversionUtils.deepTypeCast;
import static org.jsmart.zerocode.core.utils.FieldTypeConversionUtils.fieldTypes;
import static org.jsmart.zerocode.core.utils.PropertiesProviderUtils.loadAbsoluteProperties;
import static org.jsmart.zerocode.core.utils.SmartUtils.isValidAbsolutePath;
Expand Down Expand Up @@ -392,7 +392,7 @@ private String resolveFieldTypes(String resolvedJson) {
}

Map<String, Object> fieldMap = mapper.readValue(resolvedJson, new TypeReference<Map<String, Object>>() { });
digTypeCast(fieldMap);
deepTypeCast(fieldMap);

return mapper.writeValueAsString(fieldMap);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

public class FieldTypeConversionUtils {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(FieldTypeConversionUtils.class);
private static ObjectMapper mapper = new ObjectMapperProvider().get();

public static final String INT = "(int)";
public static final String LONG = "(long)";
Expand Down Expand Up @@ -49,23 +48,24 @@ public class FieldTypeConversionUtils {
}
};

public static void digTypeCast(Map<String, Object> map) {
public static void deepTypeCast(Map<String, Object> map) {

map.entrySet().stream().forEach(entry -> {

Object value = entry.getValue();

if (value instanceof Map) {
digTypeCast((Map<String, Object>) value);
deepTypeCast((Map<String, Object>) value);

} else if (value instanceof ArrayList) {
((ArrayList) value).forEach(thisItem -> {
if (thisItem instanceof Map) {
digTypeCast((Map<String, Object>) thisItem);
for(int index = 0; index < ((ArrayList<?>) value).size(); index++){
Object thisItemValue = ((ArrayList<?>) value).get(index);
if (thisItemValue instanceof Map) {
deepTypeCast((Map<String, Object>) thisItemValue);
} else{
replacePrimitiveValues(((ArrayList) value), index, thisItemValue);
}
LOGGER.debug("ARRAY - Leaf node found = {}, checking for type value...", thisItem);
replaceNodeValue(entry, thisItem);
});
}
} else {
LOGGER.debug("Leaf node found = {}, checking for type value...", value);
replaceNodeValue(entry, value);
Expand All @@ -85,9 +85,24 @@ private static void replaceNodeValue(Map.Entry<String, Object> entry, Object thi
}
} catch (Exception exx) {
String errorMsg = "Can not convert '" + entry.getValue() + "'.";
LOGGER.error(errorMsg + "\nException Details:" + exx);
LOGGER.error("{} with exception details: {}", errorMsg, exx);
throw new RuntimeException(errorMsg + exx);
}
}

private static void replacePrimitiveValues(ArrayList<Object> valueList, Integer index, Object thisItem) {
try {
if (thisItem != null) {
fieldTypes.stream().forEach(currentType -> {
if (thisItem.toString().startsWith(currentType)) {
valueList.set(index, (typeMap.get(currentType)).apply(thisItem.toString()));
}
});
}
} catch (Exception exx) {
String errorMsg = "Can not convert '" + thisItem + "'.";
LOGGER.error(errorMsg + "\nException Details:" + exx);
throw new RuntimeException(errorMsg + exx);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,53 @@ public void willResolveJsonPathOfJayWayWith_SuppliedScenarioState() throws Excep
assertThat(resolvedSpecWithPaths, containsString("\"noOfAddresses\": \"2\""));
}

@Test
public void willResolveAndTypeCast_SingleDimentionArrayElements_FromScenarioState() throws Exception {
String specAsString =
smartUtils.getJsonDocumentAsString(
"unit_test_files/test_engine/02_2_resolve_typecast_in_single_dimention_arraylist_assertion.json");

final List<String> jsonPaths = jsonPreProcessor.getAllJsonPathTokens(specAsString);
assertThat(jsonPaths.size(), is(6));

String scenarioState =
"{\n"
+ " \"step1\": {\n"
+ " \"request\": {\n"
+ " \"body\": {\n"
+ " \"customer\": {\n"
+ "\"ids\": [\n" +
" 10101,\n" +
" 10102\n" +
" ],"
+ " \"firstName\": \"FIRST_NAME\",\n"
+ " \"staticName\": \"ANOTHER_NAME\",\n"
+ " \"addresses\":[\"office-1\", \"home-2\"]\n"
+ " }\n"
+ " }\n"
+ " },\n"
+ " \"response\": {\n"
+ " \"id\": 10101\n"
+ " }\n"
+ " }\n"
+ "}";
final String resolvedSpecWithPaths =
jsonPreProcessor.resolveStringJson(specAsString, scenarioState);
System.out.println("resolvedSpecWithPaths ==> " + resolvedSpecWithPaths);

Object jsonPathValue = JsonPath.read(resolvedSpecWithPaths,
"$.steps[1].request.body.Customer.accounts[0]");

assertThat(jsonPathValue.getClass().getName(), is("java.lang.String"));

assertThat(resolvedSpecWithPaths, containsString("\"staticName\":\"abcde\""));
assertThat(resolvedSpecWithPaths, containsString("\"firstName\":\"FIRST_NAME\""));
assertThat(resolvedSpecWithPaths, containsString("\"firstName2\":\"FIRST_NAME\""));
assertThat(resolvedSpecWithPaths, containsString("\"actualName\":\"ANOTHER_NAME\""));
assertThat(resolvedSpecWithPaths, containsString("\"noOfAddresses\":\"2\""));
assertThat(resolvedSpecWithPaths, containsString("\"accounts\":[\"10101\",\"10102\"]"));
}

@Test
public void willResolveJsonPathOfJayWayFor_AssertionSection() throws Exception {
ScenarioSpec scenarioSpec =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static org.jsmart.zerocode.core.utils.FieldTypeConversionUtils.digTypeCast;
import static org.jsmart.zerocode.core.utils.FieldTypeConversionUtils.deepTypeCast;
import static org.junit.Assert.assertEquals;

public class FieldTypeConversionUtilsTest {
Expand Down Expand Up @@ -53,6 +53,10 @@ public void testSubstituted_v4() throws IOException {
" \"line1\": \"address line1\",\n" +
" \"line2\": \"address line2\"\n" +
" }," +
" \"ids\": [\n" +
" \"(int)${$.results[0].id}\",\n" +
" \"(float)${$.results[1].id}\"\n" +
" ]," +
" \"results\": [\n" +
" {\n" +
" \"id\": \"(int)${$.results[0].id}\",\n" +
Expand Down Expand Up @@ -87,14 +91,17 @@ public void testSubstituted_v4() throws IOException {
Map<String, Object> stepMap = mapper.readValue(resolvedJson, new TypeReference<Map<String, Object>>() {
});

digTypeCast(stepMap);
deepTypeCast(stepMap);

JsonNode jsonNode = mapper.valueToTree(stepMap);

assertEquals(true, jsonNode.get("found").asBoolean());
assertEquals("{\"id\":2.35,\"name\":\"Bar - 2.35\",\"isActive\":false,\"longField\":1569683094000}",
jsonNode.get("results").get(1).toString());
assertEquals("address line1", jsonNode.get("currentAddress").get("line1").asText());
assertEquals(jsonNode.get("ids").get(0).asInt(), jsonNode.get("results").get(0).get("id").asInt());
assertEquals(1, jsonNode.get("ids").get(0).asInt() );
assertEquals(2.35F, Float.valueOf(jsonNode.get("ids").get(1).asText()), 0);
}

@Test
Expand Down Expand Up @@ -158,6 +165,6 @@ public void testSubstituted_incorrectTypeException() throws IOException {

expectedException.expectMessage("Can not convert '(int)false");
expectedException.expect(RuntimeException.class);
digTypeCast(stepMap);
deepTypeCast(stepMap);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,23 @@
"availability": "(boolean)${$.another_get_call.response.body.availability}"
}
}
},
{
"name": "assert_array_elements_1D_array",
"url": "http://localhost:9998/home/accounts/1",
"operation": "GET",
"request": {},
"assertions": {
"status": 200,
"body": {
"ids": [
"(int)${$.another_get_call.response.body.id}"
],
"name": "HBSC",
"current": true
}
}
}

]
}
15 changes: 15 additions & 0 deletions core/src/test/resources/simulators/test_purpose_end_points.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
{
"name": "Mock endpoints Simulator - API Stubs",
"apis": [
{
"name": "Get Bank Account by Id",
"operation": "GET",
"url": "/home/accounts/1",
"response": {
"status": 200,
"body": {
"ids": [
1
],
"name": "HBSC",
"current": true
}
}
},
{
"name": "Get Bathroom by Id",
"operation": "GET",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
{
"scenarioName": "see assertion section",
"loop": 5,
"steps": [
{
"name": "step1",
"loop": 3,
"url": "/persons/${STATIC.ALPHABET:3}",
"operation": "POST",
"request": {
"body": {
"customer": {
"ids": [
10101,
10102
],
"firstName": "FIRST_NAME",
"staticName": "${STATIC.ALPHABET:5}",
"addresses": [
"office-1",
"home-2"
]
}
}
},
"assertions": {
"status": 201,
"body": {
"id": 1001,
"actualName": "ACTUAL NAME",
"actualNameSize": 5
}
}
},
{
"name": "step2",
"loop": 3,
"url": "/persons/${STATIC.ALPHABET:3}",
"operation": "POST",
"request": {
"body": {
"Customer": {
"id": "(int)${$.step1.request.body.customer.ids[0]}",
"accounts": [
"${$.step1.request.body.customer.ids[0]}",
"${$.step1.request.body.customer.ids[1]}"
],
"firstName2": "${$.step1.request.body.customer.firstName}",
"nickName": "${RANDOM.NUMBER}",
"noOfAddresses": "${$.step1.request.body.customer.addresses.length()}"
}
}
},
"assertions": {
"status": 201,
"status": "$GT.499", //<-- cant have presence more thna once, as jackson only reads the latest value ie "$LT.199"
"absentField": "$GT.388",
//"status": "$LT.199", //<-- cant have presence more thna once, as jackson only reads the latest value ie "$LT.199"
"body": {
"id": "$NOT.NULL",
"salary": "$LT.1300",
"actualName": "${$.step1.request.body.customer.staticName}",
"addresses.SIZE": 5,
"job": {
"rate": 700,
"type": "contract"
},
"allNames": [
"Rose, Call me by Any Name would Smell Sweet",
{
"firstName": "R Payal",
"when": "Initiation",
"citizenship": [
{
"country": "Italy"
},
{
"country": "Noorway"
}
],
"citizenship": "$[]",
"citizenship.SIZE": 4,
"personalities": "$[]",
"pastActivities": "$[]"

},
{
"firstName": "$CONTAINS.STRING:DaddyWithMac",
"when": "$NULL"
}
]
}
}
}
]
}

0 comments on commit 7a82b9b

Please sign in to comment.