Skip to content

Commit

Permalink
mock bodyPath() should return null not throw exceptions #1365
Browse files Browse the repository at this point in the history
  • Loading branch information
ptrthomas committed Nov 19, 2020
1 parent 4a9a365 commit 6ce22ce
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 3 deletions.
14 changes: 12 additions & 2 deletions karate-core/src/main/java/com/intuit/karate/core/MockHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -273,10 +273,20 @@ public Object bodyPath(String path) {
}
if (path.startsWith("/")) {
Variable v = ScenarioEngine.evalXmlPath(new Variable(body), path);
return JsValue.fromJava(v.getValue());
if (v.isNotPresent()) {
return null;
} else {
return JsValue.fromJava(v.getValue());
}
} else {
Json json = Json.of(body);
return JsValue.fromJava(json.get(path));
Object result;
try {
result = json.get(path);
} catch (Exception e) {
return null;
}
return JsValue.fromJava(result);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,10 @@ public Variable toLowerCase() {
}
}

public boolean isNotPresent() {
return "#notpresent".equals(value);
}

@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,11 +259,64 @@ void testJsVariableInBackground() {
background(
"def nextId = call read('increment.js')"
).scenario(
"pathMatches('/hello')", "def response = nextId()"
"pathMatches('/hello')",
"def response = nextId()"
);
request.path("/hello");
handle();
match(response.getBodyAsString(), "1");
}

@Test
void testJsonBodyPathThatExists() {
background().scenario(
"pathMatches('/hello')",
"def response = bodyPath('/root/foo')"
);
request.path("/hello")
.bodyJson("{ root: { foo: 'bar' } }");
handle();
match(response.getBodyAsString(), "bar");
}

@Test
void testJsonBodyPathThatDoesNotExist() {
background().scenario(
"pathMatches('/hello')",
"def result = bodyPath('root.nope')",
"def response = result == null ? 'NULL' : 'NOTNULL'"
);
request.path("/hello")
.bodyJson("{ root: { foo: 'bar' } }");
handle();
match(response.getBodyAsString(), "NULL");
}

@Test
void testXmlBodyPathThatExists() {
background().scenario(
"pathMatches('/hello')",
"def response = bodyPath('/root/foo')"
);
request.path("/hello")
.body("<root><foo>bar</foo></root>")
.contentType("application/xml");
handle();
match(response.getBodyAsString(), "bar");
}

@Test
void testXmlBodyPathThatDoesNotExist() {
background().scenario(
"pathMatches('/hello')",
"def result = bodyPath('/root/nope')",
"def response = result == null ? 'NULL' : 'NOTNULL'"
);
request.path("/hello")
.body("<root><foo>bar</foo></root>")
.contentType("application/xml");
handle();
match(response.getBodyAsString(), "NULL");
}

}

0 comments on commit 6ce22ce

Please sign in to comment.