Skip to content

Commit

Permalink
added a fix for bug which trims whitespace from xml elements when use…
Browse files Browse the repository at this point in the history
…d with print or karate.log
  • Loading branch information
Bharath G R committed Oct 10, 2023
1 parent 0d49e81 commit 42936ee
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 3 deletions.
7 changes: 5 additions & 2 deletions karate-core/src/main/java/com/intuit/karate/XmlUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,13 @@ public static String toString(Node node) {
}

public static String toString(Node node, boolean pretty) {
Node nodeToSerialize = node;
// In case of pretty string, we clone the node so that we don't modify the original node while trimming whitespaces
if (pretty) {
trimWhiteSpace(node);
nodeToSerialize = node.cloneNode(true);
trimWhiteSpace(nodeToSerialize);
}
DOMSource domSource = new DOMSource(node);
DOMSource domSource = new DOMSource(nodeToSerialize);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Expand Down
17 changes: 17 additions & 0 deletions karate-core/src/test/java/com/intuit/karate/XmlUtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,23 @@ void testPrettyPrint() {
assertEquals(temp, expected);
}

@Test
void testPrettyPrintWithWhiteSpace() {
String xml = "<foo><bar>baz</bar><ban><goo>moo </goo></ban></foo>";
Document doc = XmlUtils.toXmlDoc(xml);
String temp = XmlUtils.toString(doc, true);
String expected
= "<foo>\n"
+ " <bar>baz</bar>\n"
+ " <ban>\n"
+ " <goo>moo</goo>\n"
+ " </ban>\n"
+ "</foo>\n";

expected = expected.replace("\n", System.lineSeparator());
assertEquals(temp, expected);
}

@Test
void testCreatingNewDocumentFromSomeChildNode() {
String xml = "<root><foo><bar>baz</bar></foo></root>";
Expand Down
24 changes: 23 additions & 1 deletion karate-core/src/test/java/com/intuit/karate/core/xml/xml.feature
Original file line number Diff line number Diff line change
Expand Up @@ -504,4 +504,26 @@ Scenario: xml matching involving karate-schema substitutions
<a>x</a>
</root>
"""
* match test2 == schema
* match test2 == schema

Scenario: Xml whitespace trim after print bug fix
* def setForecastRequestXml =
"""
<myroot>
<myelement>T </myelement>
</myroot>
"""
* match setForecastRequestXml //myelement == 'T '
* print setForecastRequestXml
* match setForecastRequestXml //myelement == 'T '

Scenario: Xml whitespace trim after karate.log bug fix
* def setForecastRequestXml =
"""
<myroot>
<myelement> T </myelement>
</myroot>
"""
* match setForecastRequestXml //myelement == ' T '
* karate.log(setForecastRequestXml)
* match setForecastRequestXml //myelement == ' T '

0 comments on commit 42936ee

Please sign in to comment.