From: <bo...@us...> - 2007-02-02 21:36:25
|
Revision: 146 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=146&view=rev Author: bodewig Date: 2007-02-02 13:36:23 -0800 (Fri, 02 Feb 2007) Log Message: ----------- Move MultiLevelElementNameAndTextQualifier to examples package Added Paths: ----------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/examples/MultiLevelElementNameAndTextQualifier.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/examples/test_MultiLevelElementNameAndTextQualifier.java Removed Paths: ------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/MultiLevelElementNameAndTextQualifier.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_MultiLevelElementNameAndTextQualifier.java Deleted: trunk/xmlunit/src/java/org/custommonkey/xmlunit/MultiLevelElementNameAndTextQualifier.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/MultiLevelElementNameAndTextQualifier.java 2007-02-02 20:44:21 UTC (rev 145) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/MultiLevelElementNameAndTextQualifier.java 2007-02-02 21:36:23 UTC (rev 146) @@ -1,117 +0,0 @@ -/* -****************************************************************** -Copyright (c) 2001, Jeff Martin, Tim Bacon -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - * Neither the name of the xmlunit.sourceforge.net nor the names - of its contributors may be used to endorse or promote products - derived from this software without specific prior written - permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. - -****************************************************************** -*/ - -package org.custommonkey.xmlunit; - -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.Text; - -/** - * Per popular request an interface implementation that uses element - * names and the text node containes in the n'th child node to compare - * elements. - * - * <p>This means {@link ElementNameAndTextQualifier - * ElementNameQualifier} and MultiLevelElementNameQualifier(1) should - * lead to the same results.</p> - * - * <p>Any attribute values ar completely ignored. Only works on - * elements with exactly one child element at each level.</p> - * - * <p>This class mostly exists as an example for custom ElementQualifiers.</p> - */ -public class MultiLevelElementNameAndTextQualifier - implements ElementQualifier { - - private final int levels; - - private static final ElementNameQualifier NAME_QUALIFIER = - new ElementNameQualifier(); - private static final ElementNameAndTextQualifier NAME_AND_TEXT_QUALIFIER = - new ElementNameAndTextQualifier(); - - /** - * Uses element names and the text nested <code>levels</code> - * child elements deeper into the element to compare elements. - */ - public MultiLevelElementNameAndTextQualifier(int levels) { - if (levels < 1) { - throw new IllegalArgumentException("levels must be equal or" - + " greater than one"); - } - this.levels = levels; - } - - public boolean qualifyForComparison(Element control, Element test) { - boolean stillSimilar = true; - Element currentControl = control; - Element currentTest = test; - - // match on element names only for leading levels - for (int currentLevel = 0; stillSimilar && currentLevel <= levels - 2; - currentLevel++) { - stillSimilar = NAME_QUALIFIER.qualifyForComparison(currentControl, - currentTest); - if (stillSimilar) { - if (currentControl.hasChildNodes() - && currentTest.hasChildNodes()) { - Node n1 = currentControl.getFirstChild(); - Node n2 = currentTest.getFirstChild(); - if (n1.getNodeType() == Node.ELEMENT_NODE - && n2.getNodeType() == Node.ELEMENT_NODE) { - currentControl = (Element) n1; - currentTest = (Element) n2; - } else { - stillSimilar = false; - } - } else { - stillSimilar = false; - } - } - } - - // finally compare the level containing the text child node - if (stillSimilar) { - stillSimilar = NAME_AND_TEXT_QUALIFIER - .qualifyForComparison(currentControl, currentTest); - } - - return stillSimilar; - } - -} Copied: trunk/xmlunit/src/java/org/custommonkey/xmlunit/examples/MultiLevelElementNameAndTextQualifier.java (from rev 144, trunk/xmlunit/src/java/org/custommonkey/xmlunit/MultiLevelElementNameAndTextQualifier.java) =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/examples/MultiLevelElementNameAndTextQualifier.java (rev 0) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/examples/MultiLevelElementNameAndTextQualifier.java 2007-02-02 21:36:23 UTC (rev 146) @@ -0,0 +1,121 @@ +/* +****************************************************************** +Copyright (c) 2001, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit.examples; + +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.Text; + +import org.custommonkey.xmlunit.ElementNameAndTextQualifier; +import org.custommonkey.xmlunit.ElementNameQualifier; +import org.custommonkey.xmlunit.ElementQualifier; + +/** + * Per popular request an interface implementation that uses element + * names and the text node containes in the n'th child node to compare + * elements. + * + * <p>This means {@link ElementNameAndTextQualifier + * ElementNameQualifier} and MultiLevelElementNameQualifier(1) should + * lead to the same results.</p> + * + * <p>Any attribute values ar completely ignored. Only works on + * elements with exactly one child element at each level.</p> + * + * <p>This class mostly exists as an example for custom ElementQualifiers.</p> + */ +public class MultiLevelElementNameAndTextQualifier + implements ElementQualifier { + + private final int levels; + + private static final ElementNameQualifier NAME_QUALIFIER = + new ElementNameQualifier(); + private static final ElementNameAndTextQualifier NAME_AND_TEXT_QUALIFIER = + new ElementNameAndTextQualifier(); + + /** + * Uses element names and the text nested <code>levels</code> + * child elements deeper into the element to compare elements. + */ + public MultiLevelElementNameAndTextQualifier(int levels) { + if (levels < 1) { + throw new IllegalArgumentException("levels must be equal or" + + " greater than one"); + } + this.levels = levels; + } + + public boolean qualifyForComparison(Element control, Element test) { + boolean stillSimilar = true; + Element currentControl = control; + Element currentTest = test; + + // match on element names only for leading levels + for (int currentLevel = 0; stillSimilar && currentLevel <= levels - 2; + currentLevel++) { + stillSimilar = NAME_QUALIFIER.qualifyForComparison(currentControl, + currentTest); + if (stillSimilar) { + if (currentControl.hasChildNodes() + && currentTest.hasChildNodes()) { + Node n1 = currentControl.getFirstChild(); + Node n2 = currentTest.getFirstChild(); + if (n1.getNodeType() == Node.ELEMENT_NODE + && n2.getNodeType() == Node.ELEMENT_NODE) { + currentControl = (Element) n1; + currentTest = (Element) n2; + } else { + stillSimilar = false; + } + } else { + stillSimilar = false; + } + } + } + + // finally compare the level containing the text child node + if (stillSimilar) { + stillSimilar = NAME_AND_TEXT_QUALIFIER + .qualifyForComparison(currentControl, currentTest); + } + + return stillSimilar; + } + +} Copied: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/examples/test_MultiLevelElementNameAndTextQualifier.java (from rev 144, trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_MultiLevelElementNameAndTextQualifier.java) =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/examples/test_MultiLevelElementNameAndTextQualifier.java (rev 0) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/examples/test_MultiLevelElementNameAndTextQualifier.java 2007-02-02 21:36:23 UTC (rev 146) @@ -0,0 +1,147 @@ +/* +****************************************************************** +Copyright (c) 2001, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit.examples; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.ElementNameAndTextQualifier; +import org.custommonkey.xmlunit.ElementQualifier; +import org.custommonkey.xmlunit.XMLUnit; + +/** + * JUnit testcase for MultiLevelElementNameAndTextQualifier + * @see test_Diff#testRepeatedElementNamesWithTextQualification() + */ +public class test_MultiLevelElementNameAndTextQualifier extends TestCase { + private static final String TAG_NAME = "tagYoureIt"; + private static final String TAG_NAME2 = "tagYoureIt2"; + private static final String TEXT_A = "textA"; + private static final String TEXT_B = "textB"; + private Document document; + + // copy of ElementNameAndTextQualifier test + public void testSingleTextValue() throws Exception { + ElementQualifier qualifier = + new MultiLevelElementNameAndTextQualifier(1); + + Element control = document.createElement(TAG_NAME); + control.appendChild(document.createTextNode(TEXT_A)); + + Element test = document.createElement(TAG_NAME); + + assertFalse("control text not comparable to empty text", + qualifier.qualifyForComparison(control, test)); + + test.appendChild(document.createTextNode(TEXT_A)); + assertTrue("control textA comparable to test textA", + qualifier.qualifyForComparison(control, test)); + + test = document.createElement(TAG_NAME); + + test.appendChild(document.createTextNode(TEXT_B)); + assertFalse("control textA not comparable to test textB", + qualifier.qualifyForComparison(control, test)); + } + + // copy of ElementNameAndTextQualifier test + public void testMultipleTextValues() throws Exception { + ElementQualifier qualifier = + new MultiLevelElementNameAndTextQualifier(1); + + Element control = document.createElement(TAG_NAME); + control.appendChild(document.createTextNode(TEXT_A)); + control.appendChild(document.createTextNode(TEXT_B)); + + Element test = document.createElement(TAG_NAME); + test.appendChild(document.createTextNode(TEXT_A + TEXT_B)); + assertTrue("denormalised control text comparable to normalised test text", + qualifier.qualifyForComparison(control, test)); + } + + // three levels + public void testThreeLevels() throws Exception { + ElementQualifier qualifier = + new MultiLevelElementNameAndTextQualifier(3); + + Element control = document.createElement(TAG_NAME); + Element child = document.createElement(TAG_NAME2); + control.appendChild(child); + Element child2 = document.createElement(TAG_NAME); + child.appendChild(child2); + child2.appendChild(document.createTextNode(TEXT_B)); + + Element test = document.createElement(TAG_NAME); + child = document.createElement(TAG_NAME2); + test.appendChild(child); + child2 = document.createElement(TAG_NAME); + child.appendChild(child2); + child2.appendChild(document.createTextNode(TEXT_B)); + + assertTrue(qualifier.qualifyForComparison(control, test)); + } + + /** + * @see https://sourceforge.net/forum/forum.php?thread_id=1440169&forum_id=73274 + */ + public void testThread1440169() throws Exception { + String s1 = "<a><b><c>foo</c></b><b><c>bar</c></b></a>"; + String s2 = "<a><b><c>bar</c></b><b><c>foo</c></b></a>"; + Diff d = new Diff(s1, s2); + assertFalse(d.similar()); + + // reset + d = new Diff(s1, s2); + d.overrideElementQualifier(new ElementNameAndTextQualifier()); + assertFalse(d.similar()); + + // reset once again + d = new Diff(s1, s2); + d.overrideElementQualifier(new MultiLevelElementNameAndTextQualifier(2)); + assertTrue(d.similar()); + + } + + public void setUp() throws Exception { + document = XMLUnit.newControlParser().newDocument(); + } + +} Deleted: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_MultiLevelElementNameAndTextQualifier.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_MultiLevelElementNameAndTextQualifier.java 2007-02-02 20:44:21 UTC (rev 145) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_MultiLevelElementNameAndTextQualifier.java 2007-02-02 21:36:23 UTC (rev 146) @@ -1,142 +0,0 @@ -/* -****************************************************************** -Copyright (c) 2001, Jeff Martin, Tim Bacon -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - * Neither the name of the xmlunit.sourceforge.net nor the names - of its contributors may be used to endorse or promote products - derived from this software without specific prior written - permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. - -****************************************************************** -*/ - -package org.custommonkey.xmlunit; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * JUnit testcase for MultiLevelElementNameAndTextQualifier - * @see test_Diff#testRepeatedElementNamesWithTextQualification() - */ -public class test_MultiLevelElementNameAndTextQualifier extends TestCase { - private static final String TAG_NAME = "tagYoureIt"; - private static final String TAG_NAME2 = "tagYoureIt2"; - private static final String TEXT_A = "textA"; - private static final String TEXT_B = "textB"; - private Document document; - - // copy of ElementNameAndTextQualifier test - public void testSingleTextValue() throws Exception { - ElementQualifier qualifier = - new MultiLevelElementNameAndTextQualifier(1); - - Element control = document.createElement(TAG_NAME); - control.appendChild(document.createTextNode(TEXT_A)); - - Element test = document.createElement(TAG_NAME); - - assertFalse("control text not comparable to empty text", - qualifier.qualifyForComparison(control, test)); - - test.appendChild(document.createTextNode(TEXT_A)); - assertTrue("control textA comparable to test textA", - qualifier.qualifyForComparison(control, test)); - - test = document.createElement(TAG_NAME); - - test.appendChild(document.createTextNode(TEXT_B)); - assertFalse("control textA not comparable to test textB", - qualifier.qualifyForComparison(control, test)); - } - - // copy of ElementNameAndTextQualifier test - public void testMultipleTextValues() throws Exception { - ElementQualifier qualifier = - new MultiLevelElementNameAndTextQualifier(1); - - Element control = document.createElement(TAG_NAME); - control.appendChild(document.createTextNode(TEXT_A)); - control.appendChild(document.createTextNode(TEXT_B)); - - Element test = document.createElement(TAG_NAME); - test.appendChild(document.createTextNode(TEXT_A + TEXT_B)); - assertTrue("denormalised control text comparable to normalised test text", - qualifier.qualifyForComparison(control, test)); - } - - // three levels - public void testThreeLevels() throws Exception { - ElementQualifier qualifier = - new MultiLevelElementNameAndTextQualifier(3); - - Element control = document.createElement(TAG_NAME); - Element child = document.createElement(TAG_NAME2); - control.appendChild(child); - Element child2 = document.createElement(TAG_NAME); - child.appendChild(child2); - child2.appendChild(document.createTextNode(TEXT_B)); - - Element test = document.createElement(TAG_NAME); - child = document.createElement(TAG_NAME2); - test.appendChild(child); - child2 = document.createElement(TAG_NAME); - child.appendChild(child2); - child2.appendChild(document.createTextNode(TEXT_B)); - - assertTrue(qualifier.qualifyForComparison(control, test)); - } - - /** - * @see https://sourceforge.net/forum/forum.php?thread_id=1440169&forum_id=73274 - */ - public void testThread1440169() throws Exception { - String s1 = "<a><b><c>foo</c></b><b><c>bar</c></b></a>"; - String s2 = "<a><b><c>bar</c></b><b><c>foo</c></b></a>"; - Diff d = new Diff(s1, s2); - assertFalse(d.similar()); - - // reset - d = new Diff(s1, s2); - d.overrideElementQualifier(new ElementNameAndTextQualifier()); - assertFalse(d.similar()); - - // reset once again - d = new Diff(s1, s2); - d.overrideElementQualifier(new MultiLevelElementNameAndTextQualifier(2)); - assertTrue(d.similar()); - - } - - public void setUp() throws Exception { - document = XMLUnit.newControlParser().newDocument(); - } - -} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-02-05 19:47:45
|
Revision: 147 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=147&view=rev Author: bodewig Date: 2007-02-05 11:47:29 -0800 (Mon, 05 Feb 2007) Log Message: ----------- Fix indentation and remove tabs: (defun fixup-file () (interactive) (save-excursion (let ((start (or (re-search-forward "package") (point-min)))) (indent-region start (point-max) nil) (untabify (point-min) (point-max))))) Modified Paths: -------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/AbstractNodeTester.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/CountingNodeTester.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/DetailedDiff.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/Diff.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/Difference.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceConstants.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeReader.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/ElementNameAndAttributeQualifier.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/ElementNameAndTextQualifier.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/ElementNameQualifier.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/ElementQualifier.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/HTMLDocumentBuilder.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/IgnoreTextAndAttributeValuesDifferenceListener.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/NodeDescriptor.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/NodeDetail.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/NodeInputStream.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/NodeTest.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/NodeTestException.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/SimpleXpathEngine.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/TolerantSaxDocumentBuilder.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/Transform.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/Validator.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLAssert.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLTestCase.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/XpathNodeTracker.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/examples/MultiLevelElementNameAndTextQualifier.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/Replacement.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/SimpleSerializer.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/examples/test_MultiLevelElementNameAndTextQualifier.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/jaxp13/test_Jaxp13XpathEngine.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_BugFixes.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Constants.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_CountingNodeTester.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Diff.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Difference.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DoctypeReader.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_ElementNameAndAttributeQualifier.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_ElementNameAndTextQualifier.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_ElementNameQualifier.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_HTMLDocumentBuilder.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_IgnoreTextAndAttributeValuesDifferenceListener.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_JAXP_1_2_Schema_Validation.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_NodeDescriptor.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_NodeTest.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Replacement.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_SimpleXpathEngine.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_TolerantSaxDocumentBuilder.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Transform.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Validator.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_XMLTestCase.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_XMLUnit.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_XpathNodeTracker.java Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/AbstractNodeTester.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/AbstractNodeTester.java 2007-02-02 21:36:23 UTC (rev 146) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/AbstractNodeTester.java 2007-02-05 19:47:29 UTC (rev 147) @@ -71,41 +71,41 @@ */ public void testNode(Node aNode, NodeTest forTest) throws NodeTestException { switch (aNode.getNodeType()) { - case Node.ATTRIBUTE_NODE: - // should not happen as attributes are not exposed by DOM traversal - testAttribute((Attr)aNode); - break; - case Node.CDATA_SECTION_NODE: - testCDATASection((CDATASection)aNode); - break; - case Node.COMMENT_NODE: - testComment((Comment)aNode); - break; - case Node.DOCUMENT_TYPE_NODE: - testDocumentType((DocumentType)aNode); - break; - case Node.ELEMENT_NODE: - testElement((Element)aNode); - break; - case Node.ENTITY_NODE: - testEntity((Entity)aNode); - break; - case Node.ENTITY_REFERENCE_NODE: - testEntityReference((EntityReference)aNode); - break; - case Node.NOTATION_NODE: - testNotation((Notation)aNode); - break; - case Node.PROCESSING_INSTRUCTION_NODE: - testProcessingInstruction( - (ProcessingInstruction) aNode); - break; - case Node.TEXT_NODE: - testText((Text)aNode); - break; - default: - throw new NodeTestException("No delegate method for Node type", - aNode); + case Node.ATTRIBUTE_NODE: + // should not happen as attributes are not exposed by DOM traversal + testAttribute((Attr)aNode); + break; + case Node.CDATA_SECTION_NODE: + testCDATASection((CDATASection)aNode); + break; + case Node.COMMENT_NODE: + testComment((Comment)aNode); + break; + case Node.DOCUMENT_TYPE_NODE: + testDocumentType((DocumentType)aNode); + break; + case Node.ELEMENT_NODE: + testElement((Element)aNode); + break; + case Node.ENTITY_NODE: + testEntity((Entity)aNode); + break; + case Node.ENTITY_REFERENCE_NODE: + testEntityReference((EntityReference)aNode); + break; + case Node.NOTATION_NODE: + testNotation((Notation)aNode); + break; + case Node.PROCESSING_INSTRUCTION_NODE: + testProcessingInstruction( + (ProcessingInstruction) aNode); + break; + case Node.TEXT_NODE: + testText((Text)aNode); + break; + default: + throw new NodeTestException("No delegate method for Node type", + aNode); } } @@ -191,7 +191,7 @@ } private void unhandled(Node aNode) throws NodeTestException { - throw new NodeTestException("Test fails by default in AbstractNodeTester", aNode); + throw new NodeTestException("Test fails by default in AbstractNodeTester", aNode); } /** @@ -201,7 +201,7 @@ * @exception NodeTestException if mode Nodes were expected */ public void noMoreNodes(NodeTest forTest) throws NodeTestException { - //by default do nothing + //by default do nothing } } Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/CountingNodeTester.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/CountingNodeTester.java 2007-02-02 21:36:23 UTC (rev 146) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/CountingNodeTester.java 2007-02-05 19:47:29 UTC (rev 147) @@ -74,7 +74,7 @@ resetCounter(); if (testedNodes != expectedNumNodes) { throw new NodeTestException("Counted " + testedNodes - + " node(s) but expected " + expectedNumNodes); + + " node(s) but expected " + expectedNumNodes); } } Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DetailedDiff.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DetailedDiff.java 2007-02-02 21:36:23 UTC (rev 146) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DetailedDiff.java 2007-02-05 19:47:29 UTC (rev 147) @@ -75,13 +75,13 @@ final int returnValue = super.differenceFound(difference); Difference localDifference = null; switch (returnValue) { - case RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL: - return returnValue; - case RETURN_ACCEPT_DIFFERENCE: - break; - case RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR: - difference.setRecoverable(true); - break; + case RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL: + return returnValue; + case RETURN_ACCEPT_DIFFERENCE: + break; + case RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR: + difference.setRecoverable(true); + break; } allDifferences.add(difference); return returnValue; Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/Diff.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/Diff.java 2007-02-02 21:36:23 UTC (rev 146) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/Diff.java 2007-02-05 19:47:29 UTC (rev 147) @@ -72,7 +72,7 @@ * <br />Examples and more at <a href="http://xmlunit.sourceforge.net"/>xmlunit.sourceforge.net</a> */ public class Diff -implements DifferenceListener, ComparisonController { + implements DifferenceListener, ComparisonController { private final Document controlDoc; private final Document testDoc; private boolean similar = true; @@ -98,7 +98,7 @@ public Diff(Reader control, Reader test) throws SAXException, IOException { this(XMLUnit.buildDocument(XMLUnit.newControlParser(), control), - XMLUnit.buildDocument(XMLUnit.newTestParser(), test)); + XMLUnit.buildDocument(XMLUnit.newTestParser(), test)); } /** @@ -115,17 +115,17 @@ public Diff(String control, Transform testTransform) throws IOException, TransformerException, SAXException { this(XMLUnit.buildControlDocument(control), - testTransform.getResultDocument()); + testTransform.getResultDocument()); } - /** - * Construct a Diff that compares the XML read from two JAXP InputSources - */ + /** + * Construct a Diff that compares the XML read from two JAXP InputSources + */ public Diff(InputSource control, InputSource test) throws SAXException, IOException { - this(XMLUnit.buildDocument(XMLUnit.newControlParser(), control), - XMLUnit.buildDocument(XMLUnit.newTestParser(), test)); - } + this(XMLUnit.buildDocument(XMLUnit.newControlParser(), control), + XMLUnit.buildDocument(XMLUnit.newTestParser(), test)); + } /** * Construct a Diff that compares the XML in two JAXP DOMSources @@ -155,9 +155,9 @@ this.testDoc = getManipulatedDocument(testDoc); this.elementQualifierDelegate = elementQualifier; if (comparator == null) { - this.differenceEngine = new DifferenceEngine(this); + this.differenceEngine = new DifferenceEngine(this); } else { - this.differenceEngine = comparator; + this.differenceEngine = comparator; } this.messages = new StringBuffer(); } @@ -168,8 +168,8 @@ * @param prototype a prototypical instance */ protected Diff(Diff prototype) { - this(prototype.controlDoc, prototype.testDoc, prototype.differenceEngine, - prototype.elementQualifierDelegate); + this(prototype.controlDoc, prototype.testDoc, prototype.differenceEngine, + prototype.elementQualifierDelegate); } /** @@ -186,7 +186,7 @@ } try { Transform whitespaceStripper = XMLUnit.getStripWhitespaceTransform( - originalDoc); + originalDoc); return whitespaceStripper.getResultDocument(); } catch (TransformerException e) { throw new XMLUnitRuntimeException(e.getMessage(), e.getCause()); @@ -301,24 +301,24 @@ } switch (returnValue) { - case RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL: - return returnValue; - case RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR: - identical = false; + case RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL: + return returnValue; + case RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR: + identical = false; + haltComparison = false; + break; + case RETURN_ACCEPT_DIFFERENCE: + identical = false; + if (difference.isRecoverable()) { haltComparison = false; - break; - case RETURN_ACCEPT_DIFFERENCE: - identical = false; - if (difference.isRecoverable()) { - haltComparison = false; - } else { - similar = false; - haltComparison = true; - } - break; - default: - throw new IllegalArgumentException(returnValue - + " is not a defined DifferenceListener.RETURN_... value"); + } else { + similar = false; + haltComparison = true; + } + break; + default: + throw new IllegalArgumentException(returnValue + + " is not a defined DifferenceListener.RETURN_... value"); } if (haltComparison) { messages.append("\n[different]"); @@ -342,8 +342,8 @@ differenceListenerDelegate.skippedComparison(control, test); } else { System.err.println("DifferenceListener.skippedComparison: " - + "unhandled control node type=" + control - + ", unhandled test node type=" + test); + + "unhandled control node type=" + control + + ", unhandled test node type=" + test); } } @@ -392,13 +392,13 @@ this.differenceListenerDelegate = delegate; } - /** - * Override the <code>ElementQualifier</code> used to determine which - * control and test nodes are comparable for this difference comparison. - * @param delegate the ElementQualifier instance to delegate to. - */ - public void overrideElementQualifier(ElementQualifier delegate) { - this.elementQualifierDelegate = delegate; - } + /** + * Override the <code>ElementQualifier</code> used to determine which + * control and test nodes are comparable for this difference comparison. + * @param delegate the ElementQualifier instance to delegate to. + */ + public void overrideElementQualifier(ElementQualifier delegate) { + this.elementQualifierDelegate = delegate; + } } Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/Difference.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/Difference.java 2007-02-02 21:36:23 UTC (rev 146) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/Difference.java 2007-02-05 19:47:29 UTC (rev 147) @@ -80,7 +80,7 @@ * encountered NodeDetails */ protected Difference(Difference prototype, NodeDetail controlNodeDetail, - NodeDetail testNodeDetail) { + NodeDetail testNodeDetail) { this(prototype.getId(), prototype.getDescription(), prototype.isRecoverable()); this.controlNodeDetail = controlNodeDetail; this.testNodeDetail = testNodeDetail; @@ -113,7 +113,7 @@ * a DetailedDiff. */ protected void setRecoverable(boolean overrideValue) { - recoverable = overrideValue; + recoverable = overrideValue; } /** @@ -121,7 +121,7 @@ * at the Node where this difference was encountered */ public NodeDetail getControlNodeDetail() { - return controlNodeDetail; + return controlNodeDetail; } /** @@ -129,7 +129,7 @@ * at the Node where this difference was encountered */ public NodeDetail getTestNodeDetail() { - return testNodeDetail; + return testNodeDetail; } /** @@ -153,22 +153,22 @@ * their details also */ public String toString() { - StringBuffer buf = new StringBuffer(); - if (controlNodeDetail == null || testNodeDetail == null) { - appendBasicRepresentation(buf); - } else { - appendDetailedRepresentation(buf); - } + StringBuffer buf = new StringBuffer(); + if (controlNodeDetail == null || testNodeDetail == null) { + appendBasicRepresentation(buf); + } else { + appendDetailedRepresentation(buf); + } return buf.toString(); } private void appendBasicRepresentation(StringBuffer buf) { buf.append("Difference (#").append(id). - append(") ").append(description); + append(") ").append(description); } private void appendDetailedRepresentation(StringBuffer buf) { - buf.append("Expected ").append(getDescription()) + buf.append("Expected ").append(getDescription()) .append(" '").append(controlNodeDetail.getValue()) .append("' but was '").append(testNodeDetail.getValue()) .append("' - comparing "); Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceConstants.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceConstants.java 2007-02-02 21:36:23 UTC (rev 146) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceConstants.java 2007-02-05 19:47:29 UTC (rev 147) @@ -42,53 +42,53 @@ * <br />Examples and more at <a href="http://xmlunit.sourceforge.net"/>xmlunit.sourceforge.net</a> */ public interface DifferenceConstants { - /** Comparing an implied attribute value against an explicit value */ - int ATTR_VALUE_EXPLICITLY_SPECIFIED_ID = 1; - /** Comparing 2 elements and one has an attribute the other does not */ - int ATTR_NAME_NOT_FOUND_ID = 2; - /** Comparing 2 attributes with the same name but different values */ - int ATTR_VALUE_ID = 3; - /** Comparing 2 attribute lists with the same attributes in different sequence */ - int ATTR_SEQUENCE_ID = 4; - /** Comparing 2 CDATA sections with different values */ - int CDATA_VALUE_ID = 5; - /** Comparing 2 comments with different values */ - int COMMENT_VALUE_ID = 6; - /** Comparing 2 document types with different names */ - int DOCTYPE_NAME_ID = 7; - /** Comparing 2 document types with different public identifiers */ - int DOCTYPE_PUBLIC_ID_ID = 8; - /** Comparing 2 document types with different system identifiers */ - int DOCTYPE_SYSTEM_ID_ID = 9; - /** Comparing 2 elements with different tag names */ - int ELEMENT_TAG_NAME_ID = 10; - /** Comparing 2 elements with different number of attributes */ - int ELEMENT_NUM_ATTRIBUTES_ID = 11; - /** Comparing 2 processing instructions with different targets */ - int PROCESSING_INSTRUCTION_TARGET_ID = 12; - /** Comparing 2 processing instructions with different instructions */ - int PROCESSING_INSTRUCTION_DATA_ID = 13; - /** Comparing 2 different text values */ - int TEXT_VALUE_ID = 14; - /** Comparing 2 nodes with different namespace prefixes */ - int NAMESPACE_PREFIX_ID = 15; - /** Comparing 2 nodes with different namespace URIs */ - int NAMESPACE_URI_ID = 16; - /** Comparing 2 nodes with different node types */ - int NODE_TYPE_ID = 17; - /** Comparing 2 nodes but only one has any children*/ - int HAS_CHILD_NODES_ID = 18; - /** Comparing 2 nodes with different numbers of children */ - int CHILD_NODELIST_LENGTH_ID = 19; - /** Comparing 2 nodes with children whose nodes are in different sequence*/ - int CHILD_NODELIST_SEQUENCE_ID = 20; - /** Comparing 2 Documents only one of which has a doctype */ - int HAS_DOCTYPE_DECLARATION_ID = 21; - /** Comparing an implied attribute value against an explicit value */ - public static final Difference ATTR_VALUE_EXPLICITLY_SPECIFIED = + int ATTR_VALUE_EXPLICITLY_SPECIFIED_ID = 1; + /** Comparing 2 elements and one has an attribute the other does not */ + int ATTR_NAME_NOT_FOUND_ID = 2; + /** Comparing 2 attributes with the same name but different values */ + int ATTR_VALUE_ID = 3; + /** Comparing 2 attribute lists with the same attributes in different sequence */ + int ATTR_SEQUENCE_ID = 4; + /** Comparing 2 CDATA sections with different values */ + int CDATA_VALUE_ID = 5; + /** Comparing 2 comments with different values */ + int COMMENT_VALUE_ID = 6; + /** Comparing 2 document types with different names */ + int DOCTYPE_NAME_ID = 7; + /** Comparing 2 document types with different public identifiers */ + int DOCTYPE_PUBLIC_ID_ID = 8; + /** Comparing 2 document types with different system identifiers */ + int DOCTYPE_SYSTEM_ID_ID = 9; + /** Comparing 2 elements with different tag names */ + int ELEMENT_TAG_NAME_ID = 10; + /** Comparing 2 elements with different number of attributes */ + int ELEMENT_NUM_ATTRIBUTES_ID = 11; + /** Comparing 2 processing instructions with different targets */ + int PROCESSING_INSTRUCTION_TARGET_ID = 12; + /** Comparing 2 processing instructions with different instructions */ + int PROCESSING_INSTRUCTION_DATA_ID = 13; + /** Comparing 2 different text values */ + int TEXT_VALUE_ID = 14; + /** Comparing 2 nodes with different namespace prefixes */ + int NAMESPACE_PREFIX_ID = 15; + /** Comparing 2 nodes with different namespace URIs */ + int NAMESPACE_URI_ID = 16; + /** Comparing 2 nodes with different node types */ + int NODE_TYPE_ID = 17; + /** Comparing 2 nodes but only one has any children*/ + int HAS_CHILD_NODES_ID = 18; + /** Comparing 2 nodes with different numbers of children */ + int CHILD_NODELIST_LENGTH_ID = 19; + /** Comparing 2 nodes with children whose nodes are in different sequence*/ + int CHILD_NODELIST_SEQUENCE_ID = 20; + /** Comparing 2 Documents only one of which has a doctype */ + int HAS_DOCTYPE_DECLARATION_ID = 21; + + /** Comparing an implied attribute value against an explicit value */ + public static final Difference ATTR_VALUE_EXPLICITLY_SPECIFIED = new Difference(ATTR_VALUE_EXPLICITLY_SPECIFIED_ID, - "attribute value explicitly specified", true); + "attribute value explicitly specified", true); /** Comparing 2 elements and one has an attribute the other does not */ public static final Difference ATTR_NAME_NOT_FOUND = @@ -133,12 +133,12 @@ /** Comparing 2 processing instructions with different targets */ public static final Difference PROCESSING_INSTRUCTION_TARGET = new Difference(PROCESSING_INSTRUCTION_TARGET_ID, - "processing instruction target"); + "processing instruction target"); /** Comparing 2 processing instructions with different instructions */ public static final Difference PROCESSING_INSTRUCTION_DATA = new Difference(PROCESSING_INSTRUCTION_DATA_ID, - "processing instruction data"); + "processing instruction data"); /** Comparing 2 different text values */ public static final Difference TEXT_VALUE = @@ -167,10 +167,10 @@ /** Comparing 2 nodes with children whose nodes are in different sequence*/ public static final Difference CHILD_NODELIST_SEQUENCE = new Difference(CHILD_NODELIST_SEQUENCE_ID, - "sequence of child nodes", true); + "sequence of child nodes", true); /** Comparing 2 Documents only one of which has a doctype */ public static final Difference HAS_DOCTYPE_DECLARATION = new Difference(HAS_DOCTYPE_DECLARATION_ID, - "presence of doctype declaration", true); + "presence of doctype declaration", true); } \ No newline at end of file Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java 2007-02-02 21:36:23 UTC (rev 146) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java 2007-02-05 19:47:29 UTC (rev 147) @@ -77,9 +77,9 @@ * @see ComparisonController#haltComparison(Difference) */ public DifferenceEngine(ComparisonController controller) { - this.controller = controller; - this.controlTracker = new XpathNodeTracker(); - this.testTracker = new XpathNodeTracker(); + this.controller = controller; + this.controlTracker = new XpathNodeTracker(); + this.testTracker = new XpathNodeTracker(); } /** @@ -93,21 +93,21 @@ * in any sequence and that sequence is not considered important. */ public void compare(Node control, Node test, DifferenceListener listener, - ElementQualifier elementQualifier) { - controlTracker.reset(); - testTracker.reset(); + ElementQualifier elementQualifier) { + controlTracker.reset(); + testTracker.reset(); try { compare(getNullOrNotNull(control), getNullOrNotNull(test), - control, test, listener, NODE_TYPE); + control, test, listener, NODE_TYPE); if (control!=null) { compareNode(control, test, listener, elementQualifier); } } catch (DifferenceFoundException e) { // thrown by the protected compare() method to terminate the // comparison and unwind the call stack back to here - } + } } - + private String getNullOrNotNull(Node aNode) { return aNode==null ? NULL_NODE : NOT_NULL_NODE; } @@ -122,41 +122,41 @@ * @throws DifferenceFoundException */ protected void compareNode(Node control, Node test, - DifferenceListener listener, ElementQualifier elementQualifier) - throws DifferenceFoundException { + DifferenceListener listener, ElementQualifier elementQualifier) + throws DifferenceFoundException { boolean comparable = compareNodeBasics(control, test, listener); boolean isDocumentNode = false; - if (comparable) { - switch (control.getNodeType()) { - case Node.ELEMENT_NODE: - compareElement((Element)control, (Element)test, listener); - break; - case Node.CDATA_SECTION_NODE: - case Node.TEXT_NODE: - compareText((CharacterData) control, - (CharacterData) test, listener); - break; - case Node.COMMENT_NODE: - compareComment((Comment)control, (Comment)test, listener); - break; - case Node.DOCUMENT_TYPE_NODE: - compareDocumentType((DocumentType)control, - (DocumentType)test, listener); - break; - case Node.PROCESSING_INSTRUCTION_NODE: - compareProcessingInstruction((ProcessingInstruction)control, - (ProcessingInstruction)test, listener); - break; - case Node.DOCUMENT_NODE: - isDocumentNode = true; - compareDocument((Document)control, (Document) test, - listener, elementQualifier); - break; - default: - listener.skippedComparison(control, test); - } - } + if (comparable) { + switch (control.getNodeType()) { + case Node.ELEMENT_NODE: + compareElement((Element)control, (Element)test, listener); + break; + case Node.CDATA_SECTION_NODE: + case Node.TEXT_NODE: + compareText((CharacterData) control, + (CharacterData) test, listener); + break; + case Node.COMMENT_NODE: + compareComment((Comment)control, (Comment)test, listener); + break; + case Node.DOCUMENT_TYPE_NODE: + compareDocumentType((DocumentType)control, + (DocumentType)test, listener); + break; + case Node.PROCESSING_INSTRUCTION_NODE: + compareProcessingInstruction((ProcessingInstruction)control, + (ProcessingInstruction)test, listener); + break; + case Node.DOCUMENT_NODE: + isDocumentNode = true; + compareDocument((Document)control, (Document) test, + listener, elementQualifier); + break; + default: + listener.skippedComparison(control, test); + } + } compareHasChildNodes(control, test, listener); if (isDocumentNode) { @@ -166,8 +166,8 @@ compareNode(controlElement, testElement, listener, elementQualifier); } } else { - controlTracker.indent(); - testTracker.indent(); + controlTracker.indent(); + testTracker.indent(); compareNodeChildren(control, test, listener, elementQualifier); controlTracker.outdent(); testTracker.outdent(); @@ -183,14 +183,14 @@ * @throws DifferenceFoundException */ protected void compareDocument(Document control, Document test, - DifferenceListener listener, ElementQualifier elementQualifier) - throws DifferenceFoundException { + DifferenceListener listener, ElementQualifier elementQualifier) + throws DifferenceFoundException { DocumentType controlDoctype = control.getDoctype(); DocumentType testDoctype = test.getDoctype(); compare(getNullOrNotNull(controlDoctype), - getNullOrNotNull(testDoctype), - controlDoctype, testDoctype, listener, - HAS_DOCTYPE_DECLARATION); + getNullOrNotNull(testDoctype), + controlDoctype, testDoctype, listener, + HAS_DOCTYPE_DECLARATION); if (controlDoctype!=null && testDoctype!=null) { compareNode(controlDoctype, testDoctype, listener, elementQualifier); } @@ -206,7 +206,7 @@ * @throws DifferenceFoundException */ protected boolean compareNodeBasics(Node control, Node test, - DifferenceListener listener) throws DifferenceFoundException { + DifferenceListener listener) throws DifferenceFoundException { controlTracker.visited(control); testTracker.visited(test); @@ -220,9 +220,9 @@ NODE_TYPE); } compare(control.getNamespaceURI(), test.getNamespaceURI(), - control, test, listener, NAMESPACE_URI); + control, test, listener, NAMESPACE_URI); compare(control.getPrefix(), test.getPrefix(), - control, test, listener, NAMESPACE_PREFIX); + control, test, listener, NAMESPACE_PREFIX); return textAndCDATA || controlType.equals(testType); } @@ -245,13 +245,13 @@ * @throws DifferenceFoundException */ protected void compareHasChildNodes(Node control, Node test, - DifferenceListener listener) throws DifferenceFoundException { + DifferenceListener listener) throws DifferenceFoundException { Boolean controlHasChildren = control.hasChildNodes() ? Boolean.TRUE : Boolean.FALSE; Boolean testHasChildren = test.hasChildNodes() ? Boolean.TRUE : Boolean.FALSE; compare(controlHasChildren, testHasChildren, control, test, - listener, HAS_CHILD_NODES); + listener, HAS_CHILD_NODES); } /** @@ -264,8 +264,8 @@ * @throws DifferenceFoundException */ protected void compareNodeChildren(Node control, Node test, - DifferenceListener listener, ElementQualifier elementQualifier) - throws DifferenceFoundException { + DifferenceListener listener, ElementQualifier elementQualifier) + throws DifferenceFoundException { if (control.hasChildNodes() && test.hasChildNodes()) { NodeList controlChildren = control.getChildNodes(); NodeList testChildren = test.getChildNodes(); @@ -273,9 +273,9 @@ Integer controlLength = new Integer(controlChildren.getLength()); Integer testLength = new Integer(testChildren.getLength()); compare(controlLength, testLength, control, test, listener, - CHILD_NODELIST_LENGTH); + CHILD_NODELIST_LENGTH); compareNodeList(controlChildren, testChildren, - controlLength.intValue(), listener, elementQualifier); + controlLength.intValue(), listener, elementQualifier); } } @@ -397,80 +397,80 @@ * @throws DifferenceFoundException */ protected void compareElement(Element control, Element test, - DifferenceListener listener) throws DifferenceFoundException { - compare(getUnNamespacedNodeName(control), getUnNamespacedNodeName(test), - control, test, listener, ELEMENT_TAG_NAME); + DifferenceListener listener) throws DifferenceFoundException { + compare(getUnNamespacedNodeName(control), getUnNamespacedNodeName(test), + control, test, listener, ELEMENT_TAG_NAME); NamedNodeMap controlAttr = control.getAttributes(); - Integer controlNonXmlnsAttrLength = getNonXmlnsAttrLength(controlAttr); + Integer controlNonXmlnsAttrLength = getNonXmlnsAttrLength(controlAttr); NamedNodeMap testAttr = test.getAttributes(); Integer testNonXmlnsAttrLength = getNonXmlnsAttrLength(testAttr); compare(controlNonXmlnsAttrLength, testNonXmlnsAttrLength, - control, test, listener, ELEMENT_NUM_ATTRIBUTES); + control, test, listener, ELEMENT_NUM_ATTRIBUTES); compareElementAttributes(control, test, controlAttr, testAttr, - listener); + listener); } - private Integer getNonXmlnsAttrLength(NamedNodeMap attributes) { - int length = 0, maxLength = attributes.getLength(); - for (int i = 0; i < maxLength; ++i) { - if (!isXMLNSAttribute((Attr) attributes.item(i))) { - ++length; - } - } - return new Integer(length); - } + private Integer getNonXmlnsAttrLength(NamedNodeMap attributes) { + int length = 0, maxLength = attributes.getLength(); + for (int i = 0; i < maxLength; ++i) { + if (!isXMLNSAttribute((Attr) attributes.item(i))) { + ++length; + } + } + return new Integer(length); + } private void compareElementAttributes(Element control, Element test, - NamedNodeMap controlAttr, NamedNodeMap testAttr, - DifferenceListener listener) throws DifferenceFoundException { + NamedNodeMap controlAttr, NamedNodeMap testAttr, + DifferenceListener listener) throws DifferenceFoundException { for (int i=0; i < controlAttr.getLength(); ++i) { Attr nextAttr = (Attr) controlAttr.item(i); - if (isXMLNSAttribute(nextAttr)) { - // xml namespacing is handled in compareNodeBasics - } else { - boolean isNamespacedAttr = isNamespaced(nextAttr); - String attrName = getUnNamespacedNodeName(nextAttr, isNamespacedAttr); - Attr compareTo = null; - - if (isNamespacedAttr) { - compareTo = (Attr) testAttr.getNamedItemNS( - nextAttr.getNamespaceURI(), attrName); - } else { - compareTo = (Attr) testAttr.getNamedItem(attrName); - } - - if (compareTo != null) { - compareAttribute(nextAttr, compareTo, listener); - - Attr attributeItem = (Attr) testAttr.item(i); - String testAttrName = "[attribute absent]"; - if (attributeItem != null) { - testAttrName = getUnNamespacedNodeName(attributeItem); - } - compare(attrName, testAttrName, - nextAttr, compareTo, listener, ATTR_SEQUENCE); - } else { - compare(attrName, null, control, test, listener, - ATTR_NAME_NOT_FOUND); - } - } + if (isXMLNSAttribute(nextAttr)) { + // xml namespacing is handled in compareNodeBasics + } else { + boolean isNamespacedAttr = isNamespaced(nextAttr); + String attrName = getUnNamespacedNodeName(nextAttr, isNamespacedAttr); + Attr compareTo = null; + + if (isNamespacedAttr) { + compareTo = (Attr) testAttr.getNamedItemNS( + nextAttr.getNamespaceURI(), attrName); + } else { + compareTo = (Attr) testAttr.getNamedItem(attrName); + } + + if (compareTo != null) { + compareAttribute(nextAttr, compareTo, listener); + + Attr attributeItem = (Attr) testAttr.item(i); + String testAttrName = "[attribute absent]"; + if (attributeItem != null) { + testAttrName = getUnNamespacedNodeName(attributeItem); + } + compare(attrName, testAttrName, + nextAttr, compareTo, listener, ATTR_SEQUENCE); + } else { + compare(attrName, null, control, test, listener, + ATTR_NAME_NOT_FOUND); + } + } } controlTracker.clearTrackedAttribute(); testTracker.clearTrackedAttribute(); } private String getUnNamespacedNodeName(Node aNode) { - return getUnNamespacedNodeName(aNode, isNamespaced(aNode)); + return getUnNamespacedNodeName(aNode, isNamespaced(aNode)); } - private String getUnNamespacedNodeName(Node aNode, boolean isNamespacedNode) { - if (isNamespacedNode) { - return aNode.getLocalName(); - } - return aNode.getNodeName(); - } + private String getUnNamespacedNodeName(Node aNode, boolean isNamespacedNode) { + if (isNamespacedNode) { + return aNode.getLocalName(); + } + return aNode.getNodeName(); + } /** @@ -490,19 +490,19 @@ * @throws DifferenceFoundException */ protected void compareAttribute(Attr control, Attr test, - DifferenceListener listener) throws DifferenceFoundException { - controlTracker.visited(control); - testTracker.visited(test); - - compare(control.getPrefix(), test.getPrefix(), control, test, - listener, NAMESPACE_PREFIX); - + DifferenceListener listener) throws DifferenceFoundException { + controlTracker.visited(control); + testTracker.visited(test); + + compare(control.getPrefix(), test.getPrefix(), control, test, + listener, NAMESPACE_PREFIX); + compare(control.getValue(), test.getValue(), control, test, - listener, ATTR_VALUE); + listener, ATTR_VALUE); compare(control.getSpecified() ? Boolean.TRUE : Boolean.FALSE, - test.getSpecified() ? Boolean.TRUE : Boolean.FALSE, - control, test, listener, ATTR_VALUE_EXPLICITLY_SPECIFIED); + test.getSpecified() ? Boolean.TRUE : Boolean.FALSE, + control, test, listener, ATTR_VALUE_EXPLICITLY_SPECIFIED); } /** @@ -513,7 +513,7 @@ * @throws DifferenceFoundException */ protected void compareCDataSection(CDATASection control, CDATASection test, - DifferenceListener listener) throws DifferenceFoundException { + DifferenceListener listener) throws DifferenceFoundException { compareText(control, test, listener); } @@ -525,7 +525,7 @@ * @throws DifferenceFoundException */ protected void compareComment(Comment control, Comment test, - DifferenceListener listener) throws DifferenceFoundException { + DifferenceListener listener) throws DifferenceFoundException { compareCharacterData(control, test, listener, COMMENT_VALUE); } @@ -537,14 +537,14 @@ * @throws DifferenceFoundException */ protected void compareDocumentType(DocumentType control, DocumentType test, - DifferenceListener listener) throws DifferenceFoundException { + DifferenceListener listener) throws DifferenceFoundException { compare(control.getName(), test.getName(), control, test, listener, - DOCTYPE_NAME); + DOCTYPE_NAME); compare(control.getPublicId(), test.getPublicId(), control, test, listener, - DOCTYPE_PUBLIC_ID); + DOCTYPE_PUBLIC_ID); compare(control.getSystemId(), test.getSystemId(), - control, test, listener, DOCTYPE_SYSTEM_ID); + control, test, listener, DOCTYPE_SYSTEM_ID); } /** @@ -555,12 +555,12 @@ * @throws DifferenceFoundException */ protected void compareProcessingInstruction(ProcessingInstruction control, - ProcessingInstruction test, DifferenceListener listener) - throws DifferenceFoundException { + ProcessingInstruction test, DifferenceListener listener) + throws DifferenceFoundException { compare(control.getTarget(), test.getTarget(), control, test, listener, - PROCESSING_INSTRUCTION_TARGET); + PROCESSING_INSTRUCTION_TARGET); compare(control.getData(), test.getData(), control, test, listener, - PROCESSING_INSTRUCTION_DATA); + PROCESSING_INSTRUCTION_DATA); } /** @@ -599,10 +599,10 @@ * @throws DifferenceFoundException */ private void compareCharacterData(CharacterData control, CharacterData test, - DifferenceListener listener, Difference difference) - throws DifferenceFoundException { + DifferenceListener listener, Difference difference) + throws DifferenceFoundException { compare(control.getData(), test.getData(), control, test, listener, - difference); + difference); } /** @@ -617,15 +617,15 @@ * @throws DifferenceFoundException */ protected void compare(Object expected, Object actual, - Node control, Node test, DifferenceListener listener, Difference difference) - throws DifferenceFoundException { + Node control, Node test, DifferenceListener listener, Difference difference) + throws DifferenceFoundException { if (unequal(expected, actual)) { - NodeDetail controlDetail = new NodeDetail(String.valueOf(expected), - control, controlTracker.toXpathString()); - NodeDetail testDetail = new NodeDetail(String.valueOf(actual), - test, testTracker.toXpathString()); - Difference differenceInstance = new Difference(difference, - controlDetail, testDetail); + NodeDetail controlDetail = new NodeDetail(String.valueOf(expected), + control, controlTracker.toXpathString()); + NodeDetail testDetail = new NodeDetail(String.valueOf(actual), + test, testTracker.toXpathString()); + Difference differenceInstance = new Difference(difference, + controlDetail, testDetail); listener.differenceFound(differenceInstance); if (controller.haltComparison(differenceInstance)) { throw flowControlException; Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeReader.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeReader.java 2007-02-02 21:36:23 UTC (rev 146) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeReader.java 2007-02-05 19:47:29 UTC (rev 147) @@ -72,7 +72,7 @@ * @param systemID */ public DoctypeReader(Reader originalSource, String doctypeName, - String systemID) { + String systemID) { this.originalSource = originalSource; this.doctypeName = doctypeName; this.systemId = systemID; @@ -132,13 +132,13 @@ curChar = withinContent.charAt(i); if (curChar == '<') { switch (withinContent.charAt(i + 1)) { - case '?': - case '!': - case '-': - canInsert = false; - break; - default: - startAt = i; + case '?': + case '!': + case '-': + canInsert = false; + break; + default: + startAt = i; } } else if (curChar == '>') { canInsert = true; @@ -157,7 +157,7 @@ * @return the content, after DOCTYPE amendment / addition */ public String replaceDoctype(StringBuffer withinContent, - String doctypeName, String systemId) { + String doctypeName, String systemId) { String content = withinContent.toString(); int startDoctype = content.indexOf(DOCTYPE); boolean noCurrentDoctype = false; @@ -206,7 +206,7 @@ private Reader getReplacementReader() throws IOException { StringBuffer originalContent = getContent(originalSource); String replacedContent = replaceDoctype(originalContent, - doctypeName, systemId); + doctypeName, systemId); return new StringReader(replacedContent); } Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/ElementNameAndAttributeQualifier.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/ElementNameAndAttributeQualifier.java 2007-02-02 21:36:23 UTC (rev 146) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/ElementNameAndAttributeQualifier.java 2007-02-05 19:47:29 UTC (rev 147) @@ -7,16 +7,16 @@ modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - * Neither the name of the xmlunit.sourceforge.net nor the names - of its contributors may be used to endorse or promote products - derived from this software without specific prior written - permission. + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT @@ -49,105 +49,105 @@ * @see Diff#overrideElementQualifier(ElementQualifier) */ public class ElementNameAndAttributeQualifier extends ElementNameQualifier { - public static final String[] ALL_ATTRIBUTES = {"*"}; - - private final String[] qualifyingAttrNames; - - /** - * No-args constructor: use all attributes from all elements to determine - * whether elements qualify for comparability - */ - public ElementNameAndAttributeQualifier() { - this(ALL_ATTRIBUTES); - } - - /** - * Simple constructor for a single qualifying attribute name - * @param attrName the value to use to qualify whether two elements can be - * compared further for differences - */ - public ElementNameAndAttributeQualifier(String attrName) { - this(new String[] {attrName}); - } + public static final String[] ALL_ATTRIBUTES = {"*"}; + + private final String[] qualifyingAttrNames; + + /** + * No-args constructor: use all attributes from all elements to determine + * whether elements qualify for comparability + */ + public ElementNameAndAttributeQualifier() { + this(ALL_ATTRIBUTES); + } + + /** + * Simple constructor for a single qualifying attribute name + * @param attrName the value to use to qualify whether two elements can be + * compared further for differences + */ + public ElementNameAndAttributeQualifier(String attrName) { + this(new String[] {attrName}); + } - /** - * Extended constructor for multiple qualifying attribute names - * @param attrNames the array of values to use to qualify whether two - * elements can be compared further for differences - */ - public ElementNameAndAttributeQualifier(String[] attrNames) { - this.qualifyingAttrNames = attrNames; - } + /** + * Extended constructor for multiple qualifying attribute names + * @param attrNames the array of values to use to qualify whether two + * elements can be compared further for differences + */ + public ElementNameAndAttributeQualifier(String[] attrNames) { + this.qualifyingAttrNames = attrNames; + } - /** - * Determine whether two elements qualify for further Difference comparison. - * @param differenceEngine the DifferenceEngine instance wanting to - * determine if the elements are comparable - * @param control - * @param test - * @return true if the two elements qualify for further comparison based on - * both the superclass qualification (namespace URI and non- namespaced tag - * name), and the presence of qualifying attributes with the same values; - * false otherwise - */ - public boolean qualifyForComparison(Element control, Element test) { - if (super.qualifyForComparison(control, test)) { - return areAttributesComparable(control, test); - } - return false; - } - - /** - * Determine whether the qualifying attributes are present in both elements - * and if so whether their values are the same - * @param control - * @param test - * @return true if all qualifying attributes are present with the same - * values, false otherwise - */ - protected boolean areAttributesComparable(Element control, Element test) { - String controlValue, testValue; - Attr[] qualifyingAttributes; - NamedNodeMap namedNodeMap = control.getAttributes(); - if (qualifyingAttrNames == ALL_ATTRIBUTES) { - qualifyingAttributes = new Attr[namedNodeMap.getLength()]; - for (int n=0; n < qualifyingAttributes.length; ++n) { - qualifyingAttributes[n] = (Attr) namedNodeMap.item(n); - } - } else { - qualifyingAttributes = new Attr[qualifyingAttrNames.length]; - for (int n=0; n < qualifyingAttrNames.length; ++n) { - qualifyingAttributes[n] = (Attr) namedNodeMap.getNamedItem(qualifyingAttrNames[n]); - } - } - - String nsURI, name; - for (int i=0; i < qualifyingAttributes.length; ++i) { - if (qualifyingAttributes[i] != null) { - nsURI = qualifyingAttributes[i].getNamespaceURI(); - controlValue = qualifyingAttributes[i].getNodeValue(); - name = qualifyingAttributes[i].getName(); - } else { - // cannot be "*" case - nsURI = controlValue = ""; - name = qualifyingAttrNames[i]; - } - if (nsURI == null || nsURI.length() == 0) { - testValue = test.getAttribute(name); - } else { - testValue = test.getAttributeNS(nsURI, qualifyingAttributes[i].getLocalName()); - } - if (controlValue == null) { - if (testValue != null) { - return false; - } - } else { - if (!controlValue.equals(testValue)) { - return false; - } - } - } - return true; - } + /** + * Determine whether two elements qualify for further Difference comparison. + * @param differenceEngine the DifferenceEngine instance wanting to + * determine if the elements are comparable + * @param control + * @param test + * @return true if the two elements qualify for further comparison based on + * both the superclass qualification (namespace URI and non- namespaced tag + * name), and the presence of qualifying attributes with the same values; + * false otherwise + */ + public boolean qualifyForComparison(Element control, Element test) { + if (super.qualifyForComparison(control, test)) { + return areAttributesComparable(control, test); + } + return false; + } + + /** + * Determine whether the qualifying attributes are present in both elements + * and if so whether their values are the same + * @param control + * @param test + * @return true if all qualifying attributes are present with the same + * values, false otherwise + */ + protected boolean areAttributesComparable(Element control, Element test) { + String controlValue, testValue; + Attr[] qualifyingAttributes; + NamedNodeMap namedNodeMap = control.getAttributes(); + if (qualifyingAttrNames == ALL_ATTRIBUTES) { + qualifyingAttributes = new Attr[namedNodeMap.getLength()]; + for (int n=0; n < qualifyingAttributes.length; ++n) { + qualifyingAttributes[n] = (Attr) namedNodeMap.item(n); + } + } else { + qualifyingAttributes = new Attr[qualifyingAttrNames.length]; + for (int n=0; n < qualifyingAttrNames.length; ++n) { + qualifyingAttributes[n] = (Attr) namedNodeMap.getNamedItem(qualifyingAttrNames[n]); + } + } + + String nsURI, name; + for (int i=0; i < qualifyingAttributes.length; ++i) { + if (qualifyingAttributes[i] != null) { + nsURI = qualifyingAttributes[i].getNamespaceURI(); + controlValue = qualifyingAttributes[i].getNodeValue(); + name = qualifyingAttributes[i].getName(); + } else { + // cannot be "*" case + nsURI = controlValue = ""; + name = qualifyingAttrNames[i]; + } + if (nsURI == null || nsURI.length() == 0) { + testValue = test.getAttribute(name); + } else { + testValue = test.getAttributeNS(nsURI, qualifyingAttributes[i].getLocalName()); + } + if (controlValue == null) { + if (testValue != null) { + return false; + } + } else { + if (!controlValue.equals(testValue)) { + return false; + } + } + } + return true; + } } Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/ElementNameAndTextQualifier.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/ElementNameAndTextQualifier.java 2007-02-02 21:36:23 UTC (rev 146) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/ElementNameAndTextQualifier.java 2007-02-05 19:47:29 UTC (rev 147) @@ -7,16 +7,16 @@ modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - * Neither the name of the xmlunit.sourceforge.net nor the names - of its contributors may be used to endorse or promote products - derived from this software without specific prior written - permission. + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT @@ -50,53 +50,53 @@ * @see Diff#overrideElementQualifier(ElementQualifier) */ public class ElementNameAndTextQualifier extends ElementNameQualifier { - /** - * Determine whether two elements qualify for further Difference comparison. - * @param control - * @param test - * @return true if the two elements qualify for further comparison based on - * both the superclass qualification (namespace URI and non- namespaced tag - * name), and the qualification of the text nodes contained within the - * elements; false otherwise - */ - public bo... [truncated message content] |
From: <bo...@us...> - 2007-03-23 04:37:25
|
Revision: 151 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=151&view=rev Author: bodewig Date: 2007-03-22 21:37:22 -0700 (Thu, 22 Mar 2007) Log Message: ----------- fix issue 1683752 Modified Paths: -------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/Diff.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/Diff.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/Diff.java 2007-03-22 17:11:11 UTC (rev 150) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/Diff.java 2007-03-23 04:37:22 UTC (rev 151) @@ -154,11 +154,7 @@ this.controlDoc = getManipulatedDocument(controlDoc); this.testDoc = getManipulatedDocument(testDoc); this.elementQualifierDelegate = elementQualifier; - if (comparator == null) { - this.differenceEngine = new DifferenceEngine(this); - } else { - this.differenceEngine = comparator; - } + this.differenceEngine = comparator; this.messages = new StringBuffer(); } @@ -247,7 +243,8 @@ if (compared) { return; } - differenceEngine.compare(controlDoc, testDoc, this, elementQualifierDelegate); + getDifferenceEngine().compare(controlDoc, testDoc, this, + elementQualifierDelegate); compared = true; } @@ -401,4 +398,13 @@ this.elementQualifierDelegate = delegate; } + /** + * Lazily initializes the difference engine if it hasn't been set + * via a constructor. + */ + private DifferenceEngine getDifferenceEngine() { + return differenceEngine == null + ? new DifferenceEngine(this) : differenceEngine; + } + } Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java 2007-03-22 17:11:11 UTC (rev 150) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java 2007-03-23 04:37:22 UTC (rev 151) @@ -179,7 +179,7 @@ assertEquals(3, l.size()); } - public void XtestSeeAllDifferencesEvenIfDiffSaysHaltComparison() throws Exception { + public void testSeeAllDifferencesEvenIfDiffSaysHaltComparison() throws Exception { String control = "<a><b/><c/></a>"; String test = "<a><c/></a>"; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-03-28 04:07:35
|
Revision: 159 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=159&view=rev Author: bodewig Date: 2007-03-27 21:07:35 -0700 (Tue, 27 Mar 2007) Log Message: ----------- More overrides that allow InputSource as source Modified Paths: -------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeReader.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/Validator.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLAssert.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLTestCase.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Validator.java Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeReader.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeReader.java 2007-03-28 04:06:22 UTC (rev 158) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeReader.java 2007-03-28 04:07:35 UTC (rev 159) @@ -38,6 +38,8 @@ import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; @@ -79,6 +81,32 @@ } /** + * Create a Reader whose XML content is provided by the originalSource with + * the exception of the DOCTYPE which is provided by the doctypeName + * and systemID. + * @param originalSource + * @param doctypeName + * @param systemID + */ + public DoctypeReader(InputStream originalSource, String encoding, + String doctypeName, String systemID) + throws IOException { + this(encoding != null + ? new InputStreamReader(originalSource, encoding) + : xmlStreamToReader(originalSource), + doctypeName, systemID); + } + + // XXX - we are cheating here, we should read into the source + // stream to see whether the XML decl (if any) specifies the + // encoding and then return an InputStreamReader using the proper + // encoding + private static Reader xmlStreamToReader(InputStream originalSource) + throws IOException { + return new InputStreamReader(originalSource); + } + + /** * @return the content of the original source, without amendments or * substitutions. Safe to call multiple times. * @throws IOException if thrown while reading from the original source Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/Validator.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/Validator.java 2007-03-28 04:06:22 UTC (rev 158) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/Validator.java 2007-03-28 04:07:35 UTC (rev 159) @@ -240,6 +240,29 @@ /** * Full constructor. + * Validates the contents of the InputSource using the DTD + * specified with the systemID and named with the doctype name. + * + * @param sourceForValidation + * @param systemID + * @param doctype + * @throws SAXException + * @throws ConfigurationException if validation could not be turned on + */ + public Validator(InputSource sourceForValidation, String systemID, + String doctype) + throws SAXException, IOException, ConfigurationException { + this(sourceForValidation.getCharacterStream() != null + ? new DoctypeReader(sourceForValidation.getCharacterStream(), + doctype, systemID) + : new DoctypeReader(sourceForValidation.getByteStream(), + sourceForValidation.getEncoding(), + doctype, systemID), + systemID); + } + + /** + * Full constructor. * Validates the contents of the Reader using the DTD specified with the * systemID and named with the doctype name. * @@ -249,9 +272,12 @@ * @throws SAXException * @throws ConfigurationException if validation could not be turned on */ - public Validator(Reader readerForValidation, String systemID, String doctype) + public Validator(Reader readerForValidation, String systemID, + String doctype) throws SAXException, ConfigurationException { - this(new DoctypeReader(readerForValidation, doctype, systemID), + this(readerForValidation instanceof DoctypeReader + ? readerForValidation + : new DoctypeReader(readerForValidation, doctype, systemID), systemID); } Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLAssert.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLAssert.java 2007-03-28 04:06:22 UTC (rev 158) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLAssert.java 2007-03-28 04:07:35 UTC (rev 159) @@ -49,6 +49,7 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -109,9 +110,7 @@ * @param assertion true if asserting that result is similar */ public static void assertXMLEqual(Diff diff, boolean assertion) { - if (assertion != diff.similar()) { - fail(diff.toString()); - } + assertXMLEqual(null, diff, assertion); } /** @@ -120,21 +119,28 @@ * @param diff the result of an XML comparison * @param assertion true if asserting that result is similar */ - public static void assertXMLEqual(String msg, Diff diff, boolean assertion) { + public static void assertXMLEqual(String msg, Diff diff, + boolean assertion) { if (assertion != diff.similar()) { - fail(msg + ", " + diff.toString()); + fail(getFailMessage(msg, diff)); } } + private static String getFailMessage(String msg, Diff diff) { + StringBuffer sb = new StringBuffer(); + if (msg != null && msg.length() > 0) { + sb.append(msg).append(", "); + } + return sb.append(diff.toString()).toString(); + } + /** * Assert that the result of an XML comparison is or is not identical * @param diff the result of an XML comparison * @param assertion true if asserting that result is identical */ public static void assertXMLIdentical(Diff diff, boolean assertion) { - if (assertion != diff.identical()) { - fail(diff.toString()); - } + assertXMLIdentical(null, diff, assertion); } /** @@ -156,7 +162,7 @@ */ public static void assertXMLIdentical(String msg, Diff diff, boolean assertion) { if (assertion != diff.identical()) { - fail(msg + ", " + diff.toString()); + fail(getFailMessage(msg, diff)); } } @@ -167,10 +173,21 @@ * @throws SAXException * @throws IOException */ + public static void assertXMLEqual(InputSource control, InputSource test) + throws SAXException, IOException { + assertXMLEqual(null, control, test); + } + + /** + * Assert that two XML documents are similar + * @param control XML to be compared against + * @param test XML to be tested + * @throws SAXException + * @throws IOException + */ public static void assertXMLEqual(String control, String test) throws SAXException, IOException { - Diff diff = new Diff(control, test); - assertXMLEqual(diff, true); + assertXMLEqual(null, control, test); } /** @@ -179,8 +196,7 @@ * @param test XML to be tested */ public static void assertXMLEqual(Document control, Document test) { - Diff diff = new Diff(control, test); - assertXMLEqual(diff, true); + assertXMLEqual(null, control, test); } /** @@ -192,8 +208,22 @@ */ public static void assertXMLEqual(Reader control, Reader test) throws SAXException, IOException { + assertXMLEqual(null, control, test); + } + + /** + * Assert that two XML documents are similar + * @param err Message to be displayed on assertion failure + * @param control XML to be compared against + * @param test XML to be tested + * @throws SAXException + * @throws IOException + */ + public static void assertXMLEqual(String err, InputSource control, + InputSource test) + throws SAXException, IOException { Diff diff = new Diff(control, test); - assertXMLEqual(diff, true); + assertXMLEqual(err, diff, true); } /** @@ -243,24 +273,21 @@ * @throws SAXException * @throws IOException */ - public static void assertXMLNotEqual(String control, String test) + public static void assertXMLNotEqual(InputSource control, InputSource test) throws SAXException, IOException { - Diff diff = new Diff(control, test); - assertXMLEqual(diff, false); + assertXMLNotEqual(null, control, test); } /** * Assert that two XML documents are NOT similar - * @param err Message to be displayed on assertion failure * @param control XML to be compared against * @param test XML to be tested * @throws SAXException * @throws IOException */ - public static void assertXMLNotEqual(String err, String control, String test) + public static void assertXMLNotEqual(String control, String test) throws SAXException, IOException { - Diff diff = new Diff(control, test); - assertXMLEqual(err, diff, false); + assertXMLNotEqual(null, control, test); } /** @@ -269,33 +296,48 @@ * @param test XML to be tested */ public static void assertXMLNotEqual(Document control, Document test) { - Diff diff = new Diff(control, test); - assertXMLEqual(diff, false); + assertXMLNotEqual(null, control, test); } /** * Assert that two XML documents are NOT similar + * @param control XML to be compared against + * @param test XML to be tested + * @throws SAXException + * @throws IOException + */ + public static void assertXMLNotEqual(Reader control, Reader test) + throws SAXException, IOException { + assertXMLNotEqual(null, control, test); + } + + /** + * Assert that two XML documents are NOT similar * @param err Message to be displayed on assertion failure * @param control XML to be compared against * @param test XML to be tested + * @throws SAXException + * @throws IOException */ - public static void assertXMLNotEqual(String err, Document control, - Document test) { + public static void assertXMLNotEqual(String err, InputSource control, + InputSource test) + throws SAXException, IOException { Diff diff = new Diff(control, test); assertXMLEqual(err, diff, false); } /** * Assert that two XML documents are NOT similar + * @param err Message to be displayed on assertion failure * @param control XML to be compared against * @param test XML to be tested * @throws SAXException * @throws IOException */ - public static void assertXMLNotEqual(Reader control, Reader test) + public static void assertXMLNotEqual(String err, String control, String test) throws SAXException, IOException { Diff diff = new Diff(control, test); - assertXMLEqual(diff, false); + assertXMLEqual(err, diff, false); } /** @@ -303,6 +345,18 @@ * @param err Message to be displayed on assertion failure * @param control XML to be compared against * @param test XML to be tested + */ + public static void assertXMLNotEqual(String err, Document control, + Document test) { + Diff diff = new Diff(control, test); + assertXMLEqual(err, diff, false); + } + + /** + * Assert that two XML documents are NOT similar + * @param err Message to be displayed on assertion failure + * @param control XML to be compared against + * @param test XML to be tested * @throws SAXException * @throws IOException */ @@ -326,6 +380,20 @@ } /** + * Assert that the node lists of two Xpaths in the same document are equal + * @param xpathOne + * @param xpathTwo + * @param document + * @see XpathEngine + */ + public static void assertXpathsEqual(String controlXpath, String testXpath, + InputSource document) + throws SAXException, IOException, XpathException { + assertXpathsEqual(controlXpath, testXpath, + XMLUnit.buildControlDocument(document)); + } + + /** * Assert that the node lists of two Xpaths in the same XML string are * equal * @param xpathOne @@ -342,6 +410,25 @@ } /** + * Assert that the node lists of two Xpaths in two documents are equal + * @param xpathOne + * @param xpathTwo + * @param controlDocument + * @param testDocument + * @see XpathEngine + */ + public static void assertXpathsEqual(String controlXpath, + InputSource controlDocument, + String testXpath, + InputSource testDocument) + throws SAXException, IOException, XpathException { + assertXpathsEqual(controlXpath, + XMLUnit.buildControlDocument(controlDocument), + testXpath, + XMLUnit.buildTestDocument(testDocument)); + } + + /** * Assert that the node lists of two Xpaths in two XML strings are equal * @param xpathOne * @param inControlXMLString @@ -365,7 +452,8 @@ * Assert that the node lists of two Xpaths in two documents are equal * @param xpathOne * @param xpathTwo - * @param document + * @param controlDocument + * @param testDocument * @see XpathEngine */ public static void assertXpathsEqual(String controlXpath, @@ -398,6 +486,21 @@ } /** + * Assert that the node lists of two Xpaths in the same document are NOT equal + * @param xpathOne + * @param xpathTwo + * @param document + * @see XpathEngine + */ + public static void assertXpathsNotEqual(String controlXpath, + String testXpath, + InputSource document) + throws SAXException, IOException, XpathException { + assertXpathsNotEqual(controlXpath, testXpath, + XMLUnit.buildControlDocument(document)); + } + + /** * Assert that the node lists of two Xpaths in the same XML string are NOT * equal * @param xpathOne @@ -435,6 +538,27 @@ } /** + * Assert that the node lists of two Xpaths in two XML strings are + * NOT equal + * @param xpathOne + * @param controlDocument + * @param xpathTwo + * @param testDocument + * @throws SAXException + * @throws IOException + */ + public static void assertXpathsNotEqual(String controlXpath, + InputSource controlDocument, + String testXpath, + InputSource testDocument) + throws SAXException, IOException, XpathException { + assertXpathsNotEqual(controlXpath, + XMLUnit.buildControlDocument(controlDocument), + testXpath, + XMLUnit.buildTestDocument(testDocument)); + } + + /** * Assert that the node lists of two Xpaths in two documents are NOT equal * @param xpathOne * @param xpathTwo @@ -475,6 +599,23 @@ * equal * @param xpathOne * @param xpathTwo + * @param document + * @throws SAXException + * @throws IOException + */ + public static void assertXpathValuesEqual(String controlXpath, + String testXpath, + InputSource document) + throws SAXException, IOException, XpathException { + assertXpathValuesEqual(controlXpath, testXpath, + XMLUnit.buildControlDocument(document)); + } + + /** + * Assert that the evaluation of two Xpaths in the same XML string are + * equal + * @param xpathOne + * @param xpathTwo * @param inXMLString * @throws SAXException * @throws IOException @@ -491,6 +632,26 @@ /** * Assert that the evaluation of two Xpaths in two XML strings are equal * @param xpathOne + * @param control + * @param xpathTwo + * @param test + * @throws SAXException + * @throws IOException + */ + public static void assertXpathValuesEqual(String controlXpath, + InputSource control, + String testXpath, + InputSource test) + throws SAXException, IOException, XpathException { + assertXpathValuesEqual(controlXpath, + XMLUnit.buildControlDocument(control), + testXpath, + XMLUnit.buildTestDocument(test)); + } + + /** + * Assert that the evaluation of two Xpaths in two XML strings are equal + * @param xpathOne * @param inControlXMLString * @param xpathTwo * @param inTestXMLString @@ -531,6 +692,23 @@ * NOT equal * @param xpathOne * @param xpathTwo + * @param control + * @throws SAXException + * @throws IOException + */ + public static void assertXpathValuesNotEqual(String controlXpath, + String testXpath, + InputSource control) + throws SAXException, IOException, XpathException { + assertXpathValuesNotEqual(controlXpath, testXpath, + XMLUnit.buildControlDocument(control)); + } + + /** + * Assert that the evaluation of two Xpaths in the same XML string are + * NOT equal + * @param xpathOne + * @param xpathTwo * @param inXMLString * @throws SAXException * @throws IOException @@ -562,10 +740,30 @@ * Assert that the evaluation of two Xpaths in two XML strings are * NOT equal * @param xpathOne + * @param control + * @param xpathTwo + * @param test + * @throws SAXException + * @throws IOException + */ + public static void assertXpathValuesNotEqual(String controlXpath, + InputSource control, + String testXpath, + InputSource test) + throws SAXException, IOException, XpathException { + assertXpathValuesNotEqual(controlXpath, + XMLUnit.buildControlDocument(control), + testXpath, + XMLUnit.buildTestDocument(test)); + } + + /** + * Assert that the evaluation of two Xpaths in two XML strings are + * NOT equal + * @param xpathOne * @param inControlXMLString * @param xpathTwo * @param inTestXMLString - * @param ctx * @throws SAXException * @throws IOException */ @@ -608,6 +806,24 @@ } /** + * Assert the value of an Xpath expression in an XML document. + * @param expectedValue + * @param xpathExpression + * @param control + * @throws SAXException + * @throws IOException + * @see XpathEngine which provides the underlying evaluation mechanism + */ + public static void assertXpathEvaluatesTo(String expectedValue, + String xpathExpression, + InputSource control) + throws SAXException, IOException, + XpathException { + Document document = XMLUnit.buildControlDocument(control); + assertXpathEvaluatesTo(expectedValue, xpathExpression, document); + } + + /** * Assert the value of an Xpath expression in an XML String * @param expectedValue * @param xpathExpression @@ -644,6 +860,19 @@ /** * Assert that a specific XPath exists in some given XML * @param inXpathExpression + * @param control + * @see XpathEngine which provides the underlying evaluation mechanism + */ + public static void assertXpathExists(String xPathExpression, + InputSource control) + throws IOException, SAXException, XpathException { + Document inDocument = XMLUnit.buildControlDocument(control); + assertXpathExists(xPathExpression, inDocument); + } + + /** + * Assert that a specific XPath exists in some given XML + * @param inXpathExpression * @param inXMLString * @see XpathEngine which provides the underlying evaluation mechanism */ @@ -674,6 +903,19 @@ /** * Assert that a specific XPath does NOT exist in some given XML * @param inXpathExpression + * @param control + * @see XpathEngine which provides the underlying evaluation mechanism + */ + public static void assertXpathNotExists(String xPathExpression, + InputSource control) + throws IOException, SAXException, XpathException { + Document inDocument = XMLUnit.buildControlDocument(control); + assertXpathNotExists(xPathExpression, inDocument); + } + + /** + * Assert that a specific XPath does NOT exist in some given XML + * @param inXpathExpression * @param inXMLString * @see XpathEngine which provides the underlying evaluation mechanism */ @@ -702,6 +944,19 @@ } /** + * Assert that an InputSource containing XML contains valid XML: + * the document must contain a DOCTYPE declaration to be validated + * @param xml + * @throws SAXException + * @throws ConfigurationException if validation could not be turned on + * @see Validator + */ + public static void assertXMLValid(InputSource xml) + throws SAXException, ConfigurationException { + assertXMLValid(new Validator(xml)); + } + + /** * Assert that a String containing XML contains valid XML: the String must * contain a DOCTYPE declaration to be validated * @param xmlString @@ -711,10 +966,25 @@ */ public static void assertXMLValid(String xmlString) throws SAXException, ConfigurationException { - assertXMLValid(new Validator(new StringReader(xmlString))); + assertXMLValid(new Validator(xmlString)); } /** + * Assert that an InputSource containing XML contains valid XML: + * the document must contain a DOCTYPE to be validated, but the + * validation will use the systemId to obtain the DTD + * @param xml + * @param systemId + * @throws SAXException + * @throws ConfigurationException if validation could not be turned on + * @see Validator + */ + public static void assertXMLValid(InputSource xml, String systemId) + throws SAXException, ConfigurationException { + assertXMLValid(new Validator(xml, systemId)); + } + + /** * Assert that a String containing XML contains valid XML: the String must * contain a DOCTYPE to be validated, but the validation will use the * systemId to obtain the DTD @@ -726,10 +996,28 @@ */ public static void assertXMLValid(String xmlString, String systemId) throws SAXException, ConfigurationException { - assertXMLValid(new Validator(new StringReader(xmlString), systemId)); + assertXMLValid(new Validator(xmlString, systemId)); } /** + * Assert that a piece of XML contains valid XML: the document + * will be given a DOCTYPE to be validated with the name and + * systemId specified regardless of whether it already contains a + * doctype declaration. + * @param xml + * @param systemId + * @param doctype + * @throws SAXException + * @throws ConfigurationException if validation could not be turned on + * @see Validator + */ + public static void assertXMLValid(InputSource xml, String systemId, + String doctype) + throws SAXException, ConfigurationException { + assertXMLValid(new Validator(xml, systemId, doctype)); + } + + /** * Assert that a String containing XML contains valid XML: the String will * be given a DOCTYPE to be validated with the name and systemId specified * regardless of whether it already contains a doctype declaration. @@ -756,6 +1044,25 @@ /** * Execute a <code>NodeTest<code> for a single node type * and assert that it passes + * @param xml XML to be tested + * @param tester The test strategy + * @param nodeType The node type to be tested: constants defined + * in {@link Node org.w3c.dom.Node} e.g. <code>Node.ELEMENT_NODE</code> + * @throws SAXException + * @throws IOException + * @see AbstractNodeTester + * @see CountingNodeTester + */ + public static void assertNodeTestPasses(InputSource xml, NodeTester tester, + short nodeType) + throws SAXException, IOException { + NodeTest test = new NodeTest(xml); + assertNodeTestPasses(test, tester, new short[] {nodeType}, true); + } + + /** + * Execute a <code>NodeTest<code> for a single node type + * and assert that it passes * @param xmlString XML to be tested * @param tester The test strategy * @param nodeType The node type to be tested: constants defined Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLTestCase.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLTestCase.java 2007-03-28 04:06:22 UTC (rev 158) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLTestCase.java 2007-03-28 04:07:35 UTC (rev 159) @@ -45,6 +45,7 @@ import junit.framework.TestCase; import org.w3c.dom.Document; +import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -105,6 +106,19 @@ } /** + * Compare XML documents provided by two InputSource classes + * @param control Control document + * @param test Document to test + * @return Diff object describing differences in documents + * @throws SAXException + * @throws IOException + */ + public Diff compareXML(InputSource control, InputSource test) + throws SAXException, IOException { + return XMLUnit.compareXML(control, test); + } + + /** * Compare XML documents provided by two Reader classes * @param control Control document * @param test Document to test @@ -233,6 +247,18 @@ * @throws SAXException * @throws IOException */ + public void assertXMLEqual(InputSource control, InputSource test) + throws SAXException, IOException { + XMLAssert.assertXMLEqual(control, test); + } + + /** + * Assert that two XML documents are similar + * @param control XML to be compared against + * @param test XML to be tested + * @throws SAXException + * @throws IOException + */ public void assertXMLEqual(String control, String test) throws SAXException, IOException { XMLAssert.assertXMLEqual(control, test); @@ -277,7 +303,21 @@ * @param err Message to be displayed on assertion failure * @param control XML to be compared against * @param test XML to be tested + * @throws SAXException + * @throws IOException */ + public void assertXMLEqual(String err, InputSource control, + InputSource test) + throws SAXException, IOException { + XMLAssert.assertXMLEqual(err, control, test); + } + + /** + * Assert that two XML documents are similar + * @param err Message to be displayed on assertion failure + * @param control XML to be compared against + * @param test XML to be tested + */ public void assertXMLEqual(String err, Document control, Document test) { XMLAssert.assertXMLEqual(err, control, test); } @@ -302,22 +342,21 @@ * @throws SAXException * @throws IOException */ - public void assertXMLNotEqual(String control, String test) + public void assertXMLNotEqual(InputSource control, InputSource test) throws SAXException, IOException { XMLAssert.assertXMLNotEqual(control, test); } /** * Assert that two XML documents are NOT similar - * @param err Message to be displayed on assertion failure * @param control XML to be compared against * @param test XML to be tested * @throws SAXException * @throws IOException */ - public void assertXMLNotEqual(String err, String control, String test) + public void assertXMLNotEqual(String control, String test) throws SAXException, IOException { - XMLAssert.assertXMLNotEqual(err, control, test); + XMLAssert.assertXMLNotEqual(control, test); } /** @@ -331,24 +370,41 @@ /** * Assert that two XML documents are NOT similar + * @param control XML to be compared against + * @param test XML to be tested + * @throws SAXException + * @throws IOException + */ + public void assertXMLNotEqual(Reader control, Reader test) + throws SAXException, IOException { + XMLAssert.assertXMLNotEqual(control, test); + } + + /** + * Assert that two XML documents are NOT similar * @param err Message to be displayed on assertion failure * @param control XML to be compared against * @param test XML to be tested + * @throws SAXException + * @throws IOException */ - public void assertXMLNotEqual(String err, Document control, Document test) { + public void assertXMLNotEqual(String err, InputSource control, + InputSource test) + throws SAXException, IOException { XMLAssert.assertXMLNotEqual(err, control, test); } /** * Assert that two XML documents are NOT similar + * @param err Message to be displayed on assertion failure * @param control XML to be compared against * @param test XML to be tested * @throws SAXException * @throws IOException */ - public void assertXMLNotEqual(Reader control, Reader test) + public void assertXMLNotEqual(String err, String control, String test) throws SAXException, IOException { - XMLAssert.assertXMLNotEqual(control, test); + XMLAssert.assertXMLNotEqual(err, control, test); } /** @@ -356,6 +412,16 @@ * @param err Message to be displayed on assertion failure * @param control XML to be compared against * @param test XML to be tested + */ + public void assertXMLNotEqual(String err, Document control, Document test) { + XMLAssert.assertXMLNotEqual(err, control, test); + } + + /** + * Assert that two XML documents are NOT similar + * @param err Message to be displayed on assertion failure + * @param control XML to be compared against + * @param test XML to be tested * @throws SAXException * @throws IOException */ @@ -372,6 +438,19 @@ * @see XpathEngine */ public void assertXpathsEqual(String controlXpath, String testXpath, + InputSource document) + throws SAXException, IOException, XpathException { + XMLAssert.assertXpathsEqual(controlXpath, testXpath, document); + } + + /** + * Assert that the node lists of two Xpaths in the same document are equal + * @param xpathOne + * @param xpathTwo + * @param document + * @see XpathEngine + */ + public void assertXpathsEqual(String controlXpath, String testXpath, Document document) throws XpathException { XMLAssert.assertXpathsEqual(controlXpath, testXpath, document); @@ -393,6 +472,22 @@ } /** + * Assert that the node lists of two Xpaths in two XML pieces are equal + * @param xpathOne + * @param control + * @param xpathTwo + * @param test + * @throws SAXException + * @throws IOException + */ + public void assertXpathsEqual(String controlXpath, InputSource control, + String testXpath, InputSource test) + throws SAXException, IOException, XpathException { + XMLAssert.assertXpathsEqual(controlXpath, control, + testXpath, test); + } + + /** * Assert that the node lists of two Xpaths in two XML strings are equal * @param xpathOne * @param inControlXMLString @@ -439,6 +534,21 @@ } /** + * Assert that the node lists of two Xpaths in the same XML are NOT + * equal + * @param xpathOne + * @param xpathTwo + * @param control + * @throws SAXException + * @throws IOException + */ + public void assertXpathsNotEqual(String controlXpath, String testXpath, + InputSource control) + throws SAXException, IOException, XpathException { + XMLAssert.assertXpathsNotEqual(controlXpath, testXpath, control); + } + + /** * Assert that the node lists of two Xpaths in the same XML string are NOT * equal * @param xpathOne @@ -455,6 +565,22 @@ } /** + * Assert that the node lists of two Xpaths in two pieces of XML + * are NOT equal + * @param xpathOne + * @param control + * @param xpathTwo + * @param test + * @throws SAXException + * @throws IOException + */ + public void assertXpathsNotEqual(String controlXpath, InputSource control, + String testXpath, InputSource test) + throws SAXException, IOException, XpathException { + XMLAssert.assertXpathsNotEqual(controlXpath, control, testXpath, test); + } + + /** * Assert that the node lists of two Xpaths in two XML strings are NOT equal * @param xpathOne * @param inControlXMLString @@ -501,6 +627,21 @@ } /** + * Assert that the evaluation of two Xpaths in the same XML are + * equal + * @param xpathOne + * @param xpathTwo + * @param control + * @throws SAXException + * @throws IOException + */ + public void assertXpathValuesEqual(String controlXpath, String testXpath, + InputSource control) + throws SAXException, IOException, XpathException { + XMLAssert.assertXpathValuesEqual(controlXpath, testXpath, control); + } + + /** * Assert that the evaluation of two Xpaths in the same XML string are * equal * @param xpathOne @@ -519,6 +660,24 @@ /** * Assert that the evaluation of two Xpaths in two XML strings are equal * @param xpathOne + * @param control + * @param xpathTwo + * @param test + * @throws SAXException + * @throws IOException + */ + public void assertXpathValuesEqual(String controlXpath, + InputSource control, + String testXpath, + InputSource test) + throws SAXException, IOException, XpathException { + XMLAssert.assertXpathValuesEqual(controlXpath, control, + testXpath, test); + } + + /** + * Assert that the evaluation of two Xpaths in two XML strings are equal + * @param xpathOne * @param inControlXMLString * @param xpathTwo * @param inTestXMLString @@ -555,6 +714,23 @@ * NOT equal * @param xpathOne * @param xpathTwo + * @param control + * @throws SAXException + * @throws IOException + */ + public void assertXpathValuesNotEqual(String controlXpath, + String testXpath, + InputSource control) + throws SAXException, IOException, XpathException { + XMLAssert.assertXpathValuesNotEqual(controlXpath, testXpath, + control); + } + + /** + * Assert that the evaluation of two Xpaths in the same XML string are + * NOT equal + * @param xpathOne + * @param xpathTwo * @param inXMLString * @throws SAXException * @throws IOException @@ -584,6 +760,25 @@ * Assert that the evaluation of two Xpaths in two XML strings are * NOT equal * @param xpathOne + * @param control + * @param xpathTwo + * @param test + * @throws SAXException + * @throws IOException + */ + public void assertXpathValuesNotEqual(String controlXpath, + InputSource control, + String testXpath, + InputSource test) + throws SAXException, IOException, XpathException { + XMLAssert.assertXpathValuesNotEqual(controlXpath, control, + testXpath, test); + } + + /** + * Assert that the evaluation of two Xpaths in two XML strings are + * NOT equal + * @param xpathOne * @param inControlXMLString * @param xpathTwo * @param inTestXMLString @@ -620,6 +815,23 @@ * Assert the value of an Xpath expression in an XML String * @param expectedValue * @param xpathExpression + * @param control + * @throws SAXException + * @throws IOException + * @see XpathEngine which provides the underlying evaluation mechanism + */ + public void assertXpathEvaluatesTo(String expectedValue, + String xpathExpression, + InputSource control) + throws SAXException, IOException, XpathException { + XMLAssert.assertXpathEvaluatesTo(expectedValue, xpathExpression, + control); + } + + /** + * Assert the value of an Xpath expression in an XML String + * @param expectedValue + * @param xpathExpression * @param inXMLString * @throws SAXException * @throws IOException @@ -653,8 +865,19 @@ /** * Assert that a specific XPath exists in some given XML * @param inXpathExpression + * @param xml + * @see XpathEngine which provides the underlying evaluation mechanism + */ + public void assertXpathExists(String xPathExpression, + InputSource xml) + throws IOException, SAXException, XpathException { + XMLAssert.assertXpathExists(xPathExpression, xml); + } + + /** + * Assert that a specific XPath exists in some given XML + * @param inXpathExpression * @param inXMLString - * @param ctx * @see XpathEngine which provides the underlying evaluation mechanism */ public void assertXpathExists(String xPathExpression, @@ -678,6 +901,18 @@ /** * Assert that a specific XPath does NOT exist in some given XML * @param inXpathExpression + * @param xml + * @see XpathEngine which provides the underlying evaluation mechanism + */ + public void assertXpathNotExists(String xPathExpression, + InputSource xml) + throws IOException, SAXException, XpathException { + XMLAssert.assertXpathNotExists(xPathExpression, xml); + } + + /** + * Assert that a specific XPath does NOT exist in some given XML + * @param inXpathExpression * @param inXMLString * @see XpathEngine which provides the underlying evaluation mechanism */ @@ -724,6 +959,19 @@ } /** + * Assert that a piece of XML contains valid XML: the input must + * contain a DOCTYPE declaration to be validated + * @param xml + * @throws SAXException + * @throws ConfigurationException if validation could not be turned on + * @see Validator + */ + public void assertXMLValid(InputSource xml) + throws SAXException, ConfigurationException { + XMLAssert.assertXMLValid(xml); + } + + /** * Assert that a String containing XML contains valid XML: the String must * contain a DOCTYPE declaration to be validated * @param xmlString @@ -737,6 +985,21 @@ } /** + * Assert that a piece of XML contains valid XML: the document must + * contain a DOCTYPE to be validated, but the validation will use the + * systemId to obtain the DTD + * @param xml + * @param systemId + * @throws SAXException + * @throws ConfigurationException if validation could not be turned on + * @see Validator + */ + public void assertXMLValid(InputSource xml, String systemId) + throws SAXException, ConfigurationException { + XMLAssert.assertXMLValid(xml, systemId); + } + + /** * Assert that a String containing XML contains valid XML: the String must * contain a DOCTYPE to be validated, but the validation will use the * systemId to obtain the DTD @@ -752,6 +1015,24 @@ } /** + * Assert that a piece of XML contains valid XML: the document + * will be given a DOCTYPE to be validated with the name and + * systemId specified regardless of whether it already contains a + * doctype declaration. + * @param xml + * @param systemId + * @param doctype + * @throws SAXException + * @throws ConfigurationException if validation could not be turned on + * @see Validator + */ + public void assertXMLValid(InputSource xml, String systemId, + String doctype) + throws SAXException, ConfigurationException { + XMLAssert.assertXMLValid(xml, systemId, doctype); + } + + /** * Assert that a String containing XML contains valid XML: the String will * be given a DOCTYPE to be validated with the name and systemId specified * regardless of whether it already contains a doctype declaration. @@ -778,6 +1059,24 @@ /** * Execute a <code>NodeTest<code> for a single node type * and assert that it passes + * @param xml XML to be tested + * @param tester The test strategy + * @param nodeType The node type to be tested: constants defined + * in {@link Node org.w3c.dom.Node} e.g. <code>Node.ELEMENT_NODE</code> + * @throws SAXException + * @throws IOException + * @see AbstractNodeTester + * @see CountingNodeTester + */ + public void assertNodeTestPasses(InputSource xml, NodeTester tester, + short nodeType) + throws SAXException, IOException { + XMLAssert.assertNodeTestPasses(xml, tester, nodeType); + } + + /** + * Execute a <code>NodeTest<code> for a single node type + * and assert that it passes * @param xmlString XML to be tested * @param tester The test strategy * @param nodeType The node type to be tested: constants defined Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java 2007-03-28 04:06:22 UTC (rev 158) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java 2007-03-28 04:07:35 UTC (rev 159) @@ -507,6 +507,19 @@ return "1.1alpha"; } + /** + * Compare XML documents provided by two InputSource classes + * @param control Control document + * @param test Document to test + * @return Diff object describing differences in documents + * @throws SAXException + * @throws IOException + */ + public static Diff compareXML(InputSource control, InputSource test) + throws SAXException, IOException { + return new Diff(control, test); + } + /** * Compare XML documents provided by two Reader classes * @param control Control document Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Validator.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Validator.java 2007-03-28 04:06:22 UTC (rev 158) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Validator.java 2007-03-28 04:07:35 UTC (rev 159) @@ -39,10 +39,13 @@ import junit.framework.AssertionFailedError; import junit.framework.TestSuite; import org.w3c.dom.Document; +import org.xml.sax.InputSource; import java.io.File; +import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; +import java.io.StringBufferInputStream; import java.io.StringReader; /** @@ -56,15 +59,18 @@ public void testXSchema() throws Exception{ File xsdFile = new File(test_Constants.BASEDIR + "/tests/etc/Book.xsd"); - assertTrue("xsdFile " + xsdFile.getAbsolutePath() + " exists", xsdFile.exists()); + assertTrue("xsdFile " + xsdFile.getAbsolutePath() + " exists", + xsdFile.exists()); - File xmlFile = new File(test_Constants.BASEDIR + "/tests/etc/BookXsdGenerated.xml"); - assertTrue("xmlFile " + xmlFile.getAbsolutePath() + " exists", xmlFile.exists()); - validator = new Validator(new FileReader(xmlFile)); + File xmlFile = new File(test_Constants.BASEDIR + + "/tests/etc/BookXsdGenerated.xml"); + assertTrue("xmlFile " + xmlFile.getAbsolutePath() + " exists", + xmlFile.exists()); + validator = + new Validator(new InputSource(new FileInputStream(xmlFile))); validator.useXMLSchema(true); - - validator.assertIsValid(); + assertTrue("Schema " + validator.toString(), validator.isValid()); } public void testIsValidGood() throws Exception { @@ -72,8 +78,7 @@ + test_Constants.CHUCK_JONES_RIP_DTD_DECL + test_Constants.CHUCK_JONES_RIP_XML; validator = new Validator(new StringReader(toonXML)); - assertEquals("toonXML " + validator.toString(), - true, validator.isValid()); + assertTrue("toonXML " + validator.toString(), validator.isValid()); // test XMLTestCase passXMLTestCaseTest(toonXML); passXMLTestCaseTest(validator); @@ -90,7 +95,7 @@ public void testIsValidExternalSystemId() throws Exception { writeTempDTDFile(); - assertEquals(tempDTDFile.getAbsolutePath(), true, tempDTDFile.exists()); + assertTrue(tempDTDFile.getAbsolutePath(), tempDTDFile.exists()); String externalDTD = test_Constants.XML_DECLARATION + test_Constants.DOCUMENT_WITH_GOOD_EXTERNAL_DTD; @@ -98,8 +103,7 @@ validator = new Validator(new StringReader(externalDTD), tempDTDUrl); - assertEquals("externalDTD " + validator.toString(), - true, validator.isValid()); + assertTrue("externalDTD " + validator.toString(), validator.isValid()); // test XMLTestCase passXMLTestCaseTest(externalDTD, tempDTDFile.toURL().toExternalForm()); passXMLTestCaseTest(validator); @@ -109,8 +113,7 @@ validator = new Validator(new StringReader(noDTD), tempDTDFile.toURL().toExternalForm()); - assertEquals("noDTD " + validator.toString(), - false, validator.isValid()); + assertFalse("noDTD " + validator.toString(), validator.isValid()); // test XMLTestCase failXMLTestCaseTest(noDTD, tempDTDFile.toURL().toExternalForm()); failXMLTestCaseTest(validator); @@ -118,7 +121,7 @@ public void testIsValidNoDTD() throws Exception { writeTempDTDFile(); - assertEquals(tempDTDFile.getAbsolutePath(), true, tempDTDFile.exists()); + assertTrue(tempDTDFile.getAbsolutePath(), tempDTDFile.exists()); String noDTD = test_Constants.CHUCK_JONES_RIP_XML; String systemid = tempDTDFile.toURL().toExternalForm(); @@ -126,39 +129,33 @@ String notDoctype = "anima"; validator = new Validator(new StringReader(noDTD), systemid, doctype); - assertEquals(validator.toString(), true, validator.isValid()); + assertTrue(validator.toString(), validator.isValid()); // test XMLTestCase passXMLTestCaseTest(noDTD, systemid, doctype); passXMLTestCaseTest(validator); + // and Document constructor + Document document = getDocument(noDTD); + validator = new Validator(document, systemid, doctype); + assertTrue("Document " + validator.toString(), validator.isValid()); validator = new Validator(new StringReader(noDTD), systemid, notDoctype); - assertEquals(validator.toString(), false, validator.isValid()); + assertFalse(validator.toString(), validator.isValid()); // test XMLTestCase failXMLTestCaseTest(noDTD, systemid, notDoctype); failXMLTestCaseTest(validator); - - Document document = getDocument(noDTD); - validator = new Validator(document, systemid, doctype); - assertEquals("Document " + validator.toString(), - true, validator.isValid()); - // test XMLTestCase - passXMLTestCaseTest(validator); - + // and Document constructor validator = new Validator(document, systemid, notDoctype); - assertEquals("Document " + validator.toString(), - false, validator.isValid()); - // test XMLTestCase - failXMLTestCaseTest(validator); + assertFalse("Document " + validator.toString(), validator.isValid()); } public void testIsValidBad() throws Exception { String noDTD = test_Constants.XML_DECLARATION + test_Constants.CHUCK_JONES_RIP_XML; validator = new Validator(new StringReader(noDTD)); - assertEquals("noDTD " + validator.toString(), - false, validator.isValid()); + assertFalse("noDTD " + validator.toString(), validator.isValid()); // test XMLTestCase + failXMLTestCaseTest(noDTD); failXMLTestCaseTest(validator); String dtdTwice = test_Constants.XML_DECLARATION @@ -166,18 +163,18 @@ + test_Constants.CHUCK_JONES_RIP_DTD_DECL + test_Constants.CHUCK_JONES_RIP_XML; validator = new Validator(new StringReader(dtdTwice)); - assertEquals("dtdTwice " + validator.toString(), - false, validator.isValid()); + assertFalse("dtdTwice " + validator.toString(), validator.isValid()); // test XMLTestCase + failXMLTestCaseTest(dtdTwice); failXMLTestCaseTest(validator); String invalidXML = test_Constants.XML_DECLARATION + test_Constants.CHUCK_JONES_RIP_DTD_DECL + test_Constants.CHUCK_JONES_SPINNING_IN_HIS_GRAVE_XML; validator = new Validator(new StringReader(invalidXML)); - assertEquals("invalidXML " + validator.toString(), - false, validator.isValid()); + assertFalse("invalidXML " + validator.toString(), validator.isValid()); // test XMLTestCase + failXMLTestCaseTest(invalidXML); failXMLTestCaseTest(validator); } @@ -209,13 +206,22 @@ // ---- XMLTestCase methods ---- private void passXMLTestCaseTest(String xml) throws Exception { assertXMLValid(xml); + assertXMLValid(new InputSource(new StringReader(xml))); + assertXMLValid(new InputSource(new StringBufferInputStream(xml))); } private void passXMLTestCaseTest(String xml, String systemId) throws Exception { assertXMLValid(xml, systemId); + assertXMLValid(new InputSource(new StringReader(xml)), systemId); + assertXMLValid(new InputSource(new StringBufferInputStream(xml)), + systemId); } private void passXMLTestCaseTest(String xml, String systemId, String doctype) throws Exception { assertXMLValid(xml, systemId, doctype); + assertXMLValid(new InputSource(new StringReader(xml)), systemId, + doctype); + assertXMLValid(new InputSource(new StringBufferInputStream(xml)), + systemId, doctype); } private void passXMLTestCaseTest(Validator validator) throws Exception { assertXMLValid(validator); @@ -227,7 +233,40 @@ } catch (AssertionFailedError e) { // expecting this } + try { + assertXMLValid(new InputSource(new StringReader(xml)), systemId); + fail("Expected assertion to fail!"); + } catch (AssertionFailedError e) { + // expecting this + } + try { + assertXMLValid(new InputSource(new StringBufferInputStream(xml)), + systemId); + fail("Expected assertion to fail!"); + } catch (AssertionFailedError e) { + // expecting this + } } + private void failXMLTestCaseTest(String xml) throws Exception { + try { + assertXMLValid(xml); + fail("Expected assertion to fail!"); + } catch (AssertionFailedError e) { + // expecting this + } + try { + assertXMLValid(new InputSource(new StringReader(xml))); + fail("Expected assertion to fail!"); + } catch (AssertionFailedError e) { + // expecting this + } + try { + assertXMLValid(new InputSource(new StringBufferInputStream(xml))); + fail("Expected assertion to fail!"); + } catch (AssertionFailedError e) { + // expecting this + } + } private void failXMLTestCaseTest(String xml, String systemId, String doctype) throws Exception { try { @@ -236,6 +275,20 @@ } catch (AssertionFailedError e) { // expecting this } + try { + assertXMLValid(new InputSource(new StringReader(xml)), systemId, + doctype); + fail("Expected assertion to fail!"); + } catch (AssertionFailedError e) { + // expecting this + } + try { + assertXMLValid(new InputSource(new StringBufferInputStream(xml)), + systemId, doctype); + fail("Expected assertion to fail!"); + } catch (AssertionFailedError e) { + // expecting this + } } private void failXMLTestCaseTest(Validator validator) throws Exception { try { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-03-28 16:19:24
|
Revision: 161 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=161&view=rev Author: bodewig Date: 2007-03-28 09:19:23 -0700 (Wed, 28 Mar 2007) Log Message: ----------- I know this fails for some documents with DOCTYPEs, commit it now anyway: refactor Validator support for InputStreams Modified Paths: -------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeReader.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/Validator.java Added Paths: ----------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeConstants.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeInputStream.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeSupport.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DoctypeInputStream.java Added: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeConstants.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeConstants.java (rev 0) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeConstants.java 2007-03-28 16:19:23 UTC (rev 161) @@ -0,0 +1,45 @@ +/* +****************************************************************** +Copyright (c) 2001, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit; + +interface DoctypeConstants { + String DOCTYPE_OPEN_DECL = "<!"; + int DECL_LENGTH = DOCTYPE_OPEN_DECL.length(); + String DOCTYPE_CLOSE_DECL = ">"; + String DOCTYPE = "DOCTYPE "; + String SYSTEM = " SYSTEM \""; +} \ No newline at end of file Property changes on: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeConstants.java ___________________________________________________________________ Name: svn:executable + * Name: svn:eol-style + native Added: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeInputStream.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeInputStream.java (rev 0) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeInputStream.java 2007-03-28 16:19:23 UTC (rev 161) @@ -0,0 +1,216 @@ +/* +****************************************************************** +Copyright (c) 2001, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.IOException; + +/** + * Adapts the marked-up content in a source InputStream to specify that it + * conforms to a different DTD. + * Combines InputStream semantics with the ability to specify a target doctype + * for a byte stream containing XML markup. + * Used by Validator class to wrap an InputStrea, when performing validation of a + * document against a DTD. + * <br />Examples and more at <a href="http://xmlunit.sourceforge.net"/>xmlunit.sourceforge.net</a> + */ +public class DoctypeInputStream extends InputStream { + private final InputStream wrappedStream; + + private static final byte[] DOCTYPE_BYTES = { + 'D', 'O', 'C', 'T', 'Y', 'P', 'E', ' ' + }; + + private byte[] readAheadBeforeDeclBuffer = null; + private int readAheadBeforeDeclOffset = 0; + private byte[] readAheadAfterDeclBuffer = null; + private int readAheadAfterDeclOffset = 0; + + private final DoctypeSupport docType; + private boolean writeDecl = false; + + + /** + * Create an InputStream whose XML content is provided by the + * originalSource with the exception of the DOCTYPE which is + * provided by the doctypeName and systemID. + * @param originalSource + * @param doctypeName + * @param systemID + */ + public DoctypeInputStream(InputStream originalSource, String doctypeName, + String systemID) { + wrappedStream = originalSource instanceof BufferedInputStream + ? originalSource : new BufferedInputStream(originalSource); + docType = new DoctypeSupport(doctypeName, systemID); + } + + /** + * Read DOCTYPE-replaced content from the wrapped Reader + */ + public int read() throws IOException { + int nextByte = -1; + + if (writeDecl) { + // currently writing our own DOCTYPE declaration + nextByte = docType.read(); + if (nextByte == -1) { + writeDecl = false; + } else { + return nextByte; + } + } + + if (readAheadBeforeDeclBuffer != null) { + // in part of original document before our DOCTYPE - this + // has already been read + nextByte = readAheadBeforeDeclBuffer[readAheadBeforeDeclOffset++]; + if (readAheadBeforeDeclOffset >= readAheadBeforeDeclBuffer.length) { + readAheadBeforeDeclBuffer = null; + writeDecl = true; + } + } else if (!docType.hasBeenRead()) { + // DOCTYPE not written, yet, need to see where it should go + + // read ahead until we find a good place to insert the doctype, + // store bytes in readAheadBuffers + ByteArrayOutputStream beforeDecl = new ByteArrayOutputStream(); + ByteArrayOutputStream afterDecl = new ByteArrayOutputStream(); + int current; + boolean ready = false; + while (!ready && (current = wrappedStream.read()) != -1) { + byte c = (byte) current; + if (c >= 0 && Character.isWhitespace((char) c)) { + beforeDecl.write(c); + } else if (c == '<') { + // could be XML declaration, comment, PI, DOCTYPE + // or the first element + byte[] elementOrDeclOr = readUntilCloseCharacterIsReached(); + if (elementOrDeclOr.length > 0) { + if (elementOrDeclOr[0] == '?') { + // XML declaration or PI + beforeDecl.write('<'); + beforeDecl.write(elementOrDeclOr, 0, + elementOrDeclOr.length); + } else if (elementOrDeclOr[0] != '!') { + // first element + afterDecl.write('<'); + afterDecl.write(elementOrDeclOr, 0, + elementOrDeclOr.length); + ready = true; + } else { + // comment or doctype + if (indexOfDoctype(elementOrDeclOr) == -1) { + afterDecl.write('<'); + afterDecl.write(elementOrDeclOr, 0, + elementOrDeclOr.length); + } // else swallow old declaration + ready = true; + } + } + + } else { + afterDecl.write(c); + ready = true; + } + } + readAheadBeforeDeclBuffer = beforeDecl.size() > 0 + ? beforeDecl.toByteArray() : null; + readAheadAfterDeclBuffer = afterDecl.size() > 0 + ? afterDecl.toByteArray() : null; + writeDecl = (readAheadBeforeDeclBuffer == null); + return read(); + } else if (readAheadAfterDeclBuffer != null) { + // in part of original document read ahead after our DOCTYPE + nextByte = readAheadAfterDeclBuffer[readAheadAfterDeclOffset++]; + if (readAheadAfterDeclOffset >= readAheadAfterDeclBuffer.length) { + readAheadAfterDeclBuffer = null; + } + } else { + nextByte = wrappedStream.read(); + } + return nextByte; + } + + private byte[] readUntilCloseCharacterIsReached() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + int byteRead = -1; + int openCount = 1; + while (openCount > 0 && (byteRead = wrappedStream.read()) != -1) { + byte c = (byte) byteRead; + baos.write(c); + if (c == '<') { + openCount++; + } + if (c == '>') { + openCount--; + } + } + return baos.toByteArray(); + } + + public void close() throws IOException { + wrappedStream.close(); + } + + /** + * Could be faster when searching from the other end, but should do. + */ + private static int indexOfDoctype(byte[] b) { + int index = -1; + for (int i = 0; i < b.length - DOCTYPE_BYTES.length + 1; i++) { + if (b[i] == DOCTYPE_BYTES[0]) { + boolean found = false; + int j = 1; + for (; !found && j < DOCTYPE_BYTES.length; j++) { + if (b[i + j] != DOCTYPE_BYTES[j]) { + found = true; + } + } + if (found) { + index = i; + break; + } else { + i += j - 1; + } + } + } + return index; + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeInputStream.java ___________________________________________________________________ Name: svn:executable + * Name: svn:eol-style + native Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeReader.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeReader.java 2007-03-28 04:10:28 UTC (rev 160) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeReader.java 2007-03-28 16:19:23 UTC (rev 161) @@ -38,10 +38,7 @@ import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; import java.io.Reader; -import java.io.StringReader; /** * Adapts the marked-up content in a source Reader to specify that it @@ -52,19 +49,19 @@ * document against a DTD. * <br />Examples and more at <a href="http://xmlunit.sourceforge.net"/>xmlunit.sourceforge.net</a> */ -public class DoctypeReader extends Reader { - private static final String DOCTYPE_OPEN_DECL = "<!"; - private static final int DECL_LENGTH = DOCTYPE_OPEN_DECL.length(); - private static final String DOCTYPE_CLOSE_DECL = ">"; - private static final String DOCTYPE = "DOCTYPE "; - private static final String SYSTEM = " SYSTEM \""; - private final Reader originalSource; +public class DoctypeReader extends Reader implements DoctypeConstants { + + private final Reader originalReader; private final StringBuffer sourceBuffer = new StringBuffer(1024); - private final String doctypeName; - private final String systemId; - private Reader replacementReader; + private char[] readAheadBeforeDeclBuffer = null; + private int readAheadBeforeDeclOffset = 0; + private char[] readAheadAfterDeclBuffer = null; + private int readAheadAfterDeclOffset = 0; + private final DoctypeSupport docType; + private boolean writeDecl = false; + /** * Create a Reader whose XML content is provided by the originalSource with * the exception of the DOCTYPE which is provided by the doctypeName @@ -75,44 +72,20 @@ */ public DoctypeReader(Reader originalSource, String doctypeName, String systemID) { - this.originalSource = originalSource; - this.doctypeName = doctypeName; - this.systemId = systemID; + originalReader = originalSource instanceof BufferedReader + ? originalSource : new BufferedReader(originalSource); + docType = new DoctypeSupport(doctypeName, systemID); } /** - * Create a Reader whose XML content is provided by the originalSource with - * the exception of the DOCTYPE which is provided by the doctypeName - * and systemID. - * @param originalSource - * @param doctypeName - * @param systemID - */ - public DoctypeReader(InputStream originalSource, String encoding, - String doctypeName, String systemID) - throws IOException { - this(encoding != null - ? new InputStreamReader(originalSource, encoding) - : xmlStreamToReader(originalSource), - doctypeName, systemID); - } - - // XXX - we are cheating here, we should read into the source - // stream to see whether the XML decl (if any) specifies the - // encoding and then return an InputStreamReader using the proper - // encoding - private static Reader xmlStreamToReader(InputStream originalSource) - throws IOException { - return new InputStreamReader(originalSource); - } - - /** * @return the content of the original source, without amendments or * substitutions. Safe to call multiple times. * @throws IOException if thrown while reading from the original source + * @deprecated this method is only here for BWC, it is no longer + * used by this class */ protected String getContent() throws IOException { - return getContent(originalSource).toString(); + return obsoleteGetContent(originalReader).toString(); } /** @@ -120,7 +93,8 @@ * @return the contents of the originalSource within a StringBuffer * @throws IOException if thrown while reading from the original source */ - private StringBuffer getContent(Reader originalSource) throws IOException { + private StringBuffer obsoleteGetContent(Reader originalSource) + throws IOException { if (sourceBuffer.length() == 0) { BufferedReader bufferedReader; if (originalSource instanceof BufferedReader) { @@ -152,7 +126,7 @@ * @param withinContent * @return */ - private int findStartDoctype(StringBuffer withinContent) { + private int obsoleteFindStartDoctype(StringBuffer withinContent) { int startAt = -1; char curChar; boolean canInsert = true; @@ -183,6 +157,8 @@ * @param doctypeName * @param systemId * @return the content, after DOCTYPE amendment / addition + * @deprecated this method is only here for BWC, it is no longer + * used by this class */ public String replaceDoctype(StringBuffer withinContent, String doctypeName, String systemId) { @@ -190,7 +166,7 @@ int startDoctype = content.indexOf(DOCTYPE); boolean noCurrentDoctype = false; if (startDoctype == -1) { - startDoctype = findStartDoctype(withinContent); + startDoctype = obsoleteFindStartDoctype(withinContent); noCurrentDoctype = true; } @@ -227,18 +203,6 @@ } /** - * Wrap the DOCTYPE-replaced content in a StringReader - * @return a StringReader from which the DOCTYPE-replaced content can be read - * @throws IOException - */ - private Reader getReplacementReader() throws IOException { - StringBuffer originalContent = getContent(originalSource); - String replacedContent = replaceDoctype(originalContent, - doctypeName, systemId); - return new StringReader(replacedContent); - } - - /** * Read DOCTYPE-replaced content from the wrapped Reader * @param cbuf * @param off @@ -248,17 +212,115 @@ * @throws IOException */ public int read(char cbuf[], int off, int len) throws IOException { - if (replacementReader == null) { - replacementReader = getReplacementReader(); + int startPos = off; + int currentlyRead; + while (off - startPos < len && (currentlyRead = read()) != -1) { + cbuf[off++] = (char) currentlyRead; } - return replacementReader.read(cbuf, off, len); + return off == startPos && len != 0 ? -1 : off - startPos; } /** - * Close the wrapped Reader - * @throws IOException + * Read DOCTYPE-replaced content from the wrapped Reader */ + public int read() throws IOException { + int nextChar = -1; + + if (writeDecl) { + // currently writing our own DOCTYPE declaration + nextChar = docType.read(); + if (nextChar == -1) { + writeDecl = false; + } else { + return nextChar; + } + } + + if (readAheadBeforeDeclBuffer != null) { + // in part of original document before our DOCTYPE - this + // has already been read + nextChar = readAheadBeforeDeclBuffer[readAheadBeforeDeclOffset++]; + if (readAheadBeforeDeclOffset >= readAheadBeforeDeclBuffer.length) { + readAheadBeforeDeclBuffer = null; + writeDecl = true; + } + } else if (!docType.hasBeenRead()) { + // DOCTYPE not written, yet, need to see where it should go + + // read ahead until we find a good place to insert the doctype, + // store characters in readAheadBuffers + StringBuffer beforeDecl = new StringBuffer(); + StringBuffer afterDecl = new StringBuffer(); + int current; + boolean ready = false; + while (!ready && (current = originalReader.read()) != -1) { + char c = (char) current; + if (Character.isWhitespace(c)) { + beforeDecl.append(c); + } else if (c == '<') { + // could be XML declaration, comment, PI, DOCTYPE + // or the first element + String elementOrDeclOr = readUntilCloseCharacterIsReached(); + if (elementOrDeclOr.length() > 0) { + if (elementOrDeclOr.charAt(0) == '?') { + // XML declaration or PI + beforeDecl.append('<').append(elementOrDeclOr); + } else if (elementOrDeclOr.charAt(0) != '!') { + // first element + afterDecl.append('<').append(elementOrDeclOr); + ready = true; + } else { + // comment or doctype + if (elementOrDeclOr.indexOf(DOCTYPE) == -1) { + afterDecl.append('<').append(elementOrDeclOr); + } // else swallow old declaration + ready = true; + } + } + + } else { + afterDecl.append(c); + ready = true; + } + } + readAheadBeforeDeclBuffer = beforeDecl.length() > 0 + ? beforeDecl.toString().toCharArray() + : null; + readAheadAfterDeclBuffer = afterDecl.length() > 0 + ? afterDecl.toString().toCharArray() + : null; + writeDecl = (readAheadBeforeDeclBuffer == null); + return read(); + } else if (readAheadAfterDeclBuffer != null) { + // in part of original document read ahead after our DOCTYPE + nextChar = readAheadAfterDeclBuffer[readAheadAfterDeclOffset++]; + if (readAheadAfterDeclOffset >= readAheadAfterDeclBuffer.length) { + readAheadAfterDeclBuffer = null; + } + } else { + nextChar = originalReader.read(); + } + return nextChar; + } + + private String readUntilCloseCharacterIsReached() throws IOException { + StringBuffer sb = new StringBuffer(); + int characterRead = -1; + int openCount = 1; + while (openCount > 0 && (characterRead = originalReader.read()) != -1) { + char c = (char) characterRead; + sb.append(c); + if (c == '<') { + openCount++; + } + if (c == '>') { + openCount--; + } + } + return sb.toString(); + } + public void close() throws IOException { - replacementReader.close(); + originalReader.close(); } } Added: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeSupport.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeSupport.java (rev 0) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeSupport.java 2007-03-28 16:19:23 UTC (rev 161) @@ -0,0 +1,74 @@ +/* +****************************************************************** +Copyright (c) 2001, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit; + +/** + * Contains some common code for DoctypeReader and DoctypeInputStream. + * + * <p>When used with DoctypeInputStream it assumes that the whole + * DOCTYPE declaration consists of US-ASCII characters.</p> + */ +final class DoctypeSupport implements DoctypeConstants { + + private final String decl; + private int offset = 0; + + /** + * Encapsulates a DOCTYPE declaration for the given name and system id. + */ + DoctypeSupport(String name, String systemId) { + StringBuffer sb = new StringBuffer(DOCTYPE_OPEN_DECL); + sb.append(DOCTYPE).append(name).append(SYSTEM) + .append(systemId).append("\"").append(DOCTYPE_CLOSE_DECL); + decl = sb.toString(); + } + + /** + * Whether anybody has started to read the declaration. + */ + boolean hasBeenRead() { + return offset != 0; + } + + /** + * Reads the next character from the declaration. + * @return -1 if the end of the declaration has been reached. + */ + int read() { + return offset >= decl.length() ? -1 : decl.charAt(offset++); + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeSupport.java ___________________________________________________________________ Name: svn:executable + * Name: svn:eol-style + native Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/Validator.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/Validator.java 2007-03-28 04:10:28 UTC (rev 160) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/Validator.java 2007-03-28 16:19:23 UTC (rev 161) @@ -251,14 +251,15 @@ */ public Validator(InputSource sourceForValidation, String systemID, String doctype) - throws SAXException, IOException, ConfigurationException { + throws SAXException, ConfigurationException { this(sourceForValidation.getCharacterStream() != null - ? new DoctypeReader(sourceForValidation.getCharacterStream(), - doctype, systemID) - : new DoctypeReader(sourceForValidation.getByteStream(), - sourceForValidation.getEncoding(), - doctype, systemID), - systemID); + ? new InputSource(new DoctypeReader(sourceForValidation + .getCharacterStream(), + doctype, systemID)) + : new InputSource(new DoctypeInputStream(sourceForValidation + .getByteStream(), + doctype, systemID)), + systemID, true); } /** @@ -380,8 +381,8 @@ isValid = Boolean.TRUE; } else if (usingDoctypeReader) { try { - messages.append("\nContent was: ").append(((DoctypeReader) - validationInputSource.getCharacterStream()).getContent()); + messages.append("\nContent was: ") + .append(readFully(validationInputSource)); } catch (IOException e) { // silent but deadly? } @@ -490,4 +491,31 @@ parser.setProperty(JAXPConstants.Properties.SCHEMA_SOURCE, schemaSource); } + + private static String readFully(InputSource s) throws IOException { + return s.getCharacterStream() != null + ? readFully(s.getCharacterStream()) : readFully(s.getByteStream()); + } + + private static String readFully(Reader r) throws IOException { + StringBuffer sb = new StringBuffer(); + char[] buffer = new char[4096]; + int charsRead = -1; + while ((charsRead = r.read(buffer)) > -1) { + sb.append(buffer, 0, charsRead); + } + return sb.toString(); + } + + private static String readFully(java.io.InputStream is) throws IOException { + java.io.ByteArrayOutputStream baos = + new java.io.ByteArrayOutputStream(); + byte[] buffer = new byte[8192]; + int bytesRead = -1; + while ((bytesRead = is.read(buffer)) > -1) { + baos.write(buffer, 0, bytesRead); + } + return new String(baos.toByteArray()); + } + } Added: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DoctypeInputStream.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DoctypeInputStream.java (rev 0) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DoctypeInputStream.java 2007-03-28 16:19:23 UTC (rev 161) @@ -0,0 +1,142 @@ +/* +****************************************************************** +Copyright (c) 200, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; + +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * JUnit test for DoctypeInputStream + */ +public class test_DoctypeInputStream extends TestCase { + + private static final String NEWLINE = System.getProperty("line.separator"); + private static final String NO_DTD = "<document><element>one</element></document>"; + private File testFile; + + public void tearDown() { + if (testFile != null) { + testFile.delete(); + } + } + + private FileInputStream testDocument(String content) + throws IOException { + testFile = File.createTempFile("xmlunit_", ".xml"); + FileOutputStream fos = new FileOutputStream(testFile); + OutputStreamWriter w = new OutputStreamWriter(fos, "ISO-8859-1"); + w.write(content); + w.close(); + + return new FileInputStream(testFile); + } + + private static String readFully(DoctypeInputStream dis) + throws IOException { + StringBuffer buf = new StringBuffer(); + char[] ch = new char[1024]; + int numChars; + InputStreamReader reader = + new InputStreamReader(dis, "ISO-8859-1"); + while ((numChars = reader.read(ch))!=-1) { + buf.append(ch, 0, numChars); + } + return buf.toString(); + } + + private void assertEquals(String expected, String input, String docType, + String systemId) throws IOException { + FileInputStream fis = null; + try { + fis = testDocument(input); + DoctypeInputStream doctypeInputStream = + new DoctypeInputStream(fis, docType, systemId); + + assertEquals(expected, readFully(doctypeInputStream)); + } finally { + if (fis != null) { + fis.close(); + } + } + } + + public void testRead() throws IOException { + String oz = "Chirurgische Verbesserungen sind g\u00fcnstig"; + assertEquals("<!DOCTYPE Kylie SYSTEM \"bumJob\">" + oz, + oz, "Kylie", "bumJob"); + } + + public void testReplaceDoctypeInternalDTD() throws IOException { + assertEquals("<!DOCTYPE ni SYSTEM \"shrubbery\">", + test_Constants.CHUCK_JONES_RIP_DTD_DECL, "ni", + "shrubbery"); + } + + public void XtestReplaceDoctypeExternalDTD() throws IOException { + assertEquals("<!DOCTYPE ni SYSTEM \"shrubbery\">", + "<! DOCTYPE PUBLIC \"yak\" SYSTEM \"llama\">", "ni", + "shrubbery"); + } + + public void testReplaceDoctypeNoDTD() throws IOException { + assertEquals("<!DOCTYPE ni SYSTEM \"shrubbery\">" + NO_DTD, + NO_DTD, "ni", "shrubbery"); + } + + public void testReplaceDoctypeNoDTDButXMLDecl() throws IOException { + assertEquals(test_Constants.XML_DECLARATION + + "<!DOCTYPE ni SYSTEM \"shrubbery\">" + NO_DTD, + test_Constants.XML_DECLARATION + NO_DTD, + "ni", "shrubbery"); + } + + public test_DoctypeInputStream(String name) { + super(name); + } + + public static TestSuite suite() { + return new TestSuite(test_DoctypeInputStream.class); + } +} + Property changes on: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DoctypeInputStream.java ___________________________________________________________________ Name: svn:executable + * Name: svn:eol-style + native This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-03-30 03:50:00
|
Revision: 164 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=164&view=rev Author: bodewig Date: 2007-03-29 20:50:01 -0700 (Thu, 29 Mar 2007) Log Message: ----------- refactor DoctypeReader/InputStream Modified Paths: -------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeInputStream.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeReader.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeSupport.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/Validator.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DoctypeInputStream.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DoctypeReader.java Added Paths: ----------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/util/ trunk/xmlunit/src/java/org/custommonkey/xmlunit/util/IntegerBuffer.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/AbstractDoctypeTests.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/util/ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/util/test_IntegerBuffer.java Removed Paths: ------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeConstants.java Deleted: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeConstants.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeConstants.java 2007-03-29 07:19:41 UTC (rev 163) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeConstants.java 2007-03-30 03:50:01 UTC (rev 164) @@ -1,45 +0,0 @@ -/* -****************************************************************** -Copyright (c) 2001, Jeff Martin, Tim Bacon -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - * Neither the name of the xmlunit.sourceforge.net nor the names - of its contributors may be used to endorse or promote products - derived from this software without specific prior written - permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. - -****************************************************************** -*/ - -package org.custommonkey.xmlunit; - -interface DoctypeConstants { - String DOCTYPE_OPEN_DECL = "<!"; - int DECL_LENGTH = DOCTYPE_OPEN_DECL.length(); - String DOCTYPE_CLOSE_DECL = ">"; - String DOCTYPE = "DOCTYPE "; - String SYSTEM = " SYSTEM \""; -} \ No newline at end of file Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeInputStream.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeInputStream.java 2007-03-29 07:19:41 UTC (rev 163) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeInputStream.java 2007-03-30 03:50:01 UTC (rev 164) @@ -51,21 +51,11 @@ * <br />Examples and more at <a href="http://xmlunit.sourceforge.net"/>xmlunit.sourceforge.net</a> */ public class DoctypeInputStream extends InputStream { + + private final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); private final InputStream wrappedStream; + private final DoctypeSupport support; - private static final byte[] DOCTYPE_BYTES = { - 'D', 'O', 'C', 'T', 'Y', 'P', 'E', ' ' - }; - - private byte[] readAheadBeforeDeclBuffer = null; - private int readAheadBeforeDeclOffset = 0; - private byte[] readAheadAfterDeclBuffer = null; - private int readAheadAfterDeclOffset = 0; - - private final DoctypeSupport docType; - private boolean writeDecl = false; - - /** * Create an InputStream whose XML content is provided by the * originalSource with the exception of the DOCTYPE which is @@ -74,143 +64,44 @@ * @param doctypeName * @param systemID */ - public DoctypeInputStream(InputStream originalSource, String doctypeName, - String systemID) { + public DoctypeInputStream(InputStream originalSource, String encoding, + String doctypeName, String systemID) { wrappedStream = originalSource instanceof BufferedInputStream ? originalSource : new BufferedInputStream(originalSource); - docType = new DoctypeSupport(doctypeName, systemID); + support = + new DoctypeSupport(doctypeName, systemID, + new DoctypeSupport.Readable() { + public int read() throws IOException { + return wrappedStream.read(); + } + }, + false, encoding); } /** - * Read DOCTYPE-replaced content from the wrapped Reader + * @return the content of the original source, without amendments or + * substitutions. Safe to call multiple times. + * @throws IOException if thrown while reading from the original source */ - public int read() throws IOException { - int nextByte = -1; - - if (writeDecl) { - // currently writing our own DOCTYPE declaration - nextByte = docType.read(); - if (nextByte == -1) { - writeDecl = false; - } else { - return nextByte; + protected String getContent(String encoding) throws IOException { + if (baos.size() == 0) { + byte[] buffer = new byte[8192]; + int bytesRead = -1; + while ((bytesRead = wrappedStream.read(buffer)) > -1) { + baos.write(buffer, 0, bytesRead); } } - - if (readAheadBeforeDeclBuffer != null) { - // in part of original document before our DOCTYPE - this - // has already been read - nextByte = readAheadBeforeDeclBuffer[readAheadBeforeDeclOffset++]; - if (readAheadBeforeDeclOffset >= readAheadBeforeDeclBuffer.length) { - readAheadBeforeDeclBuffer = null; - writeDecl = true; - } - } else if (!docType.hasBeenRead()) { - // DOCTYPE not written, yet, need to see where it should go - - // read ahead until we find a good place to insert the doctype, - // store bytes in readAheadBuffers - ByteArrayOutputStream beforeDecl = new ByteArrayOutputStream(); - ByteArrayOutputStream afterDecl = new ByteArrayOutputStream(); - int current; - boolean ready = false; - while (!ready && (current = wrappedStream.read()) != -1) { - byte c = (byte) current; - if (c >= 0 && Character.isWhitespace((char) c)) { - beforeDecl.write(c); - } else if (c == '<') { - // could be XML declaration, comment, PI, DOCTYPE - // or the first element - byte[] elementOrDeclOr = readUntilCloseCharacterIsReached(); - if (elementOrDeclOr.length > 0) { - if (elementOrDeclOr[0] == '?') { - // XML declaration or PI - beforeDecl.write('<'); - beforeDecl.write(elementOrDeclOr, 0, - elementOrDeclOr.length); - } else if (elementOrDeclOr[0] != '!') { - // first element - afterDecl.write('<'); - afterDecl.write(elementOrDeclOr, 0, - elementOrDeclOr.length); - ready = true; - } else { - // comment or doctype - if (indexOfDoctype(elementOrDeclOr) == -1) { - afterDecl.write('<'); - afterDecl.write(elementOrDeclOr, 0, - elementOrDeclOr.length); - } // else swallow old declaration - ready = true; - } - } - - } else { - afterDecl.write(c); - ready = true; - } - } - readAheadBeforeDeclBuffer = beforeDecl.size() > 0 - ? beforeDecl.toByteArray() : null; - readAheadAfterDeclBuffer = afterDecl.size() > 0 - ? afterDecl.toByteArray() : null; - writeDecl = (readAheadBeforeDeclBuffer == null); - return read(); - } else if (readAheadAfterDeclBuffer != null) { - // in part of original document read ahead after our DOCTYPE - nextByte = readAheadAfterDeclBuffer[readAheadAfterDeclOffset++]; - if (readAheadAfterDeclOffset >= readAheadAfterDeclBuffer.length) { - readAheadAfterDeclBuffer = null; - } - } else { - nextByte = wrappedStream.read(); - } - return nextByte; + return encoding == null ? baos.toString() : baos.toString(encoding); } - private byte[] readUntilCloseCharacterIsReached() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - int byteRead = -1; - int openCount = 1; - while (openCount > 0 && (byteRead = wrappedStream.read()) != -1) { - byte c = (byte) byteRead; - baos.write(c); - if (c == '<') { - openCount++; - } - if (c == '>') { - openCount--; - } - } - return baos.toByteArray(); + /** + * Read DOCTYPE-replaced content from the wrapped InputStream + */ + public int read() throws IOException { + return support.read(); } - + public void close() throws IOException { wrappedStream.close(); } - - /** - * Could be faster when searching from the other end, but should do. - */ - private static int indexOfDoctype(byte[] b) { - int index = -1; - for (int i = 0; i < b.length - DOCTYPE_BYTES.length + 1; i++) { - if (b[i] == DOCTYPE_BYTES[0]) { - boolean found = false; - int j = 1; - for (; !found && j < DOCTYPE_BYTES.length; j++) { - if (b[i + j] != DOCTYPE_BYTES[j]) { - found = true; - } - } - if (found) { - index = i; - break; - } else { - i += j - 1; - } - } - } - return index; - } } \ No newline at end of file Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeReader.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeReader.java 2007-03-29 07:19:41 UTC (rev 163) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeReader.java 2007-03-30 03:50:01 UTC (rev 164) @@ -49,19 +49,13 @@ * document against a DTD. * <br />Examples and more at <a href="http://xmlunit.sourceforge.net"/>xmlunit.sourceforge.net</a> */ -public class DoctypeReader extends Reader implements DoctypeConstants { +public class DoctypeReader extends Reader { private final Reader originalReader; private final StringBuffer sourceBuffer = new StringBuffer(1024); - private char[] readAheadBeforeDeclBuffer = null; - private int readAheadBeforeDeclOffset = 0; - private char[] readAheadAfterDeclBuffer = null; - private int readAheadAfterDeclOffset = 0; + private final DoctypeSupport support; - private final DoctypeSupport docType; - private boolean writeDecl = false; - /** * Create a Reader whose XML content is provided by the originalSource with * the exception of the DOCTYPE which is provided by the doctypeName @@ -74,18 +68,23 @@ String systemID) { originalReader = originalSource instanceof BufferedReader ? originalSource : new BufferedReader(originalSource); - docType = new DoctypeSupport(doctypeName, systemID); + support = + new DoctypeSupport(doctypeName, systemID, + new DoctypeSupport.Readable() { + public int read() throws IOException { + return originalReader.read(); + } + }, + true, null); } /** * @return the content of the original source, without amendments or * substitutions. Safe to call multiple times. * @throws IOException if thrown while reading from the original source - * @deprecated this method is only here for BWC, it is no longer - * used by this class */ protected String getContent() throws IOException { - return obsoleteGetContent(originalReader).toString(); + return getContent(originalReader).toString(); } /** @@ -93,7 +92,7 @@ * @return the contents of the originalSource within a StringBuffer * @throws IOException if thrown while reading from the original source */ - private StringBuffer obsoleteGetContent(Reader originalSource) + private StringBuffer getContent(Reader originalSource) throws IOException { if (sourceBuffer.length() == 0) { BufferedReader bufferedReader; @@ -163,19 +162,22 @@ public String replaceDoctype(StringBuffer withinContent, String doctypeName, String systemId) { String content = withinContent.toString(); - int startDoctype = content.indexOf(DOCTYPE); + int startDoctype = content.indexOf(DoctypeSupport.DOCTYPE); boolean noCurrentDoctype = false; if (startDoctype == -1) { startDoctype = obsoleteFindStartDoctype(withinContent); noCurrentDoctype = true; } - int endDoctype = startDoctype + DOCTYPE.length(); + int endDoctype = startDoctype + DoctypeSupport.DOCTYPE.length(); if (noCurrentDoctype) { - withinContent.insert(startDoctype, DOCTYPE_OPEN_DECL); - withinContent.insert(startDoctype + DECL_LENGTH, DOCTYPE); - endDoctype += DECL_LENGTH; + withinContent.insert(startDoctype, + DoctypeSupport.DOCTYPE_OPEN_DECL); + withinContent.insert(startDoctype + + DoctypeSupport.DOCTYPE_OPEN_DECL.length(), + DoctypeSupport.DOCTYPE); + endDoctype += DoctypeSupport.DOCTYPE_OPEN_DECL.length(); } else { int startInternalDecl = content.indexOf('[', endDoctype); if (startInternalDecl > 0) { @@ -190,14 +192,14 @@ int atPos = endDoctype; withinContent.insert(atPos, doctypeName); atPos += doctypeName.length(); - withinContent.insert(atPos, SYSTEM); - atPos += SYSTEM.length(); + withinContent.insert(atPos, DoctypeSupport.SYSTEM); + atPos += DoctypeSupport.SYSTEM.length(); withinContent.insert(atPos, systemId); atPos += systemId.length(); withinContent.insert(atPos, '"'); if (noCurrentDoctype) { - withinContent.insert(++atPos, DOCTYPE_CLOSE_DECL); + withinContent.insert(++atPos, DoctypeSupport.DOCTYPE_CLOSE_DECL); } return withinContent.toString(); } @@ -224,102 +226,9 @@ * Read DOCTYPE-replaced content from the wrapped Reader */ public int read() throws IOException { - int nextChar = -1; - - if (writeDecl) { - // currently writing our own DOCTYPE declaration - nextChar = docType.read(); - if (nextChar == -1) { - writeDecl = false; - } else { - return nextChar; - } - } - - if (readAheadBeforeDeclBuffer != null) { - // in part of original document before our DOCTYPE - this - // has already been read - nextChar = readAheadBeforeDeclBuffer[readAheadBeforeDeclOffset++]; - if (readAheadBeforeDeclOffset >= readAheadBeforeDeclBuffer.length) { - readAheadBeforeDeclBuffer = null; - writeDecl = true; - } - } else if (!docType.hasBeenRead()) { - // DOCTYPE not written, yet, need to see where it should go - - // read ahead until we find a good place to insert the doctype, - // store characters in readAheadBuffers - StringBuffer beforeDecl = new StringBuffer(); - StringBuffer afterDecl = new StringBuffer(); - int current; - boolean ready = false; - while (!ready && (current = originalReader.read()) != -1) { - char c = (char) current; - if (Character.isWhitespace(c)) { - beforeDecl.append(c); - } else if (c == '<') { - // could be XML declaration, comment, PI, DOCTYPE - // or the first element - String elementOrDeclOr = readUntilCloseCharacterIsReached(); - if (elementOrDeclOr.length() > 0) { - if (elementOrDeclOr.charAt(0) == '?') { - // XML declaration or PI - beforeDecl.append('<').append(elementOrDeclOr); - } else if (elementOrDeclOr.charAt(0) != '!') { - // first element - afterDecl.append('<').append(elementOrDeclOr); - ready = true; - } else { - // comment or doctype - if (elementOrDeclOr.indexOf(DOCTYPE) == -1) { - afterDecl.append('<').append(elementOrDeclOr); - } // else swallow old declaration - ready = true; - } - } - - } else { - afterDecl.append(c); - ready = true; - } - } - readAheadBeforeDeclBuffer = beforeDecl.length() > 0 - ? beforeDecl.toString().toCharArray() - : null; - readAheadAfterDeclBuffer = afterDecl.length() > 0 - ? afterDecl.toString().toCharArray() - : null; - writeDecl = (readAheadBeforeDeclBuffer == null); - return read(); - } else if (readAheadAfterDeclBuffer != null) { - // in part of original document read ahead after our DOCTYPE - nextChar = readAheadAfterDeclBuffer[readAheadAfterDeclOffset++]; - if (readAheadAfterDeclOffset >= readAheadAfterDeclBuffer.length) { - readAheadAfterDeclBuffer = null; - } - } else { - nextChar = originalReader.read(); - } - return nextChar; + return support.read(); } - private String readUntilCloseCharacterIsReached() throws IOException { - StringBuffer sb = new StringBuffer(); - int characterRead = -1; - int openCount = 1; - while (openCount > 0 && (characterRead = originalReader.read()) != -1) { - char c = (char) characterRead; - sb.append(c); - if (c == '<') { - openCount++; - } - if (c == '>') { - openCount--; - } - } - return sb.toString(); - } - public void close() throws IOException { originalReader.close(); } Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeSupport.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeSupport.java 2007-03-29 07:19:41 UTC (rev 163) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DoctypeSupport.java 2007-03-30 03:50:01 UTC (rev 164) @@ -36,39 +36,231 @@ package org.custommonkey.xmlunit; +import java.io.IOException; + +import org.custommonkey.xmlunit.exceptions.XMLUnitRuntimeException; +import org.custommonkey.xmlunit.util.IntegerBuffer; + /** * Contains some common code for DoctypeReader and DoctypeInputStream. * * <p>When used with DoctypeInputStream it assumes that the whole * DOCTYPE declaration consists of US-ASCII characters.</p> */ -final class DoctypeSupport implements DoctypeConstants { +final class DoctypeSupport { - private final String decl; - private int offset = 0; + static interface Readable { + int read() throws IOException; + } + final static String DOCTYPE_OPEN_DECL = "<!"; + final static String DOCTYPE_CLOSE_DECL = ">"; + final static String DOCTYPE = "DOCTYPE "; + final static String SYSTEM = " SYSTEM \""; + private final static int[] DOCTYPE_INTS = { + 'D', 'O', 'C', 'T', 'Y', 'P', 'E', ' ' + }; + + private boolean hasSplit; + private final Readable original; + private Readable decl; + private Readable beforeDoctype; + private Readable afterDoctype; + /** * Encapsulates a DOCTYPE declaration for the given name and system id. */ - DoctypeSupport(String name, String systemId) { + DoctypeSupport(String name, String systemId, Readable original, + boolean characters, String encoding) { + this.original = original; + StringBuffer sb = new StringBuffer(DOCTYPE_OPEN_DECL); sb.append(DOCTYPE).append(name).append(SYSTEM) .append(systemId).append("\"").append(DOCTYPE_CLOSE_DECL); - decl = sb.toString(); + String s = sb.toString(); + IntegerBuffer buf = + new IntegerBuffer(s.length() * (characters ? 1 : 2)); + + if (characters) { + char[] c = s.toCharArray(); + for (int i = 0; i < c.length; i++) { + buf.append(c[i]); + } + } else { + try { + byte[] b = encoding == null + ? s.getBytes() : s.getBytes(encoding); + for (int i = 0; i < b.length; i++) { + buf.append(b[i] & 0xFF); + } + } catch (java.io.UnsupportedEncodingException use) { + throw new XMLUnitRuntimeException("Unsupported encoding", use); + } + } + + decl = new IntBufferReadable(buf); } /** - * Whether anybody has started to read the declaration. + * Reads the next character from the declaration. + * @return -1 if the end of the declaration has been reached. */ - boolean hasBeenRead() { - return offset != 0; + int read() throws IOException { + int nextInt = -1; + if (!hasSplit) { + split(); + } + if (beforeDoctype != null) { + nextInt = beforeDoctype.read(); + if (nextInt == -1) { + beforeDoctype = null; + } + } + if (nextInt == -1 && decl != null) { + nextInt = decl.read(); + if (nextInt == -1) { + decl = null; + } + } + if (nextInt == -1 && afterDoctype != null) { + nextInt = afterDoctype.read(); + if (nextInt == -1) { + afterDoctype = null; + } + } + if (nextInt == -1) { + nextInt = original.read(); + } + return nextInt; } /** - * Reads the next character from the declaration. - * @return -1 if the end of the declaration has been reached. + * Reads enough of the original Readable to know where to place + * the declaration. Fills beforeDecl and afterDecl from the data + * read ahead. Swallows the original DOCTYPE if there is one. */ - int read() { - return offset >= decl.length() ? -1 : decl.charAt(offset++); + private void split() throws IOException { + hasSplit = true; + IntegerBuffer before = new IntegerBuffer(); + IntegerBuffer after = new IntegerBuffer(); + + int current; + boolean ready = false; + boolean stillNeedToSeeDoctype = true; + while (!ready && (current = original.read()) != -1) { + if (Character.isWhitespace((char) current)) { + before.append(current); + } else if (current == '<') { + // could be XML declaration, comment, PI, DOCTYPE + // or the first element + int[] elementOrDeclOr = readUntilCloseCharIsReached(); + if (elementOrDeclOr.length > 0) { + if (elementOrDeclOr[0] == '?') { + // XML declaration or PI + before.append('<'); + before.append(elementOrDeclOr); + } else if (elementOrDeclOr[0] != '!') { + // first element + after.append('<'); + after.append(elementOrDeclOr); + stillNeedToSeeDoctype = false; + ready = true; + } else { + // comment or doctype + IntegerBuffer b = + new IntegerBuffer(elementOrDeclOr.length); + b.append(elementOrDeclOr); + if (b.indexOf(DOCTYPE_INTS) == -1) { + after.append('<'); + after.append(elementOrDeclOr); + } else { + // swallow old declaration + stillNeedToSeeDoctype = false; + } + ready = true; + } + } else { + after.append('<'); + stillNeedToSeeDoctype = false; + ready = true; + } + } else { + after.append(current); + stillNeedToSeeDoctype = false; + ready = true; + } + } + + // need to eliminate original DOCTYPE if it exists + while (stillNeedToSeeDoctype && (current = original.read()) != -1) { + if (Character.isWhitespace((char) current)) { + after.append(current); + } else if (current == '<') { + int[] elementOrDeclOr = readUntilCloseCharIsReached(); + if (elementOrDeclOr.length > 0) { + if (elementOrDeclOr[0] == '?') { + // PI + after.append('<'); + after.append(elementOrDeclOr); + } else if (elementOrDeclOr[0] != '!') { + // first element + after.append('<'); + after.append(elementOrDeclOr); + stillNeedToSeeDoctype = false; + } else { + // comment or doctype + IntegerBuffer b = + new IntegerBuffer(elementOrDeclOr.length); + b.append(elementOrDeclOr); + if (b.indexOf(DOCTYPE_INTS) == -1) { + after.append('<'); + after.append(elementOrDeclOr); + } else { + // swallow old declaration + stillNeedToSeeDoctype = false; + } + } + } else { + after.append('<'); + stillNeedToSeeDoctype = false; + } + } else { + after.append(current); + stillNeedToSeeDoctype = false; + } + } + + beforeDoctype = before.size() > 0 + ? new IntBufferReadable(before) : null; + afterDoctype = after.size() > 0 + ? new IntBufferReadable(after) : null; } + + private int[] readUntilCloseCharIsReached() throws IOException { + IntegerBuffer i = new IntegerBuffer(); + int intRead = -1; + int openCount = 1; + while (openCount > 0 && (intRead = original.read()) != -1) { + i.append(intRead); + if (intRead == '<') { + openCount++; + } + if (intRead == '>') { + openCount--; + } + } + return i.toIntArray(); + } + + private static class IntBufferReadable implements Readable { + private final int[] buf; + private int off; + IntBufferReadable(IntegerBuffer b) { + buf = b.toIntArray(); + } + public int read() { + return off >= buf.length ? -1 : buf[off++]; + } + } + } \ No newline at end of file Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/Validator.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/Validator.java 2007-03-29 07:19:41 UTC (rev 163) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/Validator.java 2007-03-30 03:50:01 UTC (rev 164) @@ -258,6 +258,8 @@ doctype, systemID)) : new InputSource(new DoctypeInputStream(sourceForValidation .getByteStream(), + sourceForValidation + .getEncoding(), doctype, systemID)), systemID, true); } @@ -382,7 +384,7 @@ } else if (usingDoctypeReader) { try { messages.append("\nContent was: ") - .append(readFully(validationInputSource)); + .append(getOriginalContent(validationInputSource)); } catch (IOException e) { // silent but deadly? } @@ -492,30 +494,11 @@ schemaSource); } - private static String readFully(InputSource s) throws IOException { - return s.getCharacterStream() != null - ? readFully(s.getCharacterStream()) : readFully(s.getByteStream()); + private static String getOriginalContent(InputSource s) + throws IOException { + return s.getCharacterStream() instanceof DoctypeReader + ? ((DoctypeReader) s.getCharacterStream()).getContent() + : ((DoctypeInputStream) s.getByteStream()) + .getContent(s.getEncoding()); } - - private static String readFully(Reader r) throws IOException { - StringBuffer sb = new StringBuffer(); - char[] buffer = new char[4096]; - int charsRead = -1; - while ((charsRead = r.read(buffer)) > -1) { - sb.append(buffer, 0, charsRead); - } - return sb.toString(); - } - - private static String readFully(java.io.InputStream is) throws IOException { - java.io.ByteArrayOutputStream baos = - new java.io.ByteArrayOutputStream(); - byte[] buffer = new byte[8192]; - int bytesRead = -1; - while ((bytesRead = is.read(buffer)) > -1) { - baos.write(buffer, 0, bytesRead); - } - return new String(baos.toByteArray()); - } - } Added: trunk/xmlunit/src/java/org/custommonkey/xmlunit/util/IntegerBuffer.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/util/IntegerBuffer.java (rev 0) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/util/IntegerBuffer.java 2007-03-30 03:50:01 UTC (rev 164) @@ -0,0 +1,146 @@ +/* +****************************************************************** +Copyright (c) 2001, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit.util; + +/** + * Simplistic dynamically growing buffer of integers used by DoctypeSupport. + * + * <p>No attempt has been made to make this class thread-safe at all. + * The append methods and indexOf are not too efficient either, but + * work for what we need.</p> + */ +public class IntegerBuffer { + + // should be big enough for the DoctypeSupport use case + private static final int INITIAL_SIZE = 512; + + private int[] buffer; + private int currentSize; + + /** + * Creates a new buffer. + */ + public IntegerBuffer() { + this(INITIAL_SIZE); + } + + /** + * Creates a new buffer with the given initial capacity. + */ + public IntegerBuffer(int capacity) { + buffer = new int[capacity]; + } + + /** + * Returns the current size. + */ + public int size() { + return currentSize; + } + + /** + * Returns the current capacity (the size the buffer can use + * before it needs to grow). + */ + public int capacity() { + return buffer.length; + } + + /** + * Appends a single int. + */ + public void append(int i) { + // could simply delegate to the other append methods, but this + // (avoiding arraycopy) is more efficient. + while (currentSize >= buffer.length) { + grow(); + } + buffer[currentSize++] = i; + } + + /** + * Appends an array of ints. + */ + public void append(int[] i) { + // could simply delegate to the other append methods, but this + // (avoiding repeated comparisions) is more efficient. + while (currentSize + i.length > buffer.length) { + grow(); + } + System.arraycopy(i, 0, buffer, currentSize, i.length); + currentSize += i.length; + } + + /** + * Returns an arry view of this buffer's content. + */ + public int[] toIntArray() { + int[] i = new int[currentSize]; + System.arraycopy(buffer, 0, i, 0, currentSize); + return i; + } + + /** + * finds sequence in current buffer. + * + * @return index of sequence or -1 if not found + */ + public int indexOf(int[] sequence) { + int index = -1; + for (int i = 0; index == -1 && i <= currentSize - sequence.length; + i++) { + if (buffer[i] == sequence[0]) { + boolean matches = true; + for (int j = 1; matches && j < sequence.length; j++) { + if (buffer[i + j] != sequence[j]) { + matches = false; + } + } + if (matches) { + index = i; + } + } + } + return index; + } + + private void grow() { + int[] i = new int[buffer.length * 2 + 1]; + System.arraycopy(buffer, 0, i, 0, buffer.length); + buffer = i; + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/java/org/custommonkey/xmlunit/util/IntegerBuffer.java ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/AbstractDoctypeTests.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/AbstractDoctypeTests.java (rev 0) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/AbstractDoctypeTests.java 2007-03-30 03:50:01 UTC (rev 164) @@ -0,0 +1,121 @@ +/* +****************************************************************** +Copyright (c) 200, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit; + +import java.io.IOException; + +import junit.framework.TestCase; + +/** + * JUnit test for DoctypeReader and DoctypeInputStream + */ +public abstract class AbstractDoctypeTests extends TestCase { + + private static final String COMMENT = "<!-- comment -->"; + protected static final String NO_DTD = + "<document><element>one</element></document>"; + + public abstract void testGetContent() throws IOException; + + protected abstract void assertEquals(String expected, String input, + String docType, String systemId) + throws IOException; + + public void testRead() throws IOException { + String oz = "Chirurgische Verbesserungen sind g\u00fcnstig"; + assertEquals("<!DOCTYPE Kylie SYSTEM \"bumJob\">" + oz, + oz, "Kylie", "bumJob"); + } + + public void testInternalDTD() throws IOException { + assertEquals("<!DOCTYPE ni SYSTEM \"shrubbery\">", + test_Constants.CHUCK_JONES_RIP_DTD_DECL, "ni", + "shrubbery"); + } + + public void testExternalDTD() throws IOException { + assertEquals("<!DOCTYPE ni SYSTEM \"shrubbery\">", + "<! DOCTYPE PUBLIC \"yak\" SYSTEM \"llama\">", "ni", + "shrubbery"); + } + + public void testNoDTD() throws IOException { + assertEquals("<!DOCTYPE ni SYSTEM \"shrubbery\">" + NO_DTD, + NO_DTD, "ni", "shrubbery"); + } + + public void testNoDTDButXMLDecl() throws IOException { + assertEquals(test_Constants.XML_DECLARATION + + "<!DOCTYPE ni SYSTEM \"shrubbery\">" + NO_DTD, + test_Constants.XML_DECLARATION + NO_DTD, + "ni", "shrubbery"); + } + + public void testInternalDTDWithComment() throws IOException { + assertEquals(test_Constants.XML_DECLARATION + + "<!DOCTYPE ni SYSTEM \"shrubbery\">" + + COMMENT, + test_Constants.XML_DECLARATION + + COMMENT + + test_Constants.CHUCK_JONES_RIP_DTD_DECL, + "ni", "shrubbery"); + } + + public void testExternalDTDWithComment() throws IOException { + assertEquals("<!DOCTYPE ni SYSTEM \"shrubbery\">" + + COMMENT, + COMMENT + "<! DOCTYPE PUBLIC \"yak\" SYSTEM \"llama\">", + "ni", "shrubbery"); + } + + public void testNoDTDWithComment() throws IOException { + assertEquals("<!DOCTYPE ni SYSTEM \"shrubbery\">" + COMMENT + NO_DTD, + COMMENT + NO_DTD, "ni", "shrubbery"); + } + + public void testNoDTDButXMLDeclWithComment() throws IOException { + assertEquals(test_Constants.XML_DECLARATION + + "<!DOCTYPE ni SYSTEM \"shrubbery\">" + COMMENT + NO_DTD, + test_Constants.XML_DECLARATION + COMMENT + NO_DTD, + "ni", "shrubbery"); + } + + public AbstractDoctypeTests(String name) { + super(name); + } +} + Property changes on: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/AbstractDoctypeTests.java ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DoctypeInputStream.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DoctypeInputStream.java 2007-03-29 07:19:41 UTC (rev 163) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DoctypeInputStream.java 2007-03-30 03:50:01 UTC (rev 164) @@ -49,10 +49,8 @@ /** * JUnit test for DoctypeInputStream */ -public class test_DoctypeInputStream extends TestCase { +public class test_DoctypeInputStream extends AbstractDoctypeTests { - private static final String NEWLINE = System.getProperty("line.separator"); - private static final String NO_DTD = "<document><element>one</element></document>"; private File testFile; public void tearDown() { @@ -85,13 +83,13 @@ return buf.toString(); } - private void assertEquals(String expected, String input, String docType, - String systemId) throws IOException { + protected void assertEquals(String expected, String input, String docType, + String systemId) throws IOException { FileInputStream fis = null; try { fis = testDocument(input); DoctypeInputStream doctypeInputStream = - new DoctypeInputStream(fis, docType, systemId); + new DoctypeInputStream(fis, "ISO-8859-1", docType, systemId); assertEquals(expected, readFully(doctypeInputStream)); } finally { @@ -101,42 +99,18 @@ } } - public void testRead() throws IOException { - String oz = "Chirurgische Verbesserungen sind g\u00fcnstig"; - assertEquals("<!DOCTYPE Kylie SYSTEM \"bumJob\">" + oz, - oz, "Kylie", "bumJob"); + public void testGetContent() throws IOException { + String source = "WooPDeDoO!\nGooRanga!\n plIng! "; + DoctypeInputStream dis = + new DoctypeInputStream(new java.io.StringBufferInputStream(source), + null, "nonsense", "words"); + assertEquals(source, dis.getContent(null)); + // can get content indefinitely from this stream + assertEquals(source, dis.getContent("UTF-8")); } - public void testReplaceDoctypeInternalDTD() throws IOException { - assertEquals("<!DOCTYPE ni SYSTEM \"shrubbery\">", - test_Constants.CHUCK_JONES_RIP_DTD_DECL, "ni", - "shrubbery"); - } - - public void XtestReplaceDoctypeExternalDTD() throws IOException { - assertEquals("<!DOCTYPE ni SYSTEM \"shrubbery\">", - "<! DOCTYPE PUBLIC \"yak\" SYSTEM \"llama\">", "ni", - "shrubbery"); - } - - public void testReplaceDoctypeNoDTD() throws IOException { - assertEquals("<!DOCTYPE ni SYSTEM \"shrubbery\">" + NO_DTD, - NO_DTD, "ni", "shrubbery"); - } - - public void testReplaceDoctypeNoDTDButXMLDecl() throws IOException { - assertEquals(test_Constants.XML_DECLARATION - + "<!DOCTYPE ni SYSTEM \"shrubbery\">" + NO_DTD, - test_Constants.XML_DECLARATION + NO_DTD, - "ni", "shrubbery"); - } - public test_DoctypeInputStream(String name) { super(name); } - - public static TestSuite suite() { - return new TestSuite(test_DoctypeInputStream.class); - } } Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DoctypeReader.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DoctypeReader.java 2007-03-29 07:19:41 UTC (rev 163) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DoctypeReader.java 2007-03-30 03:50:01 UTC (rev 164) @@ -36,7 +36,7 @@ package org.custommonkey.xmlunit; - +import java.io.IOException; import java.io.StringReader; import junit.framework.TestCase; @@ -45,29 +45,12 @@ /** * JUnit test for DoctypeReader */ -public class test_DoctypeReader extends TestCase { +public class test_DoctypeReader extends AbstractDoctypeTests { private DoctypeReader doctypeReader; private StringReader sourceReader; private static final String NEWLINE = System.getProperty("line.separator"); - private static final String NO_DTD = "<document><element>one</element></document>"; - public void testRead() throws Exception { - String oz = "Surgical enhancement is cheap"; - StringReader reader = new StringReader(oz); - doctypeReader = new DoctypeReader(reader, "Kylie", "bumJob"); - - StringBuffer buf = new StringBuffer(); - String expected = "<!DOCTYPE Kylie SYSTEM \"bumJob\">" + oz; - char[] ch = new char[expected.length()]; - int numChars; - while ((numChars = doctypeReader.read(ch))!=-1) { - buf.append(ch); - } - - assertEquals(expected, buf.toString()); - } - - public void testGetContent() throws Exception { + public void testGetContent() throws IOException { String source = "WooPDeDoO!" + NEWLINE + "GooRanga!" + NEWLINE + " plIng! "; sourceReader = new StringReader(source); @@ -115,12 +98,27 @@ doctypeReader.replaceDoctype(buf, "ni", "shrubbery")); } - public test_DoctypeReader(String name) { - super(name); + private static String readFully(DoctypeReader reader) + throws IOException { + StringBuffer buf = new StringBuffer(); + char[] ch = new char[1024]; + int numChars; + while ((numChars = reader.read(ch))!=-1) { + buf.append(ch, 0, numChars); + } + return buf.toString(); } - public static TestSuite suite() { - return new TestSuite(test_DoctypeReader.class); + protected void assertEquals(String expected, String input, String docType, + String systemId) throws IOException { + DoctypeReader doctypeReader = + new DoctypeReader(new StringReader(expected), docType, + systemId); + assertEquals(expected, readFully(doctypeReader)); } + + public test_DoctypeReader(String name) { + super(name); + } } Added: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/util/test_IntegerBuffer.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/util/test_IntegerBuffer.java (rev 0) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/util/test_IntegerBuffer.java 2007-03-30 03:50:01 UTC (rev 164) @@ -0,0 +1,168 @@ +/* +****************************************************************** +Copyright (c) 200, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit.util; + +import junit.framework.TestCase; + +/** + * Tests for IntegerBuffer + */ +public class test_IntegerBuffer extends TestCase { + + public void testToArrayEmpty() { + assertNotNull((new IntegerBuffer()).toIntArray()); + assertEquals(0, (new IntegerBuffer()).toIntArray().length); + } + + public void testSingleIntAppend() { + IntegerBuffer b = new IntegerBuffer(); + b.append(1); + assertNotNull(b.toIntArray()); + assertEquals(1, b.toIntArray().length); + assertEquals(1, b.toIntArray()[0]); + } + + public void testArrayAppend() { + IntegerBuffer b = new IntegerBuffer(); + b.append(new int[] {1, 2}); + assertNotNull(b.toIntArray()); + assertEquals(2, b.toIntArray().length); + for (int i = 0; i < 2; i++) { + assertEquals(i + 1, b.toIntArray()[i]); + } + } + + public void testSingleIntAppendWithGrowth() { + IntegerBuffer b = new IntegerBuffer(1); + for (int i = 0; i < 2; i++) { + b.append(i); + } + assertNotNull(b.toIntArray()); + assertEquals(2, b.toIntArray().length); + for (int i = 0; i < 2; i++) { + assertEquals(i, b.toIntArray()[i]); + } + } + + public void testArrayAppendWithGrowth() { + IntegerBuffer b = new IntegerBuffer(1); + b.append(new int[] {1, 2}); + assertNotNull(b.toIntArray()); + assertEquals(2, b.toIntArray().length); + for (int i = 0; i < 2; i++) { + assertEquals(i + 1, b.toIntArray()[i]); + } + } + + public void testSize() { + IntegerBuffer b = new IntegerBuffer(); + assertEquals(0, b.size()); + b.append(0); + assertEquals(1, b.size()); + b.append(new int[] {1, 2}); + assertEquals(3, b.size()); + } + + public void testCapacity() { + IntegerBuffer b = new IntegerBuffer(1); + assertEquals(1, b.capacity()); + b.append(0); + assertEquals(1, b.capacity()); + b.append(0); + assertTrue(b.capacity() > 1); + } + + public void testIndexOfSimple() { + IntegerBuffer b = new IntegerBuffer(); + int[] test = new int[] {1, 2, 3}; + assertEquals(-1, b.indexOf(test)); + b.append(test); + assertEquals(0, b.indexOf(test)); + b.append(test); + assertEquals(0, b.indexOf(test)); + } + + public void testIndexOfWithOffset() { + IntegerBuffer b = new IntegerBuffer(); + int[] test = new int[] {1, 2, 3}; + b.append(0); + assertEquals(-1, b.indexOf(test)); + b.append(test); + assertEquals(1, b.indexOf(test)); + } + + public void testIndexOfWithRepeatedInts() { + IntegerBuffer b = new IntegerBuffer(); + int[] test = new int[] {1, 2, 3}; + b.append(1); + assertEquals(-1, b.indexOf(test)); + b.append(test); + assertEquals(1, b.indexOf(test)); + } + + public void testIndexOfSupSequenceIsThere() { + IntegerBuffer b = new IntegerBuffer(); + int[] test = new int[] {1, 2, 3}; + b.append(new int[] {1, 2}); + b.append(4); + assertEquals(-1, b.indexOf(test)); + } + + public void testAllBytes() { + IntegerBuffer buf = new IntegerBuffer(); + for (byte b = Byte.MIN_VALUE; b < Byte.MAX_VALUE; b++) { + buf.append(b); + } + buf.append(Byte.MAX_VALUE); + int[] is = buf.toIntArray(); + for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) { + assertEquals((byte) i, is[i + Math.abs(Byte.MIN_VALUE)]); + } + } + + public void testAllChars() { + IntegerBuffer buf = new IntegerBuffer(); + for (char c = Character.MIN_VALUE; c < Character.MAX_VALUE; c++) { + buf.append(c); + } + buf.append(Character.MAX_VALUE); + int[] is = buf.toIntArray(); + for (int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; i++) { + assertEquals((char) i, is[i + Math.abs(Character.MIN_VALUE)]); + } + } +} \ No newline at end of file Property changes on: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/util/test_IntegerBuffer.java ___________________________________________________________________ Name: svn:eol-style + native This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-04-03 03:48:40
|
Revision: 168 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=168&view=rev Author: bodewig Date: 2007-04-02 20:48:34 -0700 (Mon, 02 Apr 2007) Log Message: ----------- Provide a Maven 2 POM and an Ivy File Modified Paths: -------------- trunk/xmlunit/LICENSE.txt trunk/xmlunit/build.xml Added Paths: ----------- trunk/xmlunit/src/etc/xmlunit-ivy.xml trunk/xmlunit/src/etc/xmlunit.pom Modified: trunk/xmlunit/LICENSE.txt =================================================================== --- trunk/xmlunit/LICENSE.txt 2007-04-01 09:52:52 UTC (rev 167) +++ trunk/xmlunit/LICENSE.txt 2007-04-03 03:48:34 UTC (rev 168) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 2001, Jeff Martin, Tim Bacon +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without Modified: trunk/xmlunit/build.xml =================================================================== --- trunk/xmlunit/build.xml 2007-04-01 09:52:52 UTC (rev 167) +++ trunk/xmlunit/build.xml 2007-04-03 03:48:34 UTC (rev 168) @@ -93,6 +93,9 @@ <target name="setDistVersion" depends="init"> <replace dir="${src.dir}" token="@@version@@" value="${xmlunit.version}" includes="**/*.java"/> + <tstamp> + <format property="ivy.publication.datetime" pattern="yyyyMMddHHmmss"/> + </tstamp> </target> <target name="docs" depends="init"> @@ -121,6 +124,24 @@ basedir="${out.dir}" excludes="**/test_*.class" /> + + <copy todir="${lib.dir}"> + <fileset dir="src/etc"> + <include name="xmlunit.pom"/> + <include name="xmlunit-ivy.xml"/> + </fileset> + <mapper type="glob" from="xmlunit*" to="xmlunit-${xmlunit.version}*"/> + <filterset> + <filter token="VERSION" value="${xmlunit.version}"/> + <filter token="DATE" value="${ivy.publication.datetime}"/> + <filter token="DESCRIPTION" value="XMLUnit compares a control XML document to a test document or the result of a transformation, validates documents, and compares the results of XPath expressions."/> + <filter token="LICENSE" value="BSD License"/> + <filter token="LICENSE_URL" value="http://xmlunit.svn.sourceforge.net/viewvc/*checkout*/xmlunit/trunk/xmlunit/LICENSE.txt"/> + <filter token="GROUP" value="xmlunit"/> + <filter token="ARTIFACT" value="xmlunit"/> + <filter token="TYPE" value="jar"/> + </filterset> + </copy> </target> <target name="dist" depends="jar,test,docs"> Added: trunk/xmlunit/src/etc/xmlunit-ivy.xml =================================================================== --- trunk/xmlunit/src/etc/xmlunit-ivy.xml (rev 0) +++ trunk/xmlunit/src/etc/xmlunit-ivy.xml 2007-04-03 03:48:34 UTC (rev 168) @@ -0,0 +1,13 @@ +<ivy-module version="1.3"> + <info organization="@GROUP@" + module="@ARTIFACT@" + revision="@VERSION@" + publication="@DATE@"> + <license name="@LICENSE@" + url="@LICENSE_URL@"/> + <description>@DESCRIPTION@</description> + </info> + <publications> + <artifact name="@ARTIFACT@" type="@TYPE@"/> + </publications> +</ivy-module> Property changes on: trunk/xmlunit/src/etc/xmlunit-ivy.xml ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/xmlunit/src/etc/xmlunit.pom =================================================================== --- trunk/xmlunit/src/etc/xmlunit.pom (rev 0) +++ trunk/xmlunit/src/etc/xmlunit.pom 2007-04-03 03:48:34 UTC (rev 168) @@ -0,0 +1,16 @@ +<project> + <modelVersion>4.0.0</modelVersion> + <groupId>@GROUP@</groupId> + <artifactId>@ARTIFACT@</artifactId> + <packaging>@TYPE@</packaging> + <version>@VERSION@</version> + <description>@DESCRIPTION@</description> + <url>http://xmlunit.sourceforge.net/</url> + <licenses> + <license> + <name>@LICENSE@</name> + <url>@LICENSE_URL@</url> + </license> + </licenses> + <dependencies/> +</project> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-04-03 04:28:28
|
Revision: 170 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=170&view=rev Author: bodewig Date: 2007-04-02 21:28:28 -0700 (Mon, 02 Apr 2007) Log Message: ----------- Refactor XPath tests a little Modified Paths: -------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/XpathEngine.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/jaxp13/test_Jaxp13XpathEngine.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_SimpleXpathEngine.java Added Paths: ----------- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/AbstractXpathEngineTests.java Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/XpathEngine.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/XpathEngine.java 2007-04-03 04:12:54 UTC (rev 169) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/XpathEngine.java 2007-04-03 04:28:28 UTC (rev 170) @@ -55,10 +55,9 @@ * @param select * @param document * @return list of matching nodes - * @throws TransformerException */ NodeList getMatchingNodes(String select, Document document) - throws ConfigurationException, XpathException; + throws XpathException; /** * Evaluate the result of executing the specified xpath syntax @@ -66,10 +65,9 @@ * @param select * @param document * @return evaluated result - * @throws TransformerException */ String evaluate(String select, Document document) - throws ConfigurationException, XpathException; + throws XpathException; /** * Establish a namespace context. Added: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/AbstractXpathEngineTests.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/AbstractXpathEngineTests.java (rev 0) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/AbstractXpathEngineTests.java 2007-04-03 04:28:28 UTC (rev 170) @@ -0,0 +1,149 @@ +/* +****************************************************************** +Copyright (c) 2007, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit; + +import java.util.HashMap; +import junit.framework.TestCase; +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public abstract class AbstractXpathEngineTests extends TestCase { + + protected static final String[] testAttrNames = {"attrOne", "attrTwo"}; + + protected static final String testString = + "<test><nodeWithoutAttributes>intellectual property rights" + + " </nodeWithoutAttributes>" + + "<nodeWithoutAttributes>make us all poorer </nodeWithoutAttributes>" + + "<nodeWithAttributes " + testAttrNames[0] + "=\"open source \" " + + testAttrNames[1] + + "=\"is the answer \">free your code from its chains" + + "</nodeWithAttributes></test>"; + protected Document testDocument; + + protected abstract XpathEngine newXpathEngine(); + + public void testGetMatchingNodesNoMatches() throws Exception { + NodeList nodeList = newXpathEngine().getMatchingNodes("toast", + testDocument); + assertEquals(0, nodeList.getLength()); + } + + public void testGetMatchingNodesMatchRootElement() throws Exception { + NodeList nodeList = newXpathEngine().getMatchingNodes("test", + testDocument); + assertEquals(1, nodeList.getLength()); + assertEquals(Node.ELEMENT_NODE, nodeList.item(0).getNodeType()); + } + + public void testGetMatchingNodesMatchElement() throws Exception { + NodeList nodeList = newXpathEngine() + .getMatchingNodes("test/nodeWithoutAttributes", testDocument); + assertEquals(2, nodeList.getLength()); + assertEquals(Node.ELEMENT_NODE, nodeList.item(0).getNodeType()); + } + + public void testGetMatchingNodesMatchText() throws Exception { + NodeList nodeList = newXpathEngine().getMatchingNodes("test//text()", + testDocument); + assertEquals(3, nodeList.getLength()); + assertEquals(Node.TEXT_NODE, nodeList.item(0).getNodeType()); + } + + public void testGetMatchingNodesCheckSubNodes() throws Exception { + NodeList nodeList = newXpathEngine() + .getMatchingNodes("test/nodeWithAttributes", testDocument); + assertEquals(1, nodeList.getLength()); + Node aNode; + + aNode = nodeList.item(0); + assertEquals(Node.ELEMENT_NODE, aNode.getNodeType()); + assertEquals(true, aNode.hasAttributes()); + assertEquals(true, aNode.hasChildNodes()); + + NodeList children = aNode.getChildNodes(); + int length = children.getLength(); + assertEquals(1, length); + for (int i=0; i < length; ++i) { + assertEquals(Node.TEXT_NODE, children.item(i).getNodeType()); + } + + NamedNodeMap attributes = aNode.getAttributes(); + int numAttrs = attributes.getLength(); + assertEquals(testAttrNames.length, numAttrs); + for (int i=0; i < testAttrNames.length; ++i) { + Node attrNode = attributes.getNamedItem(testAttrNames[i]); + assertNotNull(attrNode); + assertEquals(Node.ATTRIBUTE_NODE, attrNode.getNodeType()); + } + } + + public void testEvaluate() throws Exception { + String result = newXpathEngine().evaluate("count(test//node())", + testDocument); + assertEquals("3 elements and 3 text nodes", "6", result); + } + + public void testXpathPrefixChange() throws Exception { + String testDoc = "<t:test xmlns:t=\"urn:foo\"><t:bar/></t:test>"; + Document d = XMLUnit.buildControlDocument(testDoc); + HashMap m = new HashMap(); + m.put("foo", "urn:foo"); + NamespaceContext ctx = new SimpleNamespaceContext(m); + XpathEngine engine = newXpathEngine(); + engine.setNamespaceContext(ctx); + + NodeList l = engine.getMatchingNodes("//foo:bar", d); + assertEquals(1, l.getLength()); + assertEquals(Node.ELEMENT_NODE, l.item(0).getNodeType()); + + String s = engine.evaluate("count(foo:test//node())", d); + assertEquals("1", s); + } + + public void setUp() throws Exception { + testDocument = XMLUnit.buildControlDocument(testString); + } + + public AbstractXpathEngineTests(String name) { + super(name); + } + + +} \ No newline at end of file Property changes on: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/AbstractXpathEngineTests.java ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/jaxp13/test_Jaxp13XpathEngine.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/jaxp13/test_Jaxp13XpathEngine.java 2007-04-03 04:12:54 UTC (rev 169) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/jaxp13/test_Jaxp13XpathEngine.java 2007-04-03 04:28:28 UTC (rev 170) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 200, Jeff Martin, Tim Bacon +Copyright (c) 2006-2007, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without @@ -36,94 +36,18 @@ package org.custommonkey.xmlunit.jaxp13; -import javax.xml.transform.OutputKeys; -import junit.framework.TestCase; -import junit.framework.TestSuite; +import org.custommonkey.xmlunit.AbstractXpathEngineTests; +import org.custommonkey.xmlunit.XpathEngine; -import org.custommonkey.xmlunit.XMLUnit; - -import org.w3c.dom.Document; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - /** * JUnit test for Jaxp13XpathEngine */ -public class test_Jaxp13XpathEngine extends TestCase { - private String[] testAttrNames = {"attrOne", "attrTwo"}; - private String testString = - "<test><nodeWithoutAttributes>intellectual property rights </nodeWithoutAttributes>" - + "<nodeWithoutAttributes>make us all poorer </nodeWithoutAttributes>" - + "<nodeWithAttributes " + testAttrNames[0] + "=\"open source \" " - + testAttrNames[1] + "=\"is the answer \">free your code from its chains" - + "</nodeWithAttributes></test>"; - private Document testDocument; - private Jaxp13XpathEngine simpleXpathEngine = new Jaxp13XpathEngine(); +public class test_Jaxp13XpathEngine extends AbstractXpathEngineTests { - public void testGetMatchingNodesNoMatches() throws Exception { - NodeList nodeList = simpleXpathEngine.getMatchingNodes("toast", testDocument); - assertEquals(0, nodeList.getLength()); + protected XpathEngine newXpathEngine() { + return new Jaxp13XpathEngine(); } - public void testGetMatchingNodesMatchRootElement() throws Exception { - NodeList nodeList = simpleXpathEngine.getMatchingNodes("test", testDocument); - assertEquals(1, nodeList.getLength()); - assertEquals(Node.ELEMENT_NODE, nodeList.item(0).getNodeType()); - } - - public void testGetMatchingNodesMatchElement() throws Exception { - NodeList nodeList = simpleXpathEngine.getMatchingNodes( - "test/nodeWithoutAttributes", testDocument); - assertEquals(2, nodeList.getLength()); - assertEquals(Node.ELEMENT_NODE, nodeList.item(0).getNodeType()); - } - - public void testGetMatchingNodesMatchText() throws Exception { - NodeList nodeList = simpleXpathEngine.getMatchingNodes( - "test//text()", testDocument); - assertEquals(3, nodeList.getLength()); - assertEquals(Node.TEXT_NODE, nodeList.item(0).getNodeType()); - } - - public void testGetMatchingNodesCheckSubNodes() throws Exception { - NodeList nodeList = simpleXpathEngine.getMatchingNodes( - "test/nodeWithAttributes", testDocument); - assertEquals(1, nodeList.getLength()); - Node aNode; - - aNode = nodeList.item(0); - assertEquals(Node.ELEMENT_NODE, aNode.getNodeType()); - assertEquals(true, aNode.hasAttributes()); - assertEquals(true, aNode.hasChildNodes()); - - NodeList children = aNode.getChildNodes(); - int length = children.getLength(); - assertEquals(1, length); - for (int i=0; i < length; ++i) { - assertEquals(Node.TEXT_NODE, children.item(i).getNodeType()); - } - - NamedNodeMap attributes = aNode.getAttributes(); - int numAttrs = attributes.getLength(); - assertEquals(testAttrNames.length, numAttrs); - for (int i=0; i < testAttrNames.length; ++i) { - Node attrNode = attributes.getNamedItem(testAttrNames[i]); - assertNotNull(attrNode); - assertEquals(Node.ATTRIBUTE_NODE, attrNode.getNodeType()); - } - } - - public void testEvaluate() throws Exception { - String result = simpleXpathEngine.evaluate( - "count(test//node())", testDocument); - assertEquals("3 elements and 3 text nodes", "6", result); - } - - public void setUp() throws Exception { - testDocument = XMLUnit.buildControlDocument(testString); - } - public test_Jaxp13XpathEngine(String name) { super(name); } Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_SimpleXpathEngine.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_SimpleXpathEngine.java 2007-04-03 04:12:54 UTC (rev 169) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_SimpleXpathEngine.java 2007-04-03 04:28:28 UTC (rev 170) @@ -37,114 +37,47 @@ package org.custommonkey.xmlunit; import javax.xml.transform.OutputKeys; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import org.w3c.dom.Document; -import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; -import org.w3c.dom.NodeList; /** * JUnit test for SimpleXpathEngine */ -public class test_SimpleXpathEngine extends TestCase { - private String[] testAttrNames = {"attrOne", "attrTwo"}; - private String testString = - "<test><nodeWithoutAttributes>intellectual property rights </nodeWithoutAttributes>" - + "<nodeWithoutAttributes>make us all poorer </nodeWithoutAttributes>" - + "<nodeWithAttributes " + testAttrNames[0] + "=\"open source \" " - + testAttrNames[1] + "=\"is the answer \">free your code from its chains" - + "</nodeWithAttributes></test>"; - private Document testDocument; +public class test_SimpleXpathEngine extends AbstractXpathEngineTests { + private SimpleXpathEngine simpleXpathEngine = new SimpleXpathEngine(); + protected XpathEngine newXpathEngine() { + return simpleXpathEngine; + } + public void testGetXPathResultNode() throws Exception { - Node result = simpleXpathEngine.getXPathResultNode("test", testDocument); + Node result = simpleXpathEngine.getXPathResultNode("test", + testDocument); SimpleSerializer serializer = new SimpleSerializer(); serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); assertEquals(testString, serializer.serialize(result.getFirstChild())); } - public void testGetMatchingNodesNoMatches() throws Exception { - NodeList nodeList = simpleXpathEngine.getMatchingNodes("toast", testDocument); - assertEquals(0, nodeList.getLength()); - } - - public void testGetMatchingNodesMatchRootElement() throws Exception { - NodeList nodeList = simpleXpathEngine.getMatchingNodes("test", testDocument); - assertEquals(1, nodeList.getLength()); - assertEquals(Node.ELEMENT_NODE, nodeList.item(0).getNodeType()); - } - - public void testGetMatchingNodesMatchElement() throws Exception { - NodeList nodeList = simpleXpathEngine.getMatchingNodes( - "test/nodeWithoutAttributes", testDocument); - assertEquals(2, nodeList.getLength()); - assertEquals(Node.ELEMENT_NODE, nodeList.item(0).getNodeType()); - } - public void testGetMatchingNodesMatchText() throws Exception { if (isJava5OrNewer()) { // fails with "more recent" version of Xalan shipping with Java5 return; } - NodeList nodeList = simpleXpathEngine.getMatchingNodes( - "test//text()", testDocument); - assertEquals(3, nodeList.getLength()); - assertEquals(Node.TEXT_NODE, nodeList.item(0).getNodeType()); + super.testGetMatchingNodesMatchText(); } - public void testGetMatchingNodesCheckSubNodes() throws Exception { - NodeList nodeList = simpleXpathEngine.getMatchingNodes( - "test/nodeWithAttributes", testDocument); - assertEquals(1, nodeList.getLength()); - Node aNode; - - aNode = nodeList.item(0); - assertEquals(Node.ELEMENT_NODE, aNode.getNodeType()); - assertEquals(true, aNode.hasAttributes()); - assertEquals(true, aNode.hasChildNodes()); - - NodeList children = aNode.getChildNodes(); - int length = children.getLength(); - assertEquals(1, length); - for (int i=0; i < length; ++i) { - assertEquals(Node.TEXT_NODE, children.item(i).getNodeType()); - } - - NamedNodeMap attributes = aNode.getAttributes(); - int numAttrs = attributes.getLength(); - assertEquals(testAttrNames.length, numAttrs); - for (int i=0; i < testAttrNames.length; ++i) { - Node attrNode = attributes.getNamedItem(testAttrNames[i]); - assertNotNull(attrNode); - assertEquals(Node.ATTRIBUTE_NODE, attrNode.getNodeType()); - } - } - public void testEvaluate() throws Exception { if (isJava5OrNewer()) { // fails with "more recent" version of Xalan shipping with Java5 return; } - String result = simpleXpathEngine.evaluate( - "count(test//node())", testDocument); - assertEquals("3 elements and 3 text nodes", "6", result); + super.testEvaluate(); } - public void setUp() throws Exception { - testDocument = XMLUnit.buildControlDocument(testString); - } - public test_SimpleXpathEngine(String name) { super(name); } - public static TestSuite suite() { - return new TestSuite(test_SimpleXpathEngine.class); - } - private static boolean isJava5OrNewer() { try { Class.forName("java.net.Proxy"); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-04-04 12:01:52
|
Revision: 172 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=172&view=rev Author: bodewig Date: 2007-04-04 05:01:51 -0700 (Wed, 04 Apr 2007) Log Message: ----------- Move CountingNodeTester to examples Modified Paths: -------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/CountingNodeTester.java Added Paths: ----------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/examples/CountingNodeTester.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/examples/test_CountingNodeTester.java Removed Paths: ------------- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_CountingNodeTester.java Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/CountingNodeTester.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/CountingNodeTester.java 2007-04-03 04:44:20 UTC (rev 171) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/CountingNodeTester.java 2007-04-04 12:01:51 UTC (rev 172) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 2001, Jeff Martin, Tim Bacon +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without @@ -36,53 +36,19 @@ package org.custommonkey.xmlunit; -import org.w3c.dom.Node; - /** * Counts the number of nodes in a document to allow assertions to be made * using a NodeTest. * <br />Examples and more at <a href="http://xmlunit.sourceforge.net"/>xmlunit.sourceforge.net</a> * @see NodeTest + * @deprecated Use {@link + * org.custommonkey.xmlunit.examples.CountingNodeTester + * CountingNodeTester} instead. */ -public class CountingNodeTester implements NodeTester { - private final int expectedNumNodes; - private int actualNumNodes; +public class CountingNodeTester + extends org.custommonkey.xmlunit.examples.CountingNodeTester { public CountingNodeTester(int expectedNumNodes) { - this.expectedNumNodes = expectedNumNodes; + super(expectedNumNodes); } - - /** - * A single Node is always valid - * @param aNode - * @param forTest - */ - public void testNode(Node aNode, NodeTest forTest) { - actualNumNodes++; - } - - /** - * Called by NodeTest when all nodes have been iterated over: time to see - * if all the nodes that were expected were found. - * Note that this method also invokes {@link #resetCounter resetCounter} - * so that the instance can be reused. - * @exception true if expected num nodes == actual num nodes, - * false otherwise - */ - public void noMoreNodes(NodeTest forTest) throws NodeTestException { - int testedNodes = actualNumNodes; - resetCounter(); - if (testedNodes != expectedNumNodes) { - throw new NodeTestException("Counted " + testedNodes - + " node(s) but expected " + expectedNumNodes); - } - } - - /** - * Reset the counter so that an instance can be reused for another - * <code>NodeTest</code> - */ - public void resetCounter() { - actualNumNodes = 0; - } } \ No newline at end of file Copied: trunk/xmlunit/src/java/org/custommonkey/xmlunit/examples/CountingNodeTester.java (from rev 171, trunk/xmlunit/src/java/org/custommonkey/xmlunit/CountingNodeTester.java) =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/examples/CountingNodeTester.java (rev 0) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/examples/CountingNodeTester.java 2007-04-04 12:01:51 UTC (rev 172) @@ -0,0 +1,91 @@ +/* +****************************************************************** +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit.examples; + +import org.custommonkey.xmlunit.NodeTest; +import org.custommonkey.xmlunit.NodeTestException; +import org.custommonkey.xmlunit.NodeTester; +import org.w3c.dom.Node; + +/** + * Counts the number of nodes in a document to allow assertions to be made + * using a NodeTest. + * <br />Examples and more at <a href="http://xmlunit.sourceforge.net"/>xmlunit.sourceforge.net</a> + * @see NodeTest + */ +public class CountingNodeTester implements NodeTester { + private final int expectedNumNodes; + private int actualNumNodes; + + public CountingNodeTester(int expectedNumNodes) { + this.expectedNumNodes = expectedNumNodes; + } + + /** + * A single Node is always valid + * @param aNode + * @param forTest + */ + public void testNode(Node aNode, NodeTest forTest) { + actualNumNodes++; + } + + /** + * Called by NodeTest when all nodes have been iterated over: time to see + * if all the nodes that were expected were found. + * Note that this method also invokes {@link #resetCounter resetCounter} + * so that the instance can be reused. + * @exception true if expected num nodes == actual num nodes, + * false otherwise + */ + public void noMoreNodes(NodeTest forTest) throws NodeTestException { + int testedNodes = actualNumNodes; + resetCounter(); + if (testedNodes != expectedNumNodes) { + throw new NodeTestException("Counted " + testedNodes + + " node(s) but expected " + expectedNumNodes); + } + } + + /** + * Reset the counter so that an instance can be reused for another + * <code>NodeTest</code> + */ + public void resetCounter() { + actualNumNodes = 0; + } +} \ No newline at end of file Copied: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/examples/test_CountingNodeTester.java (from rev 171, trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_CountingNodeTester.java) =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/examples/test_CountingNodeTester.java (rev 0) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/examples/test_CountingNodeTester.java 2007-04-04 12:01:51 UTC (rev 172) @@ -0,0 +1,119 @@ +/* +****************************************************************** +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit.examples; + +import java.io.StringReader; + +import junit.framework.TestCase; + +import org.custommonkey.xmlunit.NodeTest; +import org.custommonkey.xmlunit.NodeTestException; +import org.w3c.dom.Node; + +/** + * JUnit test for CountingNodeTester + */ +public class test_CountingNodeTester extends TestCase { + private NodeTest test; + private CountingNodeTester tester; + + public void testPositivePath() throws Exception { + test = new NodeTest(new StringReader("<a><b>c</b></a>")); + tester = new CountingNodeTester(2); + test.performTest(tester, Node.ELEMENT_NODE); + + tester = new CountingNodeTester(1); + test.performTest(tester, Node.TEXT_NODE); + + tester = new CountingNodeTester(3); + test.performTest(tester, + new short[] {Node.TEXT_NODE, Node.ELEMENT_NODE}); + + tester = new CountingNodeTester(0); + test.performTest(tester, Node.COMMENT_NODE); + } + + public void testNegativePath() throws Exception { + test = new NodeTest(new StringReader("<a><b>c</b></a>")); + try { + tester = new CountingNodeTester(2); + test.performTest(tester, Node.TEXT_NODE); + fail("Expected NodeTestException"); + } catch (NodeTestException e) { + // failure, as expected + } + + try { + tester = new CountingNodeTester(1); + test.performTest(tester, Node.ELEMENT_NODE); + fail("Expected NodeTestException"); + } catch (NodeTestException e) { + // failure, as expected + } + + try { + tester = new CountingNodeTester(2); + test.performTest(tester, + new short[] {Node.TEXT_NODE, Node.ELEMENT_NODE}); + fail("Expected NodeTestException"); + } catch (NodeTestException e) { + // failure, as expected + } + + try { + tester = new CountingNodeTester(1); + test.performTest(tester, Node.COMMENT_NODE); + fail("Expected NodeTestException"); + } catch (NodeTestException e) { + // failure, as expected + } + + try { + tester = new CountingNodeTester(0); + test.performTest(tester, Node.TEXT_NODE); + fail("Expected NodeTestException"); + } catch (NodeTestException e) { + // failure, as expected + } + } + + public test_CountingNodeTester(String name) { + super(name); + } + +} + Deleted: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_CountingNodeTester.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_CountingNodeTester.java 2007-04-03 04:44:20 UTC (rev 171) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_CountingNodeTester.java 2007-04-04 12:01:51 UTC (rev 172) @@ -1,117 +0,0 @@ -/* -****************************************************************** -Copyright (c) 200, Jeff Martin, Tim Bacon -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - * Neither the name of the xmlunit.sourceforge.net nor the names - of its contributors may be used to endorse or promote products - derived from this software without specific prior written - permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. - -****************************************************************** -*/ - -package org.custommonkey.xmlunit; - -import java.io.StringReader; - -import junit.framework.TestCase; - -import org.w3c.dom.Node; - -/** - * JUnit test for CountingNodeTester - */ -public class test_CountingNodeTester extends TestCase { - private NodeTest test; - private CountingNodeTester tester; - - public void testPositivePath() throws Exception { - test = new NodeTest(new StringReader("<a><b>c</b></a>")); - tester = new CountingNodeTester(2); - test.performTest(tester, Node.ELEMENT_NODE); - - tester = new CountingNodeTester(1); - test.performTest(tester, Node.TEXT_NODE); - - tester = new CountingNodeTester(3); - test.performTest(tester, - new short[] {Node.TEXT_NODE, Node.ELEMENT_NODE}); - - tester = new CountingNodeTester(0); - test.performTest(tester, Node.COMMENT_NODE); - } - - public void testNegativePath() throws Exception { - test = new NodeTest(new StringReader("<a><b>c</b></a>")); - try { - tester = new CountingNodeTester(2); - test.performTest(tester, Node.TEXT_NODE); - fail("Expected NodeTestException"); - } catch (NodeTestException e) { - // failure, as expected - } - - try { - tester = new CountingNodeTester(1); - test.performTest(tester, Node.ELEMENT_NODE); - fail("Expected NodeTestException"); - } catch (NodeTestException e) { - // failure, as expected - } - - try { - tester = new CountingNodeTester(2); - test.performTest(tester, - new short[] {Node.TEXT_NODE, Node.ELEMENT_NODE}); - fail("Expected NodeTestException"); - } catch (NodeTestException e) { - // failure, as expected - } - - try { - tester = new CountingNodeTester(1); - test.performTest(tester, Node.COMMENT_NODE); - fail("Expected NodeTestException"); - } catch (NodeTestException e) { - // failure, as expected - } - - try { - tester = new CountingNodeTester(0); - test.performTest(tester, Node.TEXT_NODE); - fail("Expected NodeTestException"); - } catch (NodeTestException e) { - // failure, as expected - } - } - - public test_CountingNodeTester(String name) { - super(name); - } - -} - This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-04-11 12:19:25
|
Revision: 175 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=175&view=rev Author: bodewig Date: 2007-04-11 05:19:25 -0700 (Wed, 11 Apr 2007) Log Message: ----------- Unit tests for difference in attribute sequence Modified Paths: -------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java 2007-04-04 18:59:11 UTC (rev 174) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java 2007-04-11 12:19:25 UTC (rev 175) @@ -422,9 +422,11 @@ return new Integer(length); } - private void compareElementAttributes(Element control, Element test, - NamedNodeMap controlAttr, NamedNodeMap testAttr, - DifferenceListener listener) throws DifferenceFoundException { + void compareElementAttributes(Element control, Element test, + NamedNodeMap controlAttr, + NamedNodeMap testAttr, + DifferenceListener listener) + throws DifferenceFoundException { for (int i=0; i < controlAttr.getLength(); ++i) { Attr nextAttr = (Attr) controlAttr.item(i); if (isXMLNSAttribute(nextAttr)) { Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java 2007-04-04 18:59:11 UTC (rev 174) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java 2007-04-11 12:19:25 UTC (rev 175) @@ -39,6 +39,8 @@ import java.io.File; import java.io.FileWriter; import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; import javax.xml.parsers.DocumentBuilder; import junit.framework.TestCase; @@ -50,6 +52,7 @@ import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; @@ -660,6 +663,52 @@ .normalizeWhitespace("a\rb c\nd\te\r\n \tf")); } + public void testAttributeSequence() throws Exception { + Element control = document.createElement("foo"); + Element test = document.createElement("foo"); + OrderPreservingNamedNodeMap controlMap = + new OrderPreservingNamedNodeMap(); + OrderPreservingNamedNodeMap testMap = new OrderPreservingNamedNodeMap(); + for (int i = 0; i < 2; i++) { + int j = 1 - i; + Attr attrI = document.createAttribute("attr" + i); + attrI.setValue(String.valueOf(i)); + Attr attrJ = document.createAttribute("attr" + j); + attrJ.setValue(String.valueOf(j)); + + control.setAttributeNode(attrI); + controlMap.add(attrI); + test.setAttributeNode(attrJ); + testMap.add(attrJ); + } + engine.compareElementAttributes(control, test, controlMap, testMap, + listener); + assertEquals(ATTR_SEQUENCE_ID, listener.comparingWhat); + } + + public void testAttributeSequenceNS() throws Exception { + Element control = document.createElementNS("ns", "foo"); + Element test = document.createElementNS("ns", "foo"); + OrderPreservingNamedNodeMap controlMap = + new OrderPreservingNamedNodeMap(); + OrderPreservingNamedNodeMap testMap = new OrderPreservingNamedNodeMap(); + for (int i = 0; i < 2; i++) { + int j = 1 - i; + Attr attrI = document.createAttributeNS("ns", "attr" + i); + attrI.setValue(String.valueOf(i)); + Attr attrJ = document.createAttributeNS("ns", "attr" + j); + attrJ.setValue(String.valueOf(j)); + + control.setAttributeNode(attrI); + controlMap.add(attrI); + test.setAttributeNode(attrJ); + testMap.add(attrJ); + } + engine.compareElementAttributes(control, test, controlMap, testMap, + listener); + assertEquals(ATTR_SEQUENCE_ID, listener.comparingWhat); + } + private void listenToDifferences(String control, String test) throws SAXException, IOException { Document controlDoc = XMLUnit.buildControlDocument(control); @@ -679,14 +728,6 @@ document = documentBuilder.newDocument(); } - public test_DifferenceEngine(String name) { - super(name); - } - - public static TestSuite suite() { - return new TestSuite(test_DifferenceEngine.class); - } - private class SimpleComparisonController implements ComparisonController { public boolean haltComparison(Difference afterDifference) { return !afterDifference.isRecoverable(); @@ -734,5 +775,54 @@ tracing = active; } } + + private class OrderPreservingNamedNodeMap implements NamedNodeMap { + private ArrayList/* Attr */ nodes = new ArrayList(); + + void add(Attr attr) { + nodes.add(attr); + } + + public int getLength() { return nodes.size(); } + public Node item(int index) { return (Node) nodes.get(index); } + + public Node getNamedItem(String name) { + for (Iterator iter = nodes.iterator(); iter.hasNext(); ) { + Attr a = (Attr) iter.next(); + if (a.getName().equals(name)) { + return a; + } + } + return null; + } + + public Node getNamedItemNS(String ns, String localName) { + for (Iterator iter = nodes.iterator(); iter.hasNext(); ) { + Attr a = (Attr) iter.next(); + if (a.getLocalName().equals(localName) + && a.getNamespaceURI().equals(ns)) { + return a; + } + } + return null; + } + + // not implemented, not needed in our case + public Node removeNamedItem(String n) { + return fail(); + } + public Node removeNamedItemNS(String n1, String n2) { + return fail(); + } + public Node setNamedItem(Node n) { + return fail(); + } + public Node setNamedItemNS(Node n) { + return fail(); + } + private Node fail() { + throw new RuntimeException("not implemented"); + } + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-04-12 04:43:36
|
Revision: 177 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=177&view=rev Author: bodewig Date: 2007-04-11 21:43:38 -0700 (Wed, 11 Apr 2007) Log Message: ----------- Add a configuration option to ignore differences in attribute order Modified Paths: -------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java 2007-04-12 04:41:45 UTC (rev 176) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java 2007-04-12 04:43:38 UTC (rev 177) @@ -445,7 +445,8 @@ if (compareTo != null) { compareAttribute(nextAttr, compareTo, listener); - + + if (!XMLUnit.getIgnoreAttributeOrder()) { Attr attributeItem = (Attr) testAttr.item(i); String testAttrName = "[attribute absent]"; if (attributeItem != null) { @@ -453,6 +454,7 @@ } compare(attrName, testAttrName, nextAttr, compareTo, listener, ATTR_SEQUENCE); + } } else { compare(attrName, null, control, test, listener, ATTR_NAME_NOT_FOUND); Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java 2007-04-12 04:41:45 UTC (rev 176) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java 2007-04-12 04:43:38 UTC (rev 177) @@ -71,6 +71,7 @@ private static boolean ignoreComments = false; private static boolean normalize = false; private static boolean normalizeWhitespace = false; + private static boolean ignoreAttributeOrder = false; private static final String STRIP_WHITESPACE_STYLESHEET = new StringBuffer(XMLConstants.XML_DECLARATION) @@ -724,5 +725,35 @@ public static boolean getNormalizeWhitespace() { return normalizeWhitespace; } + + /** + * Whether to ignore the order of attributes on an element. + * + * <p>The order of attributes has never been relevant for XML + * documents, still XMLUnit will consider two pieces of XML + * not-identical (but similar) if they differ in order of + * attributes. Set this option to false to ignore the order.</p> + * + * <p>The default value is false for backwards compatibility + * reasons.</p> + */ + public static void setIgnoreAttributeOrder(boolean b) { + ignoreAttributeOrder = b; + } + + /** + * Whether to ignore the order of attributes on an element. + * + * <p>The order of attributes has never been relevant for XML + * documents, still XMLUnit will consider two pieces of XML + * not-identical (but similar) if they differ in order of + * attributes. Set this option to false to ignore the order.</p> + * + * <p>The default value is false for backwards compatibility + * reasons.</p> + */ + public static boolean getIgnoreAttributeOrder() { + return ignoreAttributeOrder; + } } Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java 2007-04-12 04:41:45 UTC (rev 176) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java 2007-04-12 04:43:38 UTC (rev 177) @@ -664,6 +664,17 @@ } public void testAttributeSequence() throws Exception { + testAttributeSequence(ATTR_SEQUENCE_ID); + resetListener(); + XMLUnit.setIgnoreAttributeOrder(true); + try { + testAttributeSequence(-1); + } finally { + XMLUnit.setIgnoreAttributeOrder(false); + } + } + + private void testAttributeSequence(int expected) throws Exception { Element control = document.createElement("foo"); Element test = document.createElement("foo"); OrderPreservingNamedNodeMap controlMap = @@ -683,10 +694,21 @@ } engine.compareElementAttributes(control, test, controlMap, testMap, listener); - assertEquals(ATTR_SEQUENCE_ID, listener.comparingWhat); + assertEquals(expected, listener.comparingWhat); } public void testAttributeSequenceNS() throws Exception { + testAttributeSequenceNS(ATTR_SEQUENCE_ID); + resetListener(); + XMLUnit.setIgnoreAttributeOrder(true); + try { + testAttributeSequenceNS(-1); + } finally { + XMLUnit.setIgnoreAttributeOrder(false); + } + } + + private void testAttributeSequenceNS(int expected) throws Exception { Element control = document.createElementNS("ns", "foo"); Element test = document.createElementNS("ns", "foo"); OrderPreservingNamedNodeMap controlMap = @@ -706,7 +728,7 @@ } engine.compareElementAttributes(control, test, controlMap, testMap, listener); - assertEquals(ATTR_SEQUENCE_ID, listener.comparingWhat); + assertEquals(expected, listener.comparingWhat); } private void listenToDifferences(String control, String test) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-04-13 11:31:16
|
Revision: 180 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=180&view=rev Author: bodewig Date: 2007-04-13 04:31:15 -0700 (Fri, 13 Apr 2007) Log Message: ----------- Make ignoreComments work at the DifferenceEngine level Modified Paths: -------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/XpathNodeTracker.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java 2007-04-13 08:11:02 UTC (rev 179) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java 2007-04-13 11:31:15 UTC (rev 180) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 2001, Jeff Martin, Tim Bacon +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without @@ -36,8 +36,10 @@ package org.custommonkey.xmlunit; +import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; +import java.util.List; import org.w3c.dom.Attr; import org.w3c.dom.CharacterData; @@ -246,15 +248,42 @@ */ protected void compareHasChildNodes(Node control, Node test, DifferenceListener listener) throws DifferenceFoundException { - Boolean controlHasChildren = control.hasChildNodes() - ? Boolean.TRUE : Boolean.FALSE; - Boolean testHasChildren = test.hasChildNodes() - ? Boolean.TRUE : Boolean.FALSE; + Boolean controlHasChildren = hasChildNodes(control); + Boolean testHasChildren = hasChildNodes(test); compare(controlHasChildren, testHasChildren, control, test, listener, HAS_CHILD_NODES); } /** + * Tests whether a Node has children, taking ignoreComments + * setting into account. + */ + private Boolean hasChildNodes(Node n) { + boolean flag = n.hasChildNodes(); + if (flag && XMLUnit.getIgnoreComments()) { + List nl = nodeList2List(n.getChildNodes()); + flag = nl.size() > 0; + } + return flag ? Boolean.TRUE : Boolean.FALSE; + } + + /** + * Returns the NodeList's Nodes as List, taking ignoreComments + * into account. + */ + static List nodeList2List(NodeList nl) { + int len = nl.getLength(); + ArrayList l = new ArrayList(len); + for (int i = 0; i < len; i++) { + Node n = nl.item(i); + if (!XMLUnit.getIgnoreComments() || !(n instanceof Comment)) { + l.add(n); + } + } + return l; + } + + /** * Compare the number of children, and if the same, compare the actual * children via their NodeLists. * @param control @@ -267,11 +296,11 @@ DifferenceListener listener, ElementQualifier elementQualifier) throws DifferenceFoundException { if (control.hasChildNodes() && test.hasChildNodes()) { - NodeList controlChildren = control.getChildNodes(); - NodeList testChildren = test.getChildNodes(); + List controlChildren = nodeList2List(control.getChildNodes()); + List testChildren = nodeList2List(test.getChildNodes()); - Integer controlLength = new Integer(controlChildren.getLength()); - Integer testLength = new Integer(testChildren.getLength()); + Integer controlLength = new Integer(controlChildren.size()); + Integer testLength = new Integer(testChildren.size()); compare(controlLength, testLength, control, test, listener, CHILD_NODELIST_LENGTH); compareNodeList(controlChildren, testChildren, @@ -292,23 +321,48 @@ * the test NodeList should be compared to the current child element in the * control NodeList. * @throws DifferenceFoundException + * @deprecated Use the version with List arguments instead */ protected void compareNodeList(final NodeList control, final NodeList test, final int numNodes, final DifferenceListener listener, final ElementQualifier elementQualifier) throws DifferenceFoundException { + compareNodeList(nodeList2List(control), nodeList2List(test), + numNodes, listener, elementQualifier); + } + /** + * Compare the contents of two node list one by one, assuming that order + * of children is NOT important: matching begins at same position in test + * list as control list. + * @param control + * @param test + * @param numNodes convenience parameter because the calling method should + * know the value already + * @param listener + * @param elementQualifier used to determine which of the child elements in + * the test NodeList should be compared to the current child element in the + * control NodeList. + * @throws DifferenceFoundException + */ + protected void compareNodeList(final List controlChildren, + final List testChildren, + final int numNodes, + final DifferenceListener listener, + final ElementQualifier elementQualifier) + throws DifferenceFoundException { + int j = 0; - final int lastTestNode = test.getLength() - 1; - testTracker.preloadNodeList(test); + final int lastTestNode = testChildren.size() - 1; + testTracker.preloadChildList(testChildren); HashMap/*<Node, Node>*/ matchingNodes = new HashMap(); HashMap/*<Node, Integer>*/ matchingNodeIndexes = new HashMap(); // first pass to find the matching nodes in control and test docs for (int i=0; i < numNodes; ++i) { - Node nextControl = control.item(i); + Node nextControl = (Node) controlChildren.get(i); boolean matchOnElement = nextControl instanceof Element; short findNodeType = nextControl.getNodeType(); int startAt = ( i > lastTestNode ? lastTestNode : i); @@ -317,12 +371,12 @@ boolean matchFound = false; while (!matchFound) { - if (findNodeType == test.item(j).getNodeType()) { + if (findNodeType == ((Node)testChildren.get(j)).getNodeType()) { matchFound = !matchOnElement || elementQualifier == null || elementQualifier - .qualifyForComparison((Element)nextControl, - (Element)test.item(j)); + .qualifyForComparison((Element) nextControl, + (Element) testChildren.get(j)); } if (!matchFound) { ++j; @@ -336,7 +390,7 @@ } } if (matchFound) { - matchingNodes.put(nextControl, test.item(j)); + matchingNodes.put(nextControl, testChildren.get(j)); matchingNodeIndexes.put(nextControl, new Integer(j)); } } @@ -346,7 +400,7 @@ // any other control nodes Collection matchingTestNodes = matchingNodes.values(); for (int i=0; i < numNodes; ++i) { - Node nextControl = control.item(i); + Node nextControl = (Node) controlChildren.get(i); Node nextTest = (Node) matchingNodes.get(nextControl); Integer testIndex = (Integer) matchingNodeIndexes.get(nextControl); if (nextTest == null) { @@ -357,8 +411,9 @@ boolean matchFound = false; while (!matchFound) { - if (test.item(j).getNodeType() == findNodeType - && !matchingTestNodes.contains(test.item(j))) { + if (((Node) testChildren.get(j)) + .getNodeType() == findNodeType + && !matchingTestNodes.contains(testChildren.get(j))) { matchFound = true; } else { ++j; @@ -371,7 +426,7 @@ } } } - nextTest = test.item(j); + nextTest = (Node) testChildren.get(j); testIndex = new Integer(j); } compareNode(nextControl, nextTest, listener, elementQualifier); @@ -531,7 +586,9 @@ */ protected void compareComment(Comment control, Comment test, DifferenceListener listener) throws DifferenceFoundException { - compareCharacterData(control, test, listener, COMMENT_VALUE); + if (!XMLUnit.getIgnoreComments()) { + compareCharacterData(control, test, listener, COMMENT_VALUE); + } } /** Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/XpathNodeTracker.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/XpathNodeTracker.java 2007-04-13 08:11:02 UTC (rev 179) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/XpathNodeTracker.java 2007-04-13 11:31:15 UTC (rev 180) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 2001, Jeff Martin, Tim Bacon +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without @@ -35,10 +35,10 @@ */ package org.custommonkey.xmlunit; +import java.util.ArrayList; +import java.util.HashMap; import java.util.Iterator; import java.util.List; -import java.util.ArrayList; -import java.util.HashMap; import java.util.Map; import org.w3c.dom.Attr; @@ -167,6 +167,21 @@ } /** + * Preload the items in a List by visiting each in turn + * Required for pieces of test XML whose node children can be visited + * out of sequence by a DifferenceEngine comparison + * @param nodeList the items to preload + */ + public void preloadChildList(List nodeList) { + currentEntry.trackNodesAsWellAsValues(true); + int length = nodeList.size(); + for (int i=0; i < length; ++i) { + visited((Node) nodeList.get(i)); + } + currentEntry.trackNodesAsWellAsValues(false); + } + + /** * @return the last visited node as an xpath-location String */ public String toXpathString() { Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java 2007-04-13 08:11:02 UTC (rev 179) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java 2007-04-13 11:31:15 UTC (rev 180) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 200, Jeff Martin, Tim Bacon +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without @@ -731,6 +731,55 @@ assertEquals(expected, listener.comparingWhat); } + public void testExtraComment() { + testExtraComment(true); + resetListener(); + XMLUnit.setIgnoreComments(true); + try { + testExtraComment(false); + } finally { + XMLUnit.setIgnoreComments(false); + } + } + + private void testExtraComment(boolean expectDifference) { + Element control = document.createElement("foo"); + Element test = document.createElement("foo"); + Comment c = document.createComment("bar"); + control.appendChild(c); + Element cChild = document.createElement("baz"); + control.appendChild(cChild); + Element tChild = document.createElement("baz"); + test.appendChild(tChild); + engine.compare(control, test, listener, null); + assertEquals(expectDifference, listener.different); + resetListener(); + engine.compare(test, control, listener, null); + assertEquals(expectDifference, listener.different); + } + + public void testCommentContent() { + testCommentContent(true); + resetListener(); + XMLUnit.setIgnoreComments(true); + try { + testCommentContent(false); + } finally { + XMLUnit.setIgnoreComments(false); + } + } + + private void testCommentContent(boolean expectDifference) { + Element control = document.createElement("foo"); + Element test = document.createElement("foo"); + Comment c = document.createComment("bar"); + control.appendChild(c); + Comment c2 = document.createComment("baz"); + test.appendChild(c2); + engine.compare(control, test, listener, null); + assertEquals(expectDifference, listener.different); + } + private void listenToDifferences(String control, String test) throws SAXException, IOException { Document controlDoc = XMLUnit.buildControlDocument(control); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-04-14 16:16:12
|
Revision: 184 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=184&view=rev Author: bodewig Date: 2007-04-14 09:16:11 -0700 (Sat, 14 Apr 2007) Log Message: ----------- sources of user guide Modified Paths: -------------- trunk/xmlunit/build.xml Added Paths: ----------- trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/ATourOfXMLUnit.java trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/ComparingPiecesOfXML.java trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/DOMTreeWalking.java trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/ValidatingXMLDocuments.java trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/XPathTests.java Modified: trunk/xmlunit/build.xml =================================================================== --- trunk/xmlunit/build.xml 2007-04-13 14:43:42 UTC (rev 183) +++ trunk/xmlunit/build.xml 2007-04-14 16:16:11 UTC (rev 184) @@ -8,6 +8,7 @@ <property name="out.dir" value="classes"/> <property name="dist.dir" value="dist"/> <property name="docs.dir" value="doc"/> + <property name="build.user.guide" value="userguide"/> <property file="build.properties"/> <available property="jaxp13+" classname="javax.xml.xpath.XPath"/> @@ -38,6 +39,7 @@ <fileset dir="${out.dir}" includes="**/*.class"/> <fileset dir="${test.report.dir}" includes="**/TEST*.*"/> <fileset dir="${dist.dir}"/> + <fileset dir="${build.user.guide}"/> </delete> </target> @@ -180,4 +182,14 @@ <delete file="${dist.name}-src.tar" /> </target> + <target name="compile-userguide-examples" depends="compile"> + <mkdir dir="${build.user.guide}"/> + <javac srcdir="src/user-guide" includes="org/" + destdir="${build.user.guide}" source="1.3" target="1.2"> + <classpath> + <pathelement location="${junit.lib}"/> + <pathelement location="${out.dir}"/> + </classpath> + </javac> + </target> </project> Added: trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/ATourOfXMLUnit.java =================================================================== --- trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/ATourOfXMLUnit.java (rev 0) +++ trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/ATourOfXMLUnit.java 2007-04-14 16:16:11 UTC (rev 184) @@ -0,0 +1,255 @@ +/* +****************************************************************** +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit.examples; + +import java.io.File; +import java.io.FileReader; +import java.util.List; + +import javax.xml.transform.stream.StreamSource; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.Text; + +import org.custommonkey.xmlunit.*; + +/** + * All code snippets from the "A Tour of XMLUnit" section of the the + * User Guide. + */ +public class ATourOfXMLUnit extends XMLTestCase { + public ATourOfXMLUnit(String name) { + super(name); + } + + // never invoked + private void configure() { + System.setProperty("javax.xml.parsers.DocumentBuilderFactory", + "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); + System.setProperty("javax.xml.parsers.SAXParserFactory", + "org.apache.xerces.jaxp.SAXParserFactoryImpl"); + System.setProperty("javax.xml.transform.TransformerFactory", + "org.apache.xalan.processor.TransformerFactoryImpl"); + XMLUnit + .setControlParser("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); + XMLUnit + .setTestParser("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); + XMLUnit + .setSAXParserFactory("org.apache.xerces.jaxp.SAXParserFactoryImpl"); + XMLUnit + .setTransformerFactory("org.apache.xalan.processor.TransformerFactoryImpl"); + } + + public void testForEquality() throws Exception { + String myControlXML = "<msg><uuid>0x00435A8C</uuid></msg>"; + String myTestXML = "<msg><localId>2376</localId></msg>"; + assertXMLEqual("Comparing test xml to control xml", + myControlXML, myTestXML); + } + + public void testXMLIdentical()throws Exception { + String myControlXML = + "<struct><int>3</int><boolean>false</boolean></struct>"; + String myTestXML = + "<struct><boolean>false</boolean><int>3</int></struct>"; + Diff myDiff = new Diff(myControlXML, myTestXML); + assertTrue("XML similar " + myDiff.toString(), + myDiff.similar()); + assertTrue("XML identical " + myDiff.toString(), + myDiff.identical()); + } + + public void testAllDifferences() throws Exception { + String myControlXML = "<news><item id=\"1\">War</item>" + + "<item id=\"2\">Plague</item>" + + "<item id=\"3\">Famine</item></news>"; + String myTestXML = "<news><item id=\"1\">Peace</item>" + + "<item id=\"2\">Health</item>" + + "<item id=\"3\">Plenty</item></news>"; + DetailedDiff myDiff = new DetailedDiff(new Diff(myControlXML, + myTestXML)); + List allDifferences = myDiff.getAllDifferences(); + assertEquals(myDiff.toString(), 2, allDifferences.size()); + } + + public void testCompareToSkeletonXML() throws Exception { + String myControlXML = "<location><street-address>22 any street</street-address><postcode>XY00 99Z</postcode></location>"; + String myTestXML = "<location><street-address>20 east cheap</street-address><postcode>EC3M 1EB</postcode></location>"; + DifferenceListener myDifferenceListener = new IgnoreTextAndAttributeValuesDifferenceListener(); + Diff myDiff = new Diff(myControlXML, myTestXML); + myDiff.overrideDifferenceListener(myDifferenceListener); + assertTrue("test XML matches control skeleton XML", + myDiff.similar()); + } + + public void testRepeatedChildElements() throws Exception { + String myControlXML = "<suite>" + + "<test status=\"pass\">FirstTestCase</test>" + + "<test status=\"pass\">SecondTestCase</test></suite>"; + String myTestXML = "<suite>" + + "<test status=\"pass\">SecondTestCase</test>" + + "<test status=\"pass\">FirstTestCase</test></suite>"; + assertXMLNotEqual("Repeated child elements in different sequence order are not equal by default", + myControlXML, myTestXML); + Diff myDiff = new Diff(myControlXML, myTestXML); + myDiff.overrideElementQualifier(new ElementNameAndTextQualifier()); + assertXMLEqual("But they are equal when an ElementQualifier controls which test element is compared with each control element", + myDiff, true); + } + + public void testXSLTransformation() throws Exception { + String myInputXML = "..."; + File myStylesheetFile = new File("..."); + Transform myTransform = new Transform(myInputXML, myStylesheetFile); + String myExpectedOutputXML = "..."; + Diff myDiff = new Diff(myExpectedOutputXML, myTransform); + assertTrue("XSL transformation worked as expected", myDiff.similar()); + } + + public void testAnotherXSLTransformation() throws Exception { + File myInputXMLFile = new File("..."); + File myStylesheetFile = new File("..."); + Transform myTransform = new Transform( + new StreamSource(myInputXMLFile), + new StreamSource(myStylesheetFile)); + Document myExpectedOutputXML = + XMLUnit.buildDocument(XMLUnit.getControlParser(), + new FileReader("...")); + Diff myDiff = new Diff(myExpectedOutputXML, + myTransform.getResultDocument()); + assertTrue("XSL transformation worked as expected", myDiff.similar()); + } + + public void testValidation() throws Exception { + XMLUnit.getTestDocumentBuilderFactory().setValidating(true); + // As the document is parsed it is validated against its referenced DTD + Document myTestDocument = XMLUnit.buildTestDocument("..."); + String mySystemId = "..."; + String myDTDUrl = new File("...").toURL().toExternalForm(); + Validator myValidator = new Validator(myTestDocument, mySystemId, + myDTDUrl); + assertTrue("test document validates against unreferenced DTD", + myValidator.isValid()); + } + + public void testXPaths() throws Exception { + String mySolarSystemXML = "<solar-system>" + + "<planet name='Earth' position='3' supportsLife='yes'/>" + + "<planet name='Venus' position='4'/></solar-system>"; + assertXpathExists("//planet[@name='Earth']", mySolarSystemXML); + assertNotXpathExists("//star[@name='alpha centauri']", + mySolarSystemXML); + assertXpathsEqual("//planet[@name='Earth']", + "//planet[@position='3']", mySolarSystemXML); + assertXpathsNotEqual("//planet[@name='Venus']", + "//planet[@supportsLife='yes']", + mySolarSystemXML); + } + + public void testXPathValues() throws Exception { + String myJavaFlavours = "<java-flavours>" + + "<jvm current='some platforms'>1.1.x</jvm>" + + "<jvm current='no'>1.2.x</jvm>" + + "<jvm current='yes'>1.3.x</jvm>" + + "<jvm current='yes' latest='yes'>1.4.x</jvm></javaflavours>"; + assertXpathEvaluatesTo("2", "count(//jvm[@current='yes'])", + myJavaFlavours); + assertXpathValuesEqual("//jvm[4]/@latest", "//jvm[4]/@current", + myJavaFlavours); + assertXpathValuesNotEqual("//jvm[2]/@current", + "//jvm[3]/@current", myJavaFlavours); + } + + public void testXpathsInHTML() throws Exception { + String someBadlyFormedHTML = "<html><title>Ugh</title>" + + "<body><h1>Heading<ul>" + + "<li id='1'>Item One<li id='2'>Item Two"; + TolerantSaxDocumentBuilder tolerantSaxDocumentBuilder = + new TolerantSaxDocumentBuilder(XMLUnit.getTestParser()); + HTMLDocumentBuilder htmlDocumentBuilder = + new HTMLDocumentBuilder(tolerantSaxDocumentBuilder); + Document wellFormedDocument = + htmlDocumentBuilder.parse(someBadlyFormedHTML); + assertXpathEvaluatesTo("Item One", "/html/body//li[@id='1']", + wellFormedDocument); + } + + public void testCountingNodeTester() throws Exception { + String testXML = "<fibonacci><val>1</val><val>2</val><val>3</val>" + + "<val>5</val><val>9</val></fibonacci>"; + CountingNodeTester countingNodeTester = new CountingNodeTester(4); + assertNodeTestPasses(testXML, countingNodeTester, Node.TEXT_NODE); + } + + public void testCustomNodeTester() throws Exception { + String testXML = "<fibonacci><val>1</val><val>2</val><val>3</val>" + + "<val>5</val><val>9</val></fibonacci>"; + NodeTest nodeTest = new NodeTest(testXML); + assertNodeTestPasses(nodeTest, new FibonacciNodeTester(), + new short[] {Node.TEXT_NODE, + Node.ELEMENT_NODE}, + true); + } + + private class FibonacciNodeTester extends AbstractNodeTester { + private int nextVal = 1, lastVal = 1, priorVal = 0; + + public void testText(Text text) throws NodeTestException { + int val = Integer.parseInt(text.getData()); + if (nextVal != val) { + throw new NodeTestException("Incorrect value", text); + } + nextVal = val + lastVal; + priorVal = lastVal; + lastVal = val; + } + + public void testElement(Element element) throws NodeTestException { + String name = element.getLocalName(); + if ("fibonacci".equals(name) || "val".equals(name)) { + return; + } + throw new NodeTestException("Unexpected element", element); + } + + public void noMoreNodes(NodeTest nodeTest) throws NodeTestException { + } + } +} + Property changes on: trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/ATourOfXMLUnit.java ___________________________________________________________________ Name: svn:executable + * Name: svn:eol-style + native Added: trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/ComparingPiecesOfXML.java =================================================================== --- trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/ComparingPiecesOfXML.java (rev 0) +++ trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/ComparingPiecesOfXML.java 2007-04-14 16:16:11 UTC (rev 184) @@ -0,0 +1,129 @@ +/* +****************************************************************** +Copyright (c) 2007, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit.examples; + +import java.util.Arrays; +import java.util.List; + +import org.custommonkey.xmlunit.*; +import org.w3c.dom.*; + +/** + * Code from "Comparing Pieces of XML" section of User's Guide + */ +public class ComparingPiecesOfXML extends XMLTestCase { + + class MyDifferenceListener implements DifferenceListener { + private boolean calledFlag = false; + public boolean called() { return calledFlag; } + + public int differenceFound(Difference difference) { + calledFlag = true; + return RETURN_ACCEPT_DIFFERENCE; + } + + public void skippedComparison(Node control, Node test) { + } + } + + private void usingDifferenceEngineDirectly() { + ComparisonController myComparisonController = null; + Node controlNode = null; + Node testNode = null; + ElementQualifier myElementQualifier = null; + + DifferenceEngine engine = new DifferenceEngine(myComparisonController); + MyDifferenceListener listener = new MyDifferenceListener(); + engine.compare(controlNode, testNode, listener, + myElementQualifier); + System.err.println("There have been " + + (listener.called() ? "" : "no ") + + "differences."); + } + + public class HaltOnNonRecoverable implements ComparisonController { + public boolean haltComparison(Difference afterDifference) { + return !afterDifference.isRecoverable(); + } + } + + public static class IgnoreDoctype implements DifferenceListener { + private static final int[] IGNORE = new int[] { + DifferenceConstants.HAS_DOCTYPE_DECLARATION_ID, + DifferenceConstants.DOCTYPE_NAME_ID, + DifferenceConstants.DOCTYPE_PUBLIC_ID_ID, + DifferenceConstants.DOCTYPE_SYSTEM_ID_ID + }; + + static { + Arrays.sort(IGNORE); + } + + public int differenceFound(Difference difference) { + return Arrays.binarySearch(IGNORE, difference.getId()) >= 0 + ? RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL + : RETURN_ACCEPT_DIFFERENCE; + } + + public void skippedComparison(Node control, Node test) { + } + } + + private void comparingTwoPiecesOfXMLUsingDiff() throws Exception { + Diff d = new Diff("<a><b/><c/></a>", "<a><c/><b/></a>"); + assertFalse(d.identical()); // CHILD_NODELIST_SEQUENCE Difference + assertTrue(d.similar()); + } + + private void FindingAllDifferencesUsingDetailedDiff() throws Exception { + Diff d = new Diff("<a><b/><c/></a>", "<a><c/><b/></a>"); + DetailedDiff dd = new DetailedDiff(d); + dd.overrideElementQualifier(null); + assertFalse(dd.similar()); + List l = dd.getAllDifferences(); + assertEquals(2, l.size()); // expexted <b/> but was <c/> and vice versa + } + + private void junit3() throws Exception { + String CONTROL = null; + String TEST = null; + Diff d = new Diff(CONTROL, TEST); + assertTrue("expected pieces to be similar, " + d.toString(), + d.similar()); + assertXMLEqual("expected pieces to be similar", CONTROL, TEST); + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/ComparingPiecesOfXML.java ___________________________________________________________________ Name: svn:executable + * Name: svn:eol-style + native Added: trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/DOMTreeWalking.java =================================================================== --- trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/DOMTreeWalking.java (rev 0) +++ trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/DOMTreeWalking.java 2007-04-14 16:16:11 UTC (rev 184) @@ -0,0 +1,76 @@ +/* +****************************************************************** +Copyright (c) 2007, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit.examples; + +import junit.framework.TestCase; + +import org.custommonkey.xmlunit.*; +import org.w3c.dom.*; + +/** + * Code from "DOM Tree Walking" section of User's Guide + */ +public class DOMTreeWalking extends TestCase { + + private String myXML = null; + static final String ATTRIBUTE_NAME = null; + + private void AccessingAttributesInANodeTest() throws Exception { + NodeTest nt = new NodeTest(myXML); + NodeTester tester = new MyNodeTester(); + nt.performTest(tester, Node.ELEMENT_NODE); + } + + private void AccessingAttributesInANodeTestAbstractNodeTesterVersion() throws Exception { + NodeTest nt = new NodeTest(myXML); + NodeTester tester = new AbstractNodeTester() { + public void testElement(Element element) throws NodeTestException { + Attr attributeToTest = element.getAttributeNode(ATTRIBUTE_NAME); + } + }; + nt.performTest(tester, Node.ELEMENT_NODE); + } + + static class MyNodeTester implements NodeTester { + public void testNode(Node aNode, NodeTest test) { + Element anElement = (Element) aNode; + Attr attributeToTest = anElement.getAttributeNode(ATTRIBUTE_NAME); + } + + public void noMoreNodes(NodeTest test) {} + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/DOMTreeWalking.java ___________________________________________________________________ Name: svn:executable + * Name: svn:eol-style + native Added: trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/ValidatingXMLDocuments.java =================================================================== --- trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/ValidatingXMLDocuments.java (rev 0) +++ trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/ValidatingXMLDocuments.java 2007-04-14 16:16:11 UTC (rev 184) @@ -0,0 +1,96 @@ +/* +****************************************************************** +Copyright (c) 2007, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit.examples; + +import java.io.*; +import org.custommonkey.xmlunit.*; +import org.xml.sax.*; + +/** + * Code from "Validating XML Documents" section of User's Guide + */ +public class ValidatingXMLDocuments { + + private String myXmlDocument = null; + private String myDTD = null; + + private void ValidatingAgainstTheDTDDefinedInDOCTYPE() throws Exception { + InputSource is = new InputSource(new FileInputStream(myXmlDocument)); + Validator v = new Validator(is); + boolean isValid = v.isValid(); + } + + private void ValidatingAPieceOfXMLThatDoesntContainADOCTYPE() throws Exception { + String myPublicId = null; + + InputSource is = new InputSource(new FileInputStream(myXmlDocument)); + Validator v = new Validator(is, + (new File(myDTD)).toURI().toURL().toString(), + myPublicId); + boolean isValid = v.isValid(); + } + + private void ValidatingAgainstALocalDTD() throws Exception { + InputSource is = new InputSource(new FileInputStream(myXmlDocument)); + Validator v = new Validator(is, + (new File(myDTD)).toURI().toURL().toString()); + boolean isValid = v.isValid(); + } + + private void ValidatingAgainstDTDUsingApachesXMLResolverAndAXMLCatalog() throws Exception { + InputSource is = new InputSource(new FileInputStream(myXmlDocument)); + XMLUnit.setControlEntityResolver(new CatalogResolver()); + Validator v = new Validator(is); + boolean isValid = v.isValid(); + } + + private void ValidatingAgainstALocalXMLSchema() throws Exception { + String myXmlSchemaFile = null; + + InputSource is = new InputSource(new FileInputStream(myXmlDocument)); + Validator v = new Validator(is); + v.useXMLSchema(true); + v.setJAXP12SchemaSource(new File(myXmlSchemaFile)); + boolean isValid = v.isValid(); + } + + private static class CatalogResolver implements EntityResolver { + public InputSource resolveEntity(String p, String s) { + return null; + } + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/ValidatingXMLDocuments.java ___________________________________________________________________ Name: svn:executable + * Name: svn:eol-style + native Added: trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/XPathTests.java =================================================================== --- trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/XPathTests.java (rev 0) +++ trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/XPathTests.java 2007-04-14 16:16:11 UTC (rev 184) @@ -0,0 +1,79 @@ +/* +****************************************************************** +Copyright (c) 2007, Jeff Martin, Tim Bacon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +****************************************************************** +*/ + +package org.custommonkey.xmlunit.examples; + +import java.util.HashMap; +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.custommonkey.xmlunit.*; + +/** + * Code from "XPath Tests" section of User's Guide + */ +public class XPathTests extends TestCase { + + private void MatchingAnXPathSelectionAgainstARegularExpression() throws Exception { + Document doc = null; + String regex = null; + String xpath = null; + String message = null; + + XpathEngine engine = XMLUnit.newXpathEngine(); + String value = engine.evaluate(xpath, doc); + Assert.assertTrue(message, value.matches(regex)); + } + + private void UsingNamespacesInXPathTests() throws Exception { + String testDoc = "<t:test xmlns:t=\"urn:foo\"><t:bar/></t:test>"; + Document d = XMLUnit.buildControlDocument(testDoc); + HashMap m = new HashMap(); + m.put("foo", "urn:foo"); + + NamespaceContext ctx = new SimpleNamespaceContext(m); + XpathEngine engine = XMLUnit.newXpathEngine(); + engine.setNamespaceContext(ctx); + + NodeList l = engine.getMatchingNodes("//foo:bar", d); + assertEquals(1, l.getLength()); + assertEquals(Node.ELEMENT_NODE, l.item(0).getNodeType()); + } + +} Property changes on: trunk/xmlunit/src/user-guide/org/custommonkey/xmlunit/examples/XPathTests.java ___________________________________________________________________ Name: svn:executable + * Name: svn:eol-style + native This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-04-14 16:31:22
|
Revision: 186 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=186&view=rev Author: bodewig Date: 2007-04-14 09:31:23 -0700 (Sat, 14 Apr 2007) Log Message: ----------- copy DifferenceListener Delegate in Prototype constructor Modified Paths: -------------- trunk/xmlunit/build.xml trunk/xmlunit/src/java/org/custommonkey/xmlunit/Diff.java Modified: trunk/xmlunit/build.xml =================================================================== --- trunk/xmlunit/build.xml 2007-04-14 16:18:35 UTC (rev 185) +++ trunk/xmlunit/build.xml 2007-04-14 16:31:23 UTC (rev 186) @@ -35,7 +35,7 @@ </target> <target name="clean" depends="init"> - <delete includeEmptyDirs="true" > + <delete includeEmptyDirs="true" quiet="true"> <fileset dir="${out.dir}" includes="**/*.class"/> <fileset dir="${test.report.dir}" includes="**/TEST*.*"/> <fileset dir="${dist.dir}"/> Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/Diff.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/Diff.java 2007-04-14 16:18:35 UTC (rev 185) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/Diff.java 2007-04-14 16:31:23 UTC (rev 186) @@ -81,7 +81,7 @@ private boolean haltComparison = false; private StringBuffer messages; private DifferenceEngine differenceEngine; - private DifferenceListener differenceListenerDelegate; + private DifferenceListener differenceListenerDelegate; private ElementQualifier elementQualifierDelegate; /** @@ -166,6 +166,7 @@ protected Diff(Diff prototype) { this(prototype.controlDoc, prototype.testDoc, prototype.differenceEngine, prototype.elementQualifierDelegate); + this.differenceListenerDelegate = prototype.differenceListenerDelegate; } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-04-17 04:02:13
|
Revision: 189 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=189&view=rev Author: bodewig Date: 2007-04-16 21:02:14 -0700 (Mon, 16 Apr 2007) Log Message: ----------- Make XSLT version used for internal stylesheets configurable Modified Paths: -------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/SimpleXpathEngine.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/XSLTConstants.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/exceptions/ConfigurationException.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Constants.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Transform.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_XMLUnit.java Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/SimpleXpathEngine.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/SimpleXpathEngine.java 2007-04-17 03:59:29 UTC (rev 188) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/SimpleXpathEngine.java 2007-04-17 04:02:14 UTC (rev 189) @@ -73,7 +73,7 @@ */ private StringBuffer getXSLTBase() { StringBuffer result = new StringBuffer(XML_DECLARATION) - .append(XSLT_START); + .append(XMLUnit.getXSLTStart()); String tmp = result.toString(); int close = tmp.lastIndexOf('>'); if (close == -1) { Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java 2007-04-17 03:59:29 UTC (rev 188) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java 2007-04-17 04:02:14 UTC (rev 189) @@ -1,6 +1,6 @@ /* ***************************************************************** -Copyright (c) 2001, Jeff Martin, Tim Bacon +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without @@ -48,6 +48,9 @@ import java.io.IOException; import java.io.Reader; import java.io.StringReader; +import java.text.NumberFormat; +import java.text.ParseException; +import java.util.Locale; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -72,19 +75,33 @@ private static boolean normalize = false; private static boolean normalizeWhitespace = false; private static boolean ignoreAttributeOrder = false; + private static String xsltVersion = "1.0"; - private static final String STRIP_WHITESPACE_STYLESHEET + private static final String XSLT_VERSION_START = " version=\""; + private static final String XSLT_VERSION_END = "\">"; + + private static final String STRIP_WHITESPACE_STYLESHEET_START = new StringBuffer(XMLConstants.XML_DECLARATION) - .append(XSLTConstants.XSLT_START) + .append(XSLTConstants.XSLT_START_NO_VERSION) + .append(XSLT_VERSION_START) + .toString(); + + private static final String STRIP_WHITESPACE_STYLESHEET_END + = new StringBuffer(XSLT_VERSION_END) .append(XSLTConstants.XSLT_XML_OUTPUT_NOINDENT) .append(XSLTConstants.XSLT_STRIP_WHITESPACE) .append(XSLTConstants.XSLT_IDENTITY_TEMPLATE) .append(XSLTConstants.XSLT_END) .toString(); - private static final String STRIP_COMMENTS_STYLESHEET + private static final String STRIP_COMMENTS_STYLESHEET_START = new StringBuffer(XMLConstants.XML_DECLARATION) - .append(XSLTConstants.XSLT_START) + .append(XSLTConstants.XSLT_START_NO_VERSION) + .append(XSLT_VERSION_START) + .toString(); + + private static final String STRIP_COMMENTS_STYLESHEET_END + = new StringBuffer(XSLT_VERSION_END) .append(XSLTConstants.XSLT_XML_OUTPUT_NOINDENT) .append(XSLTConstants.XSLT_STRIP_COMMENTS_TEMPLATE) .append(XSLTConstants.XSLT_END) @@ -418,23 +435,33 @@ return newFactory; } + private static String getStripWhitespaceStylesheet() { + return STRIP_WHITESPACE_STYLESHEET_START + getXSLTVersion() + + STRIP_WHITESPACE_STYLESHEET_END; + } + /** - * Obtain the transformation that will strip whitespace from a DOM containing - * empty Text nodes + * Obtain the transformation that will strip whitespace from a DOM + * containing empty Text nodes * @param forDocument * @return a <code>Transform</code> to do the whitespace stripping */ public static Transform getStripWhitespaceTransform(Document forDocument) { - return new Transform(forDocument, STRIP_WHITESPACE_STYLESHEET); + return new Transform(forDocument, getStripWhitespaceStylesheet()); } + private static String getStripCommentsStylesheet() { + return STRIP_COMMENTS_STYLESHEET_START + getXSLTVersion() + + STRIP_COMMENTS_STYLESHEET_END; + } + /** * Obtain the transformation that will strip comments from a DOM. * @param forDocument * @return a <code>Transform</code> to do the whitespace stripping */ public static Transform getStripCommentsTransform(Document forDocument) { - return new Transform(forDocument, STRIP_COMMENTS_STYLESHEET); + return new Transform(forDocument, getStripCommentsStylesheet()); } /** @@ -685,5 +712,43 @@ public static boolean getIgnoreAttributeOrder() { return ignoreAttributeOrder; } + + /** + * Sets the XSLT version to set on stylesheets used internally. + * + * <p>Defaults to "1.0".</p> + * + * @throws ConfigurationException if the argument cannot be parsed + * as a positive number. + */ + public static void setXSLTVersion(String s) { + try { + Number n = NumberFormat.getInstance(Locale.US).parse(s); + if (n.doubleValue() < 0) { + throw new ConfigurationException(s + " doesn't reperesent a" + + " positive number."); + } + } catch (ParseException e) { + throw new ConfigurationException(e); + } + xsltVersion = s; + } + + /** + * The XSLT version set on stylesheets used internally. + * + * <p>Defaults to "1.0".</p> + */ + public static String getXSLTVersion() { + return xsltVersion; + } + + /** + * XSLT stylesheet element using the configured XSLT version. + */ + static String getXSLTStart() { + return XSLTConstants.XSLT_START_NO_VERSION + + XSLT_VERSION_START + getXSLTVersion() + XSLT_VERSION_END; + } } Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/XSLTConstants.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/XSLTConstants.java 2007-04-17 03:59:29 UTC (rev 188) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/XSLTConstants.java 2007-04-17 04:02:14 UTC (rev 189) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 2001, Jeff Martin, Tim Bacon +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without @@ -41,34 +41,40 @@ */ public interface XSLTConstants extends XMLConstants { /** - * <xsl:stylesheet> + * <xsl:stylesheet */ - public static final String XSLT_START = - "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">"; + String XSLT_START_NO_VERSION = + "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\""; /** + * <xsl:stylesheet ... version="1.0"> + */ + String XSLT_START = + XSLT_START_NO_VERSION + " version=\"1.0\">"; + + /** * <xsl:output> for XML with no indentation */ - public static final String XSLT_XML_OUTPUT_NOINDENT = + String XSLT_XML_OUTPUT_NOINDENT = "<xsl:output method=\"xml\" version=\"1.0\" indent=\"no\"/>"; /** * <xsl:strip-space> for all elements */ - public static final String XSLT_STRIP_WHITESPACE = + String XSLT_STRIP_WHITESPACE = "<xsl:strip-space elements=\"*\"/>"; /** * <xsl:template> to copy the current nodeset into the output tree */ - public static final String XSLT_IDENTITY_TEMPLATE = + String XSLT_IDENTITY_TEMPLATE = "<xsl:template match=\"/\"><xsl:copy-of select=\".\"/></xsl:template>"; /** * <xsl:template> to copy the current nodeset into the * output tree while stripping comments. */ - public static final String XSLT_STRIP_COMMENTS_TEMPLATE = + String XSLT_STRIP_COMMENTS_TEMPLATE = "<xsl:template match=\"node()[not(self::comment())]|@*\">" + "<xsl:copy><xsl:apply-templates select=\"node()[not(self::comment())]|@*\"/></xsl:copy>" + "</xsl:template>"; @@ -76,5 +82,5 @@ /** * </xsl:stylesheet> */ - public static final String XSLT_END = "</xsl:stylesheet>"; + String XSLT_END = "</xsl:stylesheet>"; } Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/exceptions/ConfigurationException.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/exceptions/ConfigurationException.java 2007-04-17 03:59:29 UTC (rev 188) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/exceptions/ConfigurationException.java 2007-04-17 04:02:14 UTC (rev 189) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 2001, Jeff Martin, Tim Bacon +Copyright (c) 2006-2007, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without @@ -44,4 +44,7 @@ public ConfigurationException(Throwable t) { super(t != null ? t.getMessage() : null, t); } + public ConfigurationException(String s) { + super(s, null); + } } \ No newline at end of file Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Constants.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Constants.java 2007-04-17 03:59:29 UTC (rev 188) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Constants.java 2007-04-17 04:02:14 UTC (rev 189) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 200, Jeff Martin, Tim Bacon +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Transform.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Transform.java 2007-04-17 03:59:29 UTC (rev 188) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Transform.java 2007-04-17 04:02:14 UTC (rev 189) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 200, Jeff Martin, Tim Bacon +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_XMLUnit.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_XMLUnit.java 2007-04-17 03:59:29 UTC (rev 188) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_XMLUnit.java 2007-04-17 04:02:14 UTC (rev 189) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 200, Jeff Martin, Tim Bacon +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without @@ -40,6 +40,7 @@ import junit.framework.TestCase; import junit.framework.TestSuite; +import org.custommonkey.xmlunit.exceptions.ConfigurationException; import org.w3c.dom.Document; import org.xml.sax.EntityResolver; import org.xml.sax.helpers.DefaultHandler; @@ -112,10 +113,26 @@ assertTrue(diff.similar()); } - /** - * Returns a TestSuite containing this test case. - */ - public static TestSuite suite(){ - return new TestSuite(test_XMLUnit.class); + public void testXSLTVersion() { + try { + assertEquals("1.0", XMLUnit.getXSLTVersion()); + assertEquals(XSLTConstants.XSLT_START, XMLUnit.getXSLTStart()); + XMLUnit.setXSLTVersion("2.0"); + assertTrue(XMLUnit.getXSLTStart() + .startsWith(XSLTConstants.XSLT_START_NO_VERSION)); + assertTrue(XMLUnit.getXSLTStart().endsWith("\"2.0\">")); + try { + XMLUnit.setXSLTVersion("foo"); + fail("foo is not a number"); + } catch (ConfigurationException expected) { + } + try { + XMLUnit.setXSLTVersion("-1.0"); + fail("-1.0 is negative"); + } catch (ConfigurationException expected) { + } + } finally { + XMLUnit.setXSLTVersion("1.0"); + } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-04-18 01:36:08
|
Revision: 191 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=191&view=rev Author: bodewig Date: 2007-04-17 18:36:07 -0700 (Tue, 17 Apr 2007) Log Message: ----------- Implement new difference type for unmatched nodes Modified Paths: -------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceConstants.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceConstants.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceConstants.java 2007-04-17 04:04:57 UTC (rev 190) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceConstants.java 2007-04-18 01:36:07 UTC (rev 191) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 2001, Jeff Martin, Tim Bacon +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without @@ -84,6 +84,9 @@ int CHILD_NODELIST_SEQUENCE_ID = 20; /** Comparing 2 Documents only one of which has a doctype */ int HAS_DOCTYPE_DECLARATION_ID = 21; + /** Comparing 2 nodes and one holds more childnodes than can be + * matched against child nodes of the other. */ + int CHILD_NODE_NOT_FOUND_ID = 22; /** Comparing an implied attribute value against an explicit value */ public static final Difference ATTR_VALUE_EXPLICITLY_SPECIFIED = @@ -173,4 +176,9 @@ public static final Difference HAS_DOCTYPE_DECLARATION = new Difference(HAS_DOCTYPE_DECLARATION_ID, "presence of doctype declaration", true); + + /** Comparing 2 nodes and one holds more childnodes than can be + * matched against child nodes of the other. */ + public static final Difference CHILD_NODE_NOT_FOUND = + new Difference(CHILD_NODE_NOT_FOUND_ID, "presence of child node"); } \ No newline at end of file Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java 2007-04-17 04:04:57 UTC (rev 190) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java 2007-04-18 01:36:07 UTC (rev 191) @@ -39,6 +39,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import org.w3c.dom.Attr; @@ -360,6 +361,8 @@ HashMap/*<Node, Node>*/ matchingNodes = new HashMap(); HashMap/*<Node, Integer>*/ matchingNodeIndexes = new HashMap(); + List/*<Node>*/ unmatchedTestNodes = new ArrayList(testChildren); + // first pass to find the matching nodes in control and test docs for (int i=0; i < numNodes; ++i) { Node nextControl = (Node) controlChildren.get(i); @@ -371,12 +374,14 @@ boolean matchFound = false; while (!matchFound) { - if (findNodeType == ((Node)testChildren.get(j)).getNodeType()) { + Node t = (Node) testChildren.get(j); + if (findNodeType == t.getNodeType() + || comparingTextAndCDATA(findNodeType, t.getNodeType())) { matchFound = !matchOnElement || elementQualifier == null || elementQualifier .qualifyForComparison((Element) nextControl, - (Element) testChildren.get(j)); + (Element) t); } if (!matchFound) { ++j; @@ -392,47 +397,38 @@ if (matchFound) { matchingNodes.put(nextControl, testChildren.get(j)); matchingNodeIndexes.put(nextControl, new Integer(j)); + unmatchedTestNodes.remove(testChildren.get(j)); } } // next, do the actual comparision on those that matched - or // match them against the first test nodes that didn't match // any other control nodes - Collection matchingTestNodes = matchingNodes.values(); for (int i=0; i < numNodes; ++i) { Node nextControl = (Node) controlChildren.get(i); Node nextTest = (Node) matchingNodes.get(nextControl); Integer testIndex = (Integer) matchingNodeIndexes.get(nextControl); - if (nextTest == null) { - short findNodeType = nextControl.getNodeType(); - int startAt = ( i > lastTestNode ? lastTestNode : i); - j = startAt; - - boolean matchFound = false; - - while (!matchFound) { - if (((Node) testChildren.get(j)) - .getNodeType() == findNodeType - && !matchingTestNodes.contains(testChildren.get(j))) { - matchFound = true; - } else { - ++j; - if (j > lastTestNode) { - j = 0; - } - if (j == startAt) { - // been through all children - break; - } - } - } - nextTest = (Node) testChildren.get(j); - testIndex = new Integer(j); + if (nextTest == null && !unmatchedTestNodes.isEmpty()) { + nextTest = (Node) unmatchedTestNodes.get(0); + testIndex = new Integer(testChildren.indexOf(nextTest)); + unmatchedTestNodes.remove(0); } + if (nextTest != null) { compareNode(nextControl, nextTest, listener, elementQualifier); compare(new Integer(i), testIndex, nextControl, nextTest, listener, CHILD_NODELIST_SEQUENCE); + } else { + compare(nextControl.getNodeName(), null, nextControl, null, + listener, CHILD_NODE_NOT_FOUND); + } } + + // now handle remaining unmatched test nodes + for (Iterator iter = unmatchedTestNodes.iterator(); iter.hasNext();) { + Node n = (Node) iter.next(); + compare(null, n.getNodeName(), null, n, listener, + CHILD_NODE_NOT_FOUND); + } } /** Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java 2007-04-17 04:04:57 UTC (rev 190) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java 2007-04-18 01:36:07 UTC (rev 191) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 200, Jeff Martin, Tim Bacon +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without @@ -110,15 +110,33 @@ DetailedDiff differencesWithWhitespace = new DetailedDiff( new Diff(new InputSource(new FileReader(control)), new InputSource(new FileReader(test))) ); - assertEquals(1402, differencesWithWhitespace.getAllDifferences().size()); + List l = differencesWithWhitespace.getAllDifferences(); + int unmatchedNodes = 0; + for (Iterator iter = l.iterator(); iter.hasNext();) { + Difference d = (Difference) iter.next(); + if (d.getId() == DifferenceConstants.CHILD_NODE_NOT_FOUND_ID) { + unmatchedNodes++; + } + } + + assertEquals(1402 + unmatchedNodes, + differencesWithWhitespace.getAllDifferences().size()); + try { XMLUnit.setIgnoreWhitespace(true); Diff prototype = new Diff(new FileReader(control), new FileReader(test)); DetailedDiff detailedDiff = new DetailedDiff(prototype); List differences = detailedDiff.getAllDifferences(); - assertEquals(40, differences.size()); + unmatchedNodes = 0; + for (Iterator iter = differences.iterator(); iter.hasNext();) { + Difference d = (Difference) iter.next(); + if (d.getId() == DifferenceConstants.CHILD_NODE_NOT_FOUND_ID) { + unmatchedNodes++; + } + } + assertEquals(40 + unmatchedNodes, differences.size()); SimpleXpathEngine xpathEngine = new SimpleXpathEngine(); Document controlDoc = @@ -217,8 +235,9 @@ DetailedDiff diff = new DetailedDiff(new Diff(control, test)); List changes = diff.getAllDifferences(); - // number of children, text of first child - assertEquals(2, changes.size()); + // number of children, text of first child, unexpected second + // test child + assertEquals(3, changes.size()); } protected Diff buildDiff(Document control, Document test) { Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java 2007-04-17 04:04:57 UTC (rev 190) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java 2007-04-18 01:36:07 UTC (rev 191) @@ -620,7 +620,7 @@ String control = "<stuff><item id=\"1\"/><item id=\"2\"/></stuff>"; String test = "<stuff><?item data?></stuff>"; listenToDifferences(control, test); - assertEquals("13th control xpath", "/stuff[1]/item[2]", + assertEquals("13th control xpath", "/stuff[1]/item[1]", listener.controlXpath); assertEquals("13th test xpath", "/stuff[1]/processing-instruction()[1]", listener.testXpath); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-04-18 15:27:49
|
Revision: 193 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=193&view=rev Author: bodewig Date: 2007-04-18 08:27:50 -0700 (Wed, 18 Apr 2007) Log Message: ----------- Preparing build system and site for release Modified Paths: -------------- trunk/xmlunit/build.xml trunk/xmlunit/src/site/index.html Added Paths: ----------- trunk/xmlunit/docbook.xml Modified: trunk/xmlunit/build.xml =================================================================== --- trunk/xmlunit/build.xml 2007-04-18 15:27:27 UTC (rev 192) +++ trunk/xmlunit/build.xml 2007-04-18 15:27:50 UTC (rev 193) @@ -1,16 +1,37 @@ -<project name="xmlunit" default="compile" basedir="."> - <!-- The properties junit.lib, xmlxsl.lib, and test.report.dir should be defined in your build.properties file --> - <target name="props"> - <property name="xmlunit.version" value="1.1alpha"/> - <property name="src.dir" value="src"/> - <property name="test.dir" value="tests"/> - <property name="lib.dir" value="lib"/> - <property name="out.dir" value="classes"/> - <property name="dist.dir" value="dist"/> - <property name="docs.dir" value="doc"/> - <property name="build.user.guide" value="userguide"/> - <property file="build.properties"/> +<project name="xmlunit" default="test" basedir="."> + <!-- allow properties to be overridden in a properties file --> + <property file="build.properties"/> + + <!-- Version --> + <property name="xmlunit.version" value="1.1alpha"/> + + <!-- some locations --> + <property name="src.dir" value="src"/> + <property name="test.dir" value="tests"/> + <property name="build.dir" location="build"/> + <property name="lib.dir" value="${build.dir}/lib"/> + <property name="out.dir" value="${build.dir}/classes"/> + <property name="test.out.dir" value="${build.dir}/test-classes"/> + <property name="userguide.out.dir" value="${build.dir}/ug-classes"/> + <property name="test.report.dir" value="${build.dir}/test-report"/> + <property name="dist.dir" value="${build.dir}/dist"/> + <property name="docs.dir" value="${build.dir}/doc"/> + <property name="userguide.docs.dir" value="${docs.dir}/userguide"/> + + <!-- javac properties --> + <property name="javac.source" value="1.3"/> + <property name="javac.target" value="1.3"/> + <property name="javac.debug" value="true"/> + + <!-- some library paths --> + <!-- where is JAXP? property name="${xmlxsl.lib}" location="."/ --> + <!-- where is JUnit? property name="${junit.lib}" location="."/ --> + + <!-- Docbook related properties, macros and targets --> + <import file="docbook.xml"/> + + <target name="-props"> <available property="jaxp13+" classname="javax.xml.xpath.XPath"/> <condition property="jaxp13+.impl"> <and> @@ -21,31 +42,34 @@ <available property="regexp.present" classname="java.util.regex.Matcher"/> </target> - <target name="check-props" unless="test.report.dir"> - <fail>Please provide the -values for junit.lib, xmlxsl.lib, and test.report.dir -in build.properties</fail> - </target> - - <target name="init" depends="props,check-props"> + <target name="-init" depends="-props"> <mkdir dir="${lib.dir}"/> <mkdir dir="${out.dir}"/> + <mkdir dir="${test.out.dir}"/> <mkdir dir="${test.report.dir}"/> <mkdir dir="${dist.dir}"/> + <mkdir dir="${docs.dir}"/> + <mkdir dir="${userguide.docs.dir}"/> </target> - <target name="clean" depends="init"> + <target name="clean" + description="removes created directories"> <delete includeEmptyDirs="true" quiet="true"> - <fileset dir="${out.dir}" includes="**/*.class"/> - <fileset dir="${test.report.dir}" includes="**/TEST*.*"/> + <fileset dir="${lib.dir}"/> + <fileset dir="${out.dir}"/> + <fileset dir="${test.out.dir}"/> + <fileset dir="${test.report.dir}"/> <fileset dir="${dist.dir}"/> - <fileset dir="${build.user.guide}"/> + <fileset dir="${docs.dir}"/> + <fileset dir="${userguide.docs.dir}"/> + <fileset dir="${build.dir}"/> </delete> </target> - <target name="compile" depends="init"> - <mkdir dir="${out.dir}"/> - <javac srcdir="${src.dir}/java:${test.dir}/java" destdir="${out.dir}" debug="on" target="1.2" source="1.3"> + <target name="compile" depends="-init" + description="compiles sources and tests"> + <javac srcdir="${src.dir}/java" destdir="${out.dir}" + debug="${javac.debug}" target="${javac.target}" source="${javac.source}"> <classpath> <pathelement location="${xmlxsl.lib}"/> <pathelement location="${junit.lib}"/> @@ -54,11 +78,23 @@ <exclude name="**/jaxp13/**" unless="jaxp13+"/> <exclude name="**/*XPathRegexAssert.java" unless="regexp.present"/> </javac> + <javac srcdir="${test.dir}/java" destdir="${test.out.dir}" + debug="${javac.debug}" target="${javac.target}" source="${javac.source}"> + <classpath> + <pathelement location="${out.dir}"/> + <pathelement location="${xmlxsl.lib}"/> + <pathelement location="${junit.lib}"/> + <pathelement path="${java.class.path}"/> + </classpath> + <exclude name="**/jaxp13/**" unless="jaxp13+"/> + <exclude name="**/*XPathRegexAssert.java" unless="regexp.present"/> + </javac> </target> - <target name="test" depends="compile"> - <mkdir dir="${test.report.dir}"/> - <junit printsummary="yes" haltonfailure="no" fork="yes" forkMode="perBatch"> + <target name="test" depends="compile" + description="runs the tests"> + <junit printsummary="yes" haltonfailure="no" fork="yes" + forkMode="perBatch" failureproperty="tests.failed"> <sysproperty key="basedir" value="${basedir}"/> <sysproperty key="user.dir" value="${basedir}"/> <!-- @@ -71,6 +107,7 @@ --> <classpath> <pathelement location="${out.dir}"/> + <pathelement location="${test.out.dir}"/> <pathelement location="${xmlxsl.lib}"/> <pathelement location="${junit.lib}"/> <pathelement path="${java.class.path}"/> @@ -90,25 +127,23 @@ </fileset> <report format="frames" todir="${test.report.dir}/html"/> </junitreport> - </target> - <target name="setDistVersion" depends="init"> - <replace dir="${src.dir}" token="@@version@@" value="${xmlunit.version}" - includes="**/*.java"/> - <tstamp> - <format property="ivy.publication.datetime" pattern="yyyyMMddHHmmss"/> - </tstamp> + <fail if="tests.failed">Some tests failed</fail> </target> - <target name="docs" depends="init"> - <mkdir dir="${docs.dir}"/> - <delete includeEmptyDirs="true" dir="${docs.dir}/org"/> - <javadoc destdir="${docs.dir}" + <target name="docs" + depends="create-users-guide,javadocs,-site" + description="creates the documentation bundle"/> + + <target name="javadocs" depends="-init" + description="creates the API documentation"> + <delete includeEmptyDirs="true" dir="${docs.dir}/api"/> + <javadoc destdir="${docs.dir}/api" overview="${src.dir}/java/overview.html" windowtitle="XMLUnit Documentation" footer="<p><a href="http://xmlunit.sourceforge.net/">XMLUnit</a> is hosted by sourceforge.net</p>"> <group title="XMLUnit v${xmlunit.version}" - packages="org.custommonkey.xmlunit.*"/> + packages="org.custommonkey.xmlunit*"/> <fileset dir="${src.dir}/java"> <include name="org/custommonkey/**/*.java"/> </fileset> @@ -121,14 +156,23 @@ </javadoc> </target> - <target name="jar" depends="clean,setDistVersion,compile"> + <target name="-site" depends="-init"> + <copy todir="${docs.dir}"> + <fileset dir="${src.dir}/site"> + <include name="*.html"/> + <include name="*.png"/> + </fileset> + </copy> + </target> + + <target name="jar" depends="clean,compile" + description="creates jar, Maven2 POM and Ivy file"> <jar jarfile="${lib.dir}/xmlunit-${xmlunit.version}.jar" basedir="${out.dir}" - excludes="**/test_*.class" /> <copy todir="${lib.dir}"> - <fileset dir="src/etc"> + <fileset dir="${src.dir}/etc"> <include name="xmlunit.pom"/> <include name="xmlunit-ivy.xml"/> </fileset> @@ -146,50 +190,59 @@ </copy> </target> - <target name="dist" depends="jar,test,docs"> - <mkdir dir="${dist.dir}"/> - <zip zipfile="${dist.dir}/xmlunit${xmlunit.version}.zip"> - <zipfileset prefix="xmlunit" dir="${basedir}" - includes="**/xmlunit${xmlunit.version}.jar"/> - <zipfileset prefix="xmlunit" dir="${basedir}" - includes="**/*.java,**/*.txt,**/*.xml,**/*.xsl,**/*.dtd,**/*.xsd" - excludes="${out.dir}/*,**/TEST*.xml,bugs/*"/> - <zipfileset prefix="xmlunit" dir="${basedir}" - includes="${docs.dir}/**/*.css,${docs.dir}/**/*.html,${test.dir}/etc/*.html"/> - <zipfileset prefix="xmlunit" dir="${src.dir}/site" - includes="*.pdf,example.html"/> + <target name="bindist" depends="jar,test,docs"> + <zip zipfile="${dist.dir}/xmlunit-${xmlunit.version}-bin.zip"> + <zipfileset prefix="xmlunit-${xmlunit.version}/lib" + dir="${lib.dir}" includes="*.jar"/> + <zipfileset prefix="xmlunit-${xmlunit.version}/docs" + dir="${docs.dir}"/> + <zipfileset prefix="xmlunit-${xmlunit.version}" dir="."> + <include name="KEYS"/> + <include name="LICENSE.txt"/> + <include name="README.txt"/> + </zipfileset> </zip> </target> - <target name="src" depends="clean"> - <property name="dist.name" - value="${ant.project.name}-${xmlunit.version}"/> - <copy todir="${dist.dir}/${dist.name}"> - <fileset dir="${basedir}"> - <include name="${src.dir}/**"/> - <include name="${test.dir}/**"/> - <include name="ISSUES"/> + <target name="srcdist" depends="-init,create-users-guide"> + <zip zipfile="${dist.dir}/xmlunit-${xmlunit.version}-src.zip"> + <zipfileset prefix="xmlunit-${xmlunit.version}" dir="."> + <include name="*.xml"/> + <include name="${src.dir}/"/> + <include name="${test.dir}/"/> + <include name="KEYS"/> <include name="LICENSE.txt"/> <include name="README.txt"/> - <include name="build.xml"/> - <include name="build.properties"/> + </zipfileset> + <zipfileset dir="${userguide.docs.dir}" + prefix="xmlunit-${xmlunit.version}/userguide"/> + </zip> + </target> + + <target name="dist" + depends="clean,bindist,srcdist,compile-userguide-examples" + description="creates the distribution files"> + <checksum algorithm="md5"> + <fileset dir="${dist.dir}"> + <include name="*.zip"/> </fileset> - </copy> - <tar tarfile="${dist.name}-src.tar" basedir="${dist.dir}"> - </tar> - <gzip zipfile="${dist.name}-src.tgz" - src="${dist.name}-src.tar" /> - <delete file="${dist.name}-src.tar" /> + </checksum> + <checksum algorithm="sha1"> + <fileset dir="${dist.dir}"> + <include name="*.zip"/> + </fileset> + </checksum> </target> <target name="compile-userguide-examples" depends="compile"> - <mkdir dir="${build.user.guide}"/> + <mkdir dir="${userguide.out.dir}"/> <javac srcdir="src/user-guide" includes="org/" - destdir="${build.user.guide}" source="1.3" target="1.2"> + destdir="${userguide.out.dir}" source="1.3" target="1.2"> <classpath> <pathelement location="${junit.lib}"/> <pathelement location="${out.dir}"/> </classpath> </javac> + <delete dir="${userguide.out.dir}"/> </target> </project> Added: trunk/xmlunit/docbook.xml =================================================================== --- trunk/xmlunit/docbook.xml (rev 0) +++ trunk/xmlunit/docbook.xml 2007-04-18 15:27:50 UTC (rev 193) @@ -0,0 +1,84 @@ +<project> + <!-- allow overrides --> + <property file="docbook.properties"/> + + <!-- location of Docbook Stylesheets and dblatex --> + <property name="db5.xsl" location="../../docbook/docbook5-xsl-1.72.0"/> + <property name="dblatex" value="/usr/bin/dblatex"/> + + <property name="html.dir" location="${userguide.docs.dir}/html"/> + <property name="user.guide" value="XMLUnit-Java"/> + <property name="src.userguide.dir" value="${src.dir}/user-guide"/> + + <target name="create-users-guide" + depends="users-guide-html,users-guide-pdf" + description="creates PDF and HTML version of User's Guide"/> + + <target name="-html-needs-refresh?"> + <uptodate property="HTML is up-to-date" + srcfile="${src.userguide.dir}/${user.guide}.xml" + targetfile="${html.dir}/index.html"/> + </target> + + <target name="users-guide-html" depends="-html-needs-refresh?" + unless="HTML is up-to-date" + description="Creates HTML version of the User's Guide"> + <delete dir="${html.dir}" quiet="true"/> + <mkdir dir="${html.dir}"/> + <xslt + basedir="${src.userguide.dir}" + destdir="${html.dir}" + style="${db5.xsl}/html/chunk.xsl"> + <include name="${user.guide}.xml"/> + + <param name="section.autolabel" expression="1"/> + <param name="section.label.includes.component.label" expression="1"/> + </xslt> + <copy file="${src.dir}/site/xmlunit.png" toDir="${html.dir}"/> + <delete file="${html.dir}/${user.guide}.html" quiet="true"/> + </target> + + <target name="-check-os"> + <condition property="isWindows"> + <os family="windows"/> + </condition> + </target> + + <target name="-define-dblatex-unix" unless="isWindows" + depends="-check-os"> + <macrodef name="dblatex"> + <attribute name="sourcefile"/> + <sequential> + <apply executable="${dblatex}"> + <fileset file="@{sourcefile}"/> + <globmapper from="*.xml" to="*.pdf"/> + </apply> + </sequential> + </macrodef> + </target> + + <target name="-define-dblatex-cygwin" if="isWindows" + depends="-check-os"> + <macrodef name="dblatex"> + <attribute name="sourcefile"/> + <sequential> + <apply executable="bash.exe" addsourcefile="false"> + <fileset file="@{sourcefile}"/> + <globmapper from="*.xml" to="*.pdf"/> + <arg value="-c"/> + <arg value="${dblatex} @{sourcefile}"/> + </apply> + </sequential> + </macrodef> + </target> + + <target name="-define-dblatex" + depends="-define-dblatex-unix,-define-dblatex-cygwin"/> + + <target name="users-guide-pdf" depends="-define-dblatex" + description="Creates the PDF version of the User's Guide"> + <dblatex sourcefile="${src.userguide.dir}/${user.guide}.xml"/> + <move file="${src.userguide.dir}/${user.guide}.pdf" + todir="${userguide.docs.dir}"/> + </target> +</project> \ No newline at end of file Property changes on: trunk/xmlunit/docbook.xml ___________________________________________________________________ Name: svn:executable + * Name: svn:eol-style + native Modified: trunk/xmlunit/src/site/index.html =================================================================== --- trunk/xmlunit/src/site/index.html 2007-04-18 15:27:27 UTC (rev 192) +++ trunk/xmlunit/src/site/index.html 2007-04-18 15:27:50 UTC (rev 193) @@ -62,10 +62,10 @@ </tr> <tr> <td colspan="2"> - <p>The current release is <a + <p>The current stable release is <a href="http://sourceforge.net/project/showfiles.php?group_id=23187&release_id=155097">XMLUnit 1.0</a>, April 2003 (release notes are <a - href="http://xmlunit.svn.sourceforge.net/viewvc/*checkout*/xmlunit/tags/v1_0/xmlunit/README.txt">here</a>)</p> + href="http://xmlunit.svn.sourceforge.net/viewvc/*checkout*/xmlunit/tags/v1_0/xmlunit/README.txt">here</a>), the latest release is XMLUnit 1.1 beta 1 released in April 2007. It can be downloaded from <a href="http://sourceforge.net/project/showfiles.php?group_id=23187">here</a>.</p> <p>XMLUnit for Java provides two JUnit extension classes, <code>XMLAssert</code> and <code>XMLTestCase</code>, and a set of supporting classes (e.g. <code>Diff</code>, <code>DetailedDiff</code>,<code>Transform</code>,<code>SimpleXpathEngine</code>,<code>Validator</code>,<code>NodeTest</code>) @@ -84,9 +84,11 @@ <table border="0" cellspacing="5" cellpadding="5"> <tbody> <tr> - <td><a href="XMLUnit.pdf">Read the overview document (PDF)</a></td> + <td>Read the User's Guide (<a + href="userguide/XMLUnit-Java.pdf">PDF</a> or <a + href="userguide/html/index.html">HTML</a>)</td> <td><a href="example.html">See some example code</a></td> - <td><a href="doc">Browse the Javadocs</a></td> + <td><a href="api/index.html">Browse the Javadocs</a></td> <td><a href="http://xmlunit.svn.sourceforge.net/viewvc/xmlunit/trunk/xmlunit/">Visit the Subversion repository</a> </td> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-04-19 04:00:54
|
Revision: 196 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=196&view=rev Author: bodewig Date: 2007-04-18 21:00:56 -0700 (Wed, 18 Apr 2007) Log Message: ----------- bump version Modified Paths: -------------- trunk/xmlunit/build.xml trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java Modified: trunk/xmlunit/build.xml =================================================================== --- trunk/xmlunit/build.xml 2007-04-19 03:59:31 UTC (rev 195) +++ trunk/xmlunit/build.xml 2007-04-19 04:00:56 UTC (rev 196) @@ -4,7 +4,7 @@ <property file="build.properties"/> <!-- Version --> - <property name="xmlunit.version" value="1.1alpha"/> + <property name="xmlunit.version" value="1.1beta2"/> <!-- some locations --> <property name="src.dir" value="src"/> Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java 2007-04-19 03:59:31 UTC (rev 195) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java 2007-04-19 04:00:56 UTC (rev 196) @@ -469,7 +469,7 @@ * @return current version */ public static String getVersion() { - return "1.1alpha"; + return "1.1beta2"; } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-04-23 16:09:50
|
Revision: 200 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=200&view=rev Author: bodewig Date: 2007-04-23 08:47:38 -0700 (Mon, 23 Apr 2007) Log Message: ----------- modernize NUnit usage: Assertion -> Assert Modified Paths: -------------- trunk/xmlunit/src/csharp/XmlAssertion.cs trunk/xmlunit/tests/csharp/DiffConfigurationTests.cs trunk/xmlunit/tests/csharp/DiffResultTests.cs trunk/xmlunit/tests/csharp/DifferenceTests.cs trunk/xmlunit/tests/csharp/ValidatorTests.cs trunk/xmlunit/tests/csharp/XPathTests.cs trunk/xmlunit/tests/csharp/XmlAssertionTests.cs trunk/xmlunit/tests/csharp/XmlDiffTests.cs trunk/xmlunit/tests/csharp/XmlInputTests.cs trunk/xmlunit/tests/csharp/XsltTests.cs Modified: trunk/xmlunit/src/csharp/XmlAssertion.cs =================================================================== --- trunk/xmlunit/src/csharp/XmlAssertion.cs 2007-04-23 15:18:56 UTC (rev 199) +++ trunk/xmlunit/src/csharp/XmlAssertion.cs 2007-04-23 15:47:38 UTC (rev 200) @@ -2,7 +2,7 @@ using NUnit.Framework; using System.IO; - public class XmlAssertion : Assertion { + public class XmlAssertion : Assert { public static void AssertXmlEquals(TextReader controlTextReader, TextReader testTextReader) { AssertXmlEquals(new XmlDiff(controlTextReader, testTextReader)); } @@ -37,7 +37,11 @@ private static void AssertXmlEquals(XmlDiff xmlDiff, bool equalOrNot) { DiffResult diffResult = xmlDiff.Compare(); - Assertion.AssertEquals(diffResult.StringValue, equalOrNot, diffResult.Equal); + if (equalOrNot) { + IsTrue(diffResult.Equal, diffResult.StringValue); + } else { + IsFalse(diffResult.Equal, diffResult.StringValue); + } } public static void AssertXmlIdentical(XmlDiff xmlDiff) { @@ -50,7 +54,11 @@ private static void AssertXmlIdentical(XmlDiff xmlDiff, bool identicalOrNot) { DiffResult diffResult = xmlDiff.Compare(); - AssertEquals(xmlDiff.OptionalDescription, identicalOrNot, diffResult.Identical); + if (identicalOrNot) { + IsTrue(diffResult.Identical, xmlDiff.OptionalDescription); + } else { + IsFalse(diffResult.Identical, xmlDiff.OptionalDescription); + } } public static void AssertXmlValid(string someXml) { @@ -75,7 +83,7 @@ } public static void AssertXmlValid(Validator validator) { - AssertEquals(validator.ValidationMessage, true, validator.IsValid); + IsTrue(validator.IsValid, validator.ValidationMessage); } public static void AssertXPathExists(string anXPathExpression, string inXml) { @@ -88,7 +96,7 @@ public static void AssertXPathExists(string anXPathExpression, XmlInput inXml) { XPath xpath = new XPath(anXPathExpression); - AssertEquals(true, xpath.XPathExists(inXml)); + AreEqual(true, xpath.XPathExists(inXml)); } public static void AssertXPathEvaluatesTo(string anXPathExpression, string inXml, @@ -104,7 +112,7 @@ public static void AssertXPathEvaluatesTo(string anXPathExpression, XmlInput inXml, string expectedValue) { XPath xpath = new XPath(anXPathExpression); - AssertEquals(expectedValue, xpath.EvaluateXPath(inXml)); + AreEqual(expectedValue, xpath.EvaluateXPath(inXml)); } public static void AssertXslTransformResults(string xslTransform, string xmlToTransform, string expectedResult) { Modified: trunk/xmlunit/tests/csharp/DiffConfigurationTests.cs =================================================================== --- trunk/xmlunit/tests/csharp/DiffConfigurationTests.cs 2007-04-23 15:18:56 UTC (rev 199) +++ trunk/xmlunit/tests/csharp/DiffConfigurationTests.cs 2007-04-23 15:47:38 UTC (rev 200) @@ -14,16 +14,16 @@ [Test] public void DefaultConfiguredWithGenericDescription() { DiffConfiguration diffConfiguration = new DiffConfiguration(); - Assertion.AssertEquals(DiffConfiguration.DEFAULT_DESCRIPTION, + Assert.AreEqual(DiffConfiguration.DEFAULT_DESCRIPTION, diffConfiguration.Description); - Assertion.AssertEquals(DiffConfiguration.DEFAULT_DESCRIPTION, + Assert.AreEqual(DiffConfiguration.DEFAULT_DESCRIPTION, new XmlDiff("", "").OptionalDescription); } [Test] public void DefaultConfiguredToUseValidatingParser() { DiffConfiguration diffConfiguration = new DiffConfiguration(); - Assertion.AssertEquals(DiffConfiguration.DEFAULT_USE_VALIDATING_PARSER, + Assert.AreEqual(DiffConfiguration.DEFAULT_USE_VALIDATING_PARSER, diffConfiguration.UseValidatingParser); FileStream controlFileStream = File.Open(ValidatorTests.VALID_FILE, @@ -34,7 +34,7 @@ XmlDiff diff = new XmlDiff(new StreamReader(controlFileStream), new StreamReader(testFileStream)); diff.Compare(); - Assertion.Fail("Expected validation failure"); + Assert.Fail("Expected validation failure"); } catch (XmlSchemaException e) { string message = e.Message; // to prevent 'unused variable' compiler warning } finally { @@ -45,7 +45,7 @@ [Test] public void CanConfigureNotToUseValidatingParser() { DiffConfiguration diffConfiguration = new DiffConfiguration(false); - Assertion.AssertEquals(false, diffConfiguration.UseValidatingParser); + Assert.AreEqual(false, diffConfiguration.UseValidatingParser); FileStream controlFileStream = File.Open(ValidatorTests.VALID_FILE, FileMode.Open, FileAccess.Read); @@ -57,7 +57,7 @@ diffConfiguration); diff.Compare(); } catch (XmlSchemaException e) { - Assertion.Fail("Unexpected validation failure: " + e.Message); + Assert.Fail("Unexpected validation failure: " + e.Message); } finally { controlFileStream.Close(); testFileStream.Close(); @@ -66,7 +66,7 @@ [Test] public void DefaultConfiguredWithWhitespaceHandlingAll() { DiffConfiguration diffConfiguration = new DiffConfiguration(); - Assertion.AssertEquals(WhitespaceHandling.All, diffConfiguration.WhitespaceHandling); + Assert.AreEqual(WhitespaceHandling.All, diffConfiguration.WhitespaceHandling); PerformAssertion(xmlWithoutWhitespace, xmlWithWhitespaceElement, false); PerformAssertion(xmlWithoutWhitespace, xmlWithoutWhitespaceElement, false); @@ -85,8 +85,8 @@ PerformAssertion(diff, assertion); } private void PerformAssertion(XmlDiff diff, bool assertion) { - Assertion.AssertEquals(assertion, diff.Compare().Equal); - Assertion.AssertEquals(assertion, diff.Compare().Identical); + Assert.AreEqual(assertion, diff.Compare().Equal); + Assert.AreEqual(assertion, diff.Compare().Identical); } [Test] public void CanConfigureWhitespaceHandlingSignificant() { Modified: trunk/xmlunit/tests/csharp/DiffResultTests.cs =================================================================== --- trunk/xmlunit/tests/csharp/DiffResultTests.cs 2007-04-23 15:18:56 UTC (rev 199) +++ trunk/xmlunit/tests/csharp/DiffResultTests.cs 2007-04-23 15:47:38 UTC (rev 200) @@ -18,25 +18,25 @@ } [Test] public void NewDiffResultIsEqualAndIdentical() { - Assertion.AssertEquals(true, _result.Identical); - Assertion.AssertEquals(true, _result.Equal); - Assertion.AssertEquals("Identical", _result.StringValue); + Assert.AreEqual(true, _result.Identical); + Assert.AreEqual(true, _result.Equal); + Assert.AreEqual("Identical", _result.StringValue); } [Test] public void NotEqualOrIdenticalAfterMajorDifferenceFound() { _result.DifferenceFound(_diff, _majorDifference); - Assertion.AssertEquals(false, _result.Identical); - Assertion.AssertEquals(false, _result.Equal); - Assertion.AssertEquals(_diff.OptionalDescription + Assert.AreEqual(false, _result.Identical); + Assert.AreEqual(false, _result.Equal); + Assert.AreEqual(_diff.OptionalDescription + Environment.NewLine + _majorDifference.ToString(), _result.StringValue); } [Test] public void NotIdenticalButEqualAfterMinorDifferenceFound() { _result.DifferenceFound(_diff, _minorDifference); - Assertion.AssertEquals(false, _result.Identical); - Assertion.AssertEquals(true, _result.Equal); - Assertion.AssertEquals(_diff.OptionalDescription + Assert.AreEqual(false, _result.Identical); + Assert.AreEqual(true, _result.Equal); + Assert.AreEqual(_diff.OptionalDescription + Environment.NewLine + _minorDifference.ToString(), _result.StringValue); } Modified: trunk/xmlunit/tests/csharp/DifferenceTests.cs =================================================================== --- trunk/xmlunit/tests/csharp/DifferenceTests.cs 2007-04-23 15:18:56 UTC (rev 199) +++ trunk/xmlunit/tests/csharp/DifferenceTests.cs 2007-04-23 15:47:38 UTC (rev 200) @@ -9,16 +9,15 @@ [SetUp] public void CreateMinorDifference() { DifferenceType id = DifferenceType.ATTR_SEQUENCE_ID; - Assertion.AssertEquals(false, Differences.isMajorDifference(id)); + Assert.IsFalse(Differences.isMajorDifference(id)); minorDifference = new Difference(id); } [Test] public void ToStringContainsId() { string commentDifference = minorDifference.ToString(); string idValue = "type: " + (int)DifferenceType.ATTR_SEQUENCE_ID; - Assertion.AssertEquals("contains " + idValue, - true, - commentDifference.IndexOfAny(idValue.ToCharArray()) > 0); + Assert.IsTrue(commentDifference.IndexOfAny(idValue.ToCharArray()) > 0, + "contains " + idValue); } } } Modified: trunk/xmlunit/tests/csharp/ValidatorTests.cs =================================================================== --- trunk/xmlunit/tests/csharp/ValidatorTests.cs 2007-04-23 15:18:56 UTC (rev 199) +++ trunk/xmlunit/tests/csharp/ValidatorTests.cs 2007-04-23 15:47:38 UTC (rev 200) @@ -19,7 +19,7 @@ FileStream input = File.Open(file, FileMode.Open, FileAccess.Read); try { Validator validator = new Validator(new XmlInput(new StreamReader(input))); - Assertion.AssertEquals(expected, validator.IsValid); + Assert.AreEqual(expected, validator.IsValid); return validator; } finally { input.Close(); @@ -29,7 +29,7 @@ [Test] public void XsdInvalidFileIsNotValid() { Validator validator = PerformAssertion(INVALID_FILE, false); string expected = "The element 'http://www.publishing.org:Book' has incomplete content"; - Assertion.AssertEquals(true, + Assert.AreEqual(true, validator.ValidationMessage.StartsWith(expected)); } } Modified: trunk/xmlunit/tests/csharp/XPathTests.cs =================================================================== --- trunk/xmlunit/tests/csharp/XPathTests.cs 2007-04-23 15:18:56 UTC (rev 199) +++ trunk/xmlunit/tests/csharp/XPathTests.cs 2007-04-23 15:47:38 UTC (rev 200) @@ -13,39 +13,39 @@ private static readonly string COUNT_XPATH = "count(//b)"; [Test] public void XpathExistsTrueForXpathThatExists() { XPath xpath = new XPath(EXISTENT_XPATH); - Assertion.AssertEquals(true, + Assert.AreEqual(true, xpath.XPathExists(SIMPLE_XML)); } [Test] public void XpathExistsFalseForUnmatchedExpression() { XPath xpath = new XPath(NONEXISTENT_XPATH); - Assertion.AssertEquals(false, + Assert.AreEqual(false, xpath.XPathExists(SIMPLE_XML)); } [Test] public void XpathEvaluatesToTextValueForSimpleString() { string expectedValue = "one two"; XPath xpath = new XPath(EXISTENT_XPATH); - Assertion.AssertEquals(expectedValue, + Assert.AreEqual(expectedValue, xpath.EvaluateXPath(SIMPLE_XML)); } [Test] public void XpathEvaluatesToEmptyStringForUnmatchedExpression() { string expectedValue = ""; XPath xpath = new XPath(NONEXISTENT_XPATH); - Assertion.AssertEquals(expectedValue, + Assert.AreEqual(expectedValue, xpath.EvaluateXPath(SIMPLE_XML)); } [Test] public void XpathEvaluatesCountExpression() { string expectedValue = "2"; XPath xpath = new XPath(COUNT_XPATH); - Assertion.AssertEquals(expectedValue, + Assert.AreEqual(expectedValue, xpath.EvaluateXPath(MORE_COMPLEX_XML)); } [Test] public void XpathEvaluatesMultiNodeExpression() { string expectedValue = "onetwo"; XPath xpath = new XPath(MULTI_NODE_XPATH); - Assertion.AssertEquals(expectedValue, + Assert.AreEqual(expectedValue, xpath.EvaluateXPath(MORE_COMPLEX_XML)); } } Modified: trunk/xmlunit/tests/csharp/XmlAssertionTests.cs =================================================================== --- trunk/xmlunit/tests/csharp/XmlAssertionTests.cs 2007-04-23 15:18:56 UTC (rev 199) +++ trunk/xmlunit/tests/csharp/XmlAssertionTests.cs 2007-04-23 15:47:38 UTC (rev 200) @@ -27,7 +27,7 @@ new DiffConfiguration(description)); XmlAssertion.AssertXmlIdentical(diff); } catch (NUnit.Framework.AssertionException e) { - Assertion.AssertEquals(true, e.Message.StartsWith(description)); + Assert.IsTrue(e.Message.StartsWith(description)); } } @@ -38,7 +38,7 @@ new DiffConfiguration(description)); XmlAssertion.AssertXmlEquals(diff); } catch (NUnit.Framework.AssertionException e) { - Assertion.AssertEquals(true, e.Message.StartsWith(description)); + Assert.AreEqual(true, e.Message.StartsWith(description)); } } @@ -55,7 +55,7 @@ StreamReader reader = GetStreamReader(ValidatorTests.INVALID_FILE); try { XmlAssertion.AssertXmlValid(reader); - Assertion.Fail("Expected assertion failure"); + Assert.Fail("Expected assertion failure"); } catch(AssertionException e) { AvoidUnusedVariableCompilerWarning(e); } finally { @@ -79,7 +79,7 @@ try { XmlAssertion.AssertXPathExists("//star[@name='alpha centauri']", MY_SOLAR_SYSTEM); - Assertion.Fail("Expected assertion failure"); + Assert.Fail("Expected assertion failure"); } catch (AssertionException e) { AvoidUnusedVariableCompilerWarning(e); } @@ -131,7 +131,7 @@ try { XmlAssertion.AssertXslTransformResults(xslt, xmlToTransform, expectedXml); exceptionExpected = false; - Assertion.Fail("Expected dog not cat!"); + Assert.Fail("Expected dog not cat!"); } catch (AssertionException e) { AvoidUnusedVariableCompilerWarning(e); if (!exceptionExpected) { Modified: trunk/xmlunit/tests/csharp/XmlDiffTests.cs =================================================================== --- trunk/xmlunit/tests/csharp/XmlDiffTests.cs 2007-04-23 15:18:56 UTC (rev 199) +++ trunk/xmlunit/tests/csharp/XmlDiffTests.cs 2007-04-23 15:47:38 UTC (rev 200) @@ -10,14 +10,14 @@ [Test] public void EqualResultForSameReader() { TextReader reader = new StringReader("<empty/>"); DiffResult result = PerformDiff(reader, reader); - Assertion.AssertEquals(true, result.Equal); + Assert.AreEqual(true, result.Equal); } [Test] public void SameResultForTwoInvocations() { TextReader reader = new StringReader("<empty/>"); DiffResult result1 = PerformDiff(reader, reader); DiffResult result2 = _xmlDiff.Compare(); - Assertion.AssertSame(result1, result2); + Assert.AreSame(result1, result2); } @@ -26,7 +26,7 @@ TextReader reader2 = new StringReader(input2); DiffResult result = PerformDiff(reader1, reader2); string msg = "comparing " + input1 + " to " + input2 + ": " + result.Difference; - Assertion.AssertEquals(msg, expected, result.Equal); + Assert.AreEqual(expected, result.Equal); } private void AssertExpectedResult(string[] inputs1, string[] inputs2, bool expected) { Modified: trunk/xmlunit/tests/csharp/XmlInputTests.cs =================================================================== --- trunk/xmlunit/tests/csharp/XmlInputTests.cs 2007-04-23 15:18:56 UTC (rev 199) +++ trunk/xmlunit/tests/csharp/XmlInputTests.cs 2007-04-23 15:47:38 UTC (rev 200) @@ -18,13 +18,13 @@ [Test] public void StringInputTranslatesToXmlReader() { XmlInput input = new XmlInput(INPUT); string actual = ReadOuterXml(input.CreateXmlReader()); - Assertion.AssertEquals(_expected, actual); + Assert.AreEqual(_expected, actual); } [Test] public void TextReaderInputTranslatesToXmlReader() { XmlInput input = new XmlInput(new StringReader(INPUT)); string actual = ReadOuterXml(input.CreateXmlReader()); - Assertion.AssertEquals(_expected, actual); + Assert.AreEqual(_expected, actual); } [Test] public void StreamInputTranslatesToXmlReader() { @@ -36,7 +36,7 @@ XmlInput input = new XmlInput(stream); string actual = ReadOuterXml(input.CreateXmlReader()); try { - Assertion.AssertEquals(_expected, actual); + Assert.AreEqual(_expected, actual); } finally { writer.Close(); } @@ -53,32 +53,32 @@ [Test] public void NotEqualsNull() { XmlInput input = new XmlInput(INPUT); - Assertion.AssertEquals(false, input.Equals(null)); + Assert.AreEqual(false, input.Equals(null)); } [Test] public void NotEqualsADifferentClass() { XmlInput input = new XmlInput(INPUT); - Assertion.AssertEquals(false, input.Equals(INPUT)); + Assert.AreEqual(false, input.Equals(INPUT)); } [Test] public void EqualsSelf() { XmlInput input = new XmlInput(INPUT); - Assertion.AssertEquals(input, input); + Assert.AreEqual(input, input); } [Test] public void EqualsCopyOfSelf() { XmlInput input = new XmlInput(INPUT); - Assertion.AssertEquals(new XmlInput(INPUT), input); + Assert.AreEqual(new XmlInput(INPUT), input); } [Test] public void HashCodeEqualsHashCodeOfInput() { XmlInput input = new XmlInput(INPUT); - Assertion.AssertEquals(INPUT.GetHashCode(), input.GetHashCode()); + Assert.AreEqual(INPUT.GetHashCode(), input.GetHashCode()); } [Test] public void HashCodeEqualsHashCodeOfCopy() { XmlInput input = new XmlInput(INPUT); - Assertion.AssertEquals(new XmlInput(INPUT).GetHashCode(), input.GetHashCode()); + Assert.AreEqual(new XmlInput(INPUT).GetHashCode(), input.GetHashCode()); } } Modified: trunk/xmlunit/tests/csharp/XsltTests.cs =================================================================== --- trunk/xmlunit/tests/csharp/XsltTests.cs 2007-04-23 15:18:56 UTC (rev 199) +++ trunk/xmlunit/tests/csharp/XsltTests.cs 2007-04-23 15:47:38 UTC (rev 200) @@ -27,8 +27,8 @@ Xslt xslt = new Xslt(IDENTITY_TRANSFORM); string input = "<qwerty>uiop</qwerty>"; string output = new string(input.ToCharArray()); - Assertion.AssertEquals(output, xslt.Transform(input).AsString()); - Assertion.AssertEquals(output, xslt.Transform(input).AsString()); + Assert.AreEqual(output, xslt.Transform(input).AsString()); + Assert.AreEqual(output, xslt.Transform(input).AsString()); } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-05-16 11:25:24
|
Revision: 209 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=209&view=rev Author: bodewig Date: 2007-05-16 04:25:23 -0700 (Wed, 16 May 2007) Log Message: ----------- Treat xsi:schemaLocation and xsi:noNamespaceSchemaLocation in a special way Modified Paths: -------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceConstants.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/JAXPConstants.java trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLConstants.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Diff.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceConstants.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceConstants.java 2007-05-12 19:54:41 UTC (rev 208) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceConstants.java 2007-05-16 11:25:23 UTC (rev 209) @@ -87,6 +87,16 @@ /** Comparing 2 nodes and one holds more childnodes than can be * matched against child nodes of the other. */ int CHILD_NODE_NOT_FOUND_ID = 22; + /** Comparing 2 nodes with different xsi:schemaLocation + * attributes, potentially only one of the two provides such an + * attribute at all. + */ + int SCHEMA_LOCATION_ID = 23; + /** Comparing 2 nodes with different xsi:noNamespaceSchemaLocation + * attributes, potentially only one of the two provides such an + * attribute at all. + */ + int NO_NAMESPACE_SCHEMA_LOCATION_ID = 24; /** Comparing an implied attribute value against an explicit value */ public static final Difference ATTR_VALUE_EXPLICITLY_SPECIFIED = @@ -181,4 +191,20 @@ * matched against child nodes of the other. */ public static final Difference CHILD_NODE_NOT_FOUND = new Difference(CHILD_NODE_NOT_FOUND_ID, "presence of child node"); + + /** Comparing 2 nodes with different xsi:schemaLocation + * attributes, potentially only one of the two provides such an + * attribute at all. + */ + public static final Difference SCHEMA_LOCATION = + new Difference(SCHEMA_LOCATION_ID, "xsi:schemaLocation attribute", + true); + /** Comparing 2 nodes with different xsi:noNamespaceSchemaLocation + * attributes, potentially only one of the two provides such an + * attribute at all. + */ + public static final Difference NO_NAMESPACE_SCHEMA_LOCATION = + new Difference(NO_NAMESPACE_SCHEMA_LOCATION_ID, + "xsi:noNamespaceSchemaLocation attribute", + true); } \ No newline at end of file Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java 2007-05-12 19:54:41 UTC (rev 208) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java 2007-05-16 11:25:23 UTC (rev 209) @@ -453,9 +453,10 @@ control, test, listener, ELEMENT_TAG_NAME); NamedNodeMap controlAttr = control.getAttributes(); - Integer controlNonXmlnsAttrLength = getNonXmlnsAttrLength(controlAttr); + Integer controlNonXmlnsAttrLength = + getNonSpecialAttrLength(controlAttr); NamedNodeMap testAttr = test.getAttributes(); - Integer testNonXmlnsAttrLength = getNonXmlnsAttrLength(testAttr); + Integer testNonXmlnsAttrLength = getNonSpecialAttrLength(testAttr); compare(controlNonXmlnsAttrLength, testNonXmlnsAttrLength, control, test, listener, ELEMENT_NUM_ATTRIBUTES); @@ -463,10 +464,16 @@ listener); } - private Integer getNonXmlnsAttrLength(NamedNodeMap attributes) { + /** + * The number of attributes not related to namespace declarations + * and/or Schema location. + */ + private Integer getNonSpecialAttrLength(NamedNodeMap attributes) { int length = 0, maxLength = attributes.getLength(); for (int i = 0; i < maxLength; ++i) { - if (!isXMLNSAttribute((Attr) attributes.item(i))) { + Attr a = (Attr) attributes.item(i); + if (!isXMLNSAttribute(a) + && !isRecognizedXMLSchemaInstanceAttribute(a)) { ++length; } } @@ -493,8 +500,13 @@ } else { compareTo = (Attr) testAttr.getNamedItem(attrName); } - - if (compareTo != null) { + + if (isRecognizedXMLSchemaInstanceAttribute(nextAttr)) { + compareRecognizedXMLSchemaInstanceAttribute(nextAttr, + compareTo, + listener); + + } else if (compareTo != null) { compareAttribute(nextAttr, compareTo, listener); if (!XMLUnit.getIgnoreAttributeOrder()) { @@ -539,12 +551,54 @@ } /** + * @param attr + * @return true if the attribute is an XML Schema Instance + * namespace attribute XMLUnit treats in a special way. + */ + private boolean isRecognizedXMLSchemaInstanceAttribute(Attr attr) { + return XMLConstants + .W3C_XML_SCHEMA_INSTANCE_NS_URI.equals(attr.getNamespaceURI()) + && (XMLConstants + .W3C_XML_SCHEMA_INSTANCE_SCHEMA_LOCATION_ATTR + .equals(attr.getLocalName()) + || XMLConstants + .W3C_XML_SCHEMA_INSTANCE_NO_NAMESPACE_SCHEMA_LOCATION_ATTR + .equals(attr.getLocalName())); + } + + /** * Compare two attributes * @param control * @param test * @param listener * @throws DifferenceFoundException */ + protected void compareRecognizedXMLSchemaInstanceAttribute(Attr control, + Attr test, + DifferenceListener listener) + throws DifferenceFoundException { + Difference d = + XMLConstants.W3C_XML_SCHEMA_INSTANCE_SCHEMA_LOCATION_ATTR + .equals(control.getLocalName()) + ? SCHEMA_LOCATION : NO_NAMESPACE_SCHEMA_LOCATION; + + controlTracker.visited(control); + if (test != null) { + testTracker.visited(test); + } + + compare(control.getValue(), + test != null ? test.getValue() : "[not specified]", + control, test, listener, d); + } + + /** + * Compare two attributes + * @param control + * @param test + * @param listener + * @throws DifferenceFoundException + */ protected void compareAttribute(Attr control, Attr test, DifferenceListener listener) throws DifferenceFoundException { controlTracker.visited(control); Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/JAXPConstants.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/JAXPConstants.java 2007-05-12 19:54:41 UTC (rev 208) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/JAXPConstants.java 2007-05-16 11:25:23 UTC (rev 209) @@ -1,6 +1,6 @@ /* ****************************************************************** - Copyright (c) 200, Jeff Martin, Tim Bacon + Copyright (c) 2001-2007, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLConstants.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLConstants.java 2007-05-12 19:54:41 UTC (rev 208) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLConstants.java 2007-05-16 11:25:23 UTC (rev 209) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 2001, Jeff Martin, Tim Bacon +Copyright (c) 2001-2007 Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without @@ -139,4 +139,22 @@ */ public static final String W3C_XML_SCHEMA_NS_URI = "http://www.w3.org/2001/XMLSchema"; + + /** + * http://www.w3.org/2001/XMLSchema-instance + */ + public static final String W3C_XML_SCHEMA_INSTANCE_NS_URI + = "http://www.w3.org/2001/XMLSchema-instance"; + + /** + * "schemaLocation" + */ + public static final String W3C_XML_SCHEMA_INSTANCE_SCHEMA_LOCATION_ATTR + = "schemaLocation"; + + /** + * "noNamespaceSchemaLocation" + */ + String W3C_XML_SCHEMA_INSTANCE_NO_NAMESPACE_SCHEMA_LOCATION_ATTR + = "noNamespaceSchemaLocation"; } Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Diff.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Diff.java 2007-05-12 19:54:41 UTC (rev 208) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Diff.java 2007-05-16 11:25:23 UTC (rev 209) @@ -683,4 +683,27 @@ } } + /** + * inspired by {@link + * http://day-to-day-stuff.blogspot.com/2007/05/comparing-xml-in-junit-test.html + * Erik von Oosten's Weblog }, made us implement special handling + * of schemaLocation. + */ + public void testNamespacePrefixDiff() throws Exception { + String xml1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + + "<Message xmlns=\"http://www.a.nl/a10.xsd\"" + + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + + " xsi:schemaLocation=\"C:/longpath/a10.xsd\"" + + ">" + + "<MessageHeader/>" + + "</Message>"; + String xml2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + + "<a:Message xmlns:a=\"http://www.a.nl/a10.xsd\">" + + "<a:MessageHeader/>" + + "</a:Message>"; + Diff d = buildDiff(xml1, xml2); + assertFalse(d.toString(), d.identical()); + assertTrue(d.toString(), d.similar()); + } + } Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java 2007-05-12 19:54:41 UTC (rev 208) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java 2007-05-16 11:25:23 UTC (rev 209) @@ -780,6 +780,57 @@ assertEquals(expectDifference, listener.different); } + public void testMissingSchemaLocation() throws Exception { + testMissingXSIAttribute(XMLConstants + .W3C_XML_SCHEMA_INSTANCE_SCHEMA_LOCATION_ATTR, + DifferenceConstants.SCHEMA_LOCATION_ID); + } + + public void testMissingNoNamespaceSchemaLocation() throws Exception { + testMissingXSIAttribute(XMLConstants + .W3C_XML_SCHEMA_INSTANCE_NO_NAMESPACE_SCHEMA_LOCATION_ATTR, + DifferenceConstants.NO_NAMESPACE_SCHEMA_LOCATION_ID); + } + + private void testMissingXSIAttribute(String attrName, + int expectedDifference) + throws Exception { + Element control = document.createElement("foo"); + control.setAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, + attrName, "bar"); + Element test = document.createElement("foo"); + engine.compare(control, test, listener, null); + assertEquals(expectedDifference, listener.comparingWhat); + //resetListener(); + //engine.compare(test, control, listener, null); + //assertEquals(expectedDifference, listener.comparingWhat); + } + + public void testDifferentSchemaLocation() throws Exception { + testDifferentXSIAttribute(XMLConstants + .W3C_XML_SCHEMA_INSTANCE_SCHEMA_LOCATION_ATTR, + DifferenceConstants.SCHEMA_LOCATION_ID); + } + + public void testDifferentNoNamespaceSchemaLocation() throws Exception { + testDifferentXSIAttribute(XMLConstants + .W3C_XML_SCHEMA_INSTANCE_NO_NAMESPACE_SCHEMA_LOCATION_ATTR, + DifferenceConstants.NO_NAMESPACE_SCHEMA_LOCATION_ID); + } + + private void testDifferentXSIAttribute(String attrName, + int expectedDifference) + throws Exception { + Element control = document.createElement("foo"); + control.setAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, + attrName, "bar"); + Element test = document.createElement("foo"); + test.setAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, + attrName, "baz"); + engine.compare(control, test, listener, null); + assertEquals(expectedDifference, listener.comparingWhat); + } + private void listenToDifferences(String control, String test) throws SAXException, IOException { Document controlDoc = XMLUnit.buildControlDocument(control); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-05-18 05:25:54
|
Revision: 210 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=210&view=rev Author: bodewig Date: 2007-05-17 22:25:53 -0700 (Thu, 17 May 2007) Log Message: ----------- make attribute check symmetric Modified Paths: -------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Diff.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java 2007-05-16 11:25:23 UTC (rev 209) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java 2007-05-18 05:25:53 UTC (rev 210) @@ -485,6 +485,14 @@ NamedNodeMap testAttr, DifferenceListener listener) throws DifferenceFoundException { + ArrayList allTestAttrs = new ArrayList(); + for (int i=0; i < testAttr.getLength(); ++i) { + Attr nextAttr = (Attr) testAttr.item(i); + if (!isXMLNSAttribute(nextAttr)) { + allTestAttrs.add(nextAttr); + } + } + for (int i=0; i < controlAttr.getLength(); ++i) { Attr nextAttr = (Attr) controlAttr.item(i); if (isXMLNSAttribute(nextAttr)) { @@ -501,6 +509,10 @@ compareTo = (Attr) testAttr.getNamedItem(attrName); } + if (compareTo != null) { + allTestAttrs.remove(compareTo); + } + if (isRecognizedXMLSchemaInstanceAttribute(nextAttr)) { compareRecognizedXMLSchemaInstanceAttribute(nextAttr, compareTo, @@ -525,6 +537,20 @@ } } } + + for (Iterator iter = allTestAttrs.iterator(); iter.hasNext(); ) { + Attr nextAttr = (Attr) iter.next(); + if (isRecognizedXMLSchemaInstanceAttribute(nextAttr)) { + compareRecognizedXMLSchemaInstanceAttribute(null, nextAttr, + listener); + } else { + compare(null, + getUnNamespacedNodeName(nextAttr, + isNamespaced(nextAttr)), + control, test, listener, ATTR_NAME_NOT_FOUND); + } + } + controlTracker.clearTrackedAttribute(); testTracker.clearTrackedAttribute(); } @@ -577,17 +603,20 @@ Attr test, DifferenceListener listener) throws DifferenceFoundException { + Attr nonNullNode = control != null ? control : test; Difference d = XMLConstants.W3C_XML_SCHEMA_INSTANCE_SCHEMA_LOCATION_ATTR - .equals(control.getLocalName()) + .equals(nonNullNode.getLocalName()) ? SCHEMA_LOCATION : NO_NAMESPACE_SCHEMA_LOCATION; - controlTracker.visited(control); + if (control != null) { + controlTracker.visited(control); + } if (test != null) { testTracker.visited(test); } - compare(control.getValue(), + compare(control != null ? control.getValue() : "[not specified]", test != null ? test.getValue() : "[not specified]", control, test, listener, d); } Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java 2007-05-16 11:25:23 UTC (rev 209) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java 2007-05-18 05:25:53 UTC (rev 210) @@ -81,15 +81,18 @@ List differences = detailedDiff.getAllDifferences(); - assertEquals("size: " + detailedDiff, 4, differences.size()); + assertEquals("size: " + detailedDiff, 5, differences.size()); assertEquals("first: " + detailedDiff, DifferenceConstants.ELEMENT_NUM_ATTRIBUTES, differences.get(0)); assertEquals("second: " + detailedDiff, DifferenceConstants.ATTR_VALUE, differences.get(1)); assertEquals("third: " + detailedDiff, DifferenceConstants.ATTR_SEQUENCE, differences.get(2)); - assertEquals("fourth: " + detailedDiff, - DifferenceConstants.HAS_CHILD_NODES, differences.get(3)); + assertEquals("forth: " + detailedDiff, + DifferenceConstants.ATTR_NAME_NOT_FOUND, + differences.get(3)); + assertEquals("fifth: " + detailedDiff, + DifferenceConstants.HAS_CHILD_NODES, differences.get(4)); } public void testPrototypeIsADetailedDiff() throws Exception { Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Diff.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Diff.java 2007-05-16 11:25:23 UTC (rev 209) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_Diff.java 2007-05-18 05:25:53 UTC (rev 210) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 200, Jeff Martin, Tim Bacon +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without @@ -686,7 +686,7 @@ /** * inspired by {@link * http://day-to-day-stuff.blogspot.com/2007/05/comparing-xml-in-junit-test.html - * Erik von Oosten's Weblog }, made us implement special handling + * Erik von Oosten's Weblog}, made us implement special handling * of schemaLocation. */ public void testNamespacePrefixDiff() throws Exception { Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java 2007-05-16 11:25:23 UTC (rev 209) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java 2007-05-18 05:25:53 UTC (rev 210) @@ -801,9 +801,9 @@ Element test = document.createElement("foo"); engine.compare(control, test, listener, null); assertEquals(expectedDifference, listener.comparingWhat); - //resetListener(); - //engine.compare(test, control, listener, null); - //assertEquals(expectedDifference, listener.comparingWhat); + resetListener(); + engine.compare(test, control, listener, null); + assertEquals(expectedDifference, listener.comparingWhat); } public void testDifferentSchemaLocation() throws Exception { @@ -831,6 +831,15 @@ assertEquals(expectedDifference, listener.comparingWhat); } + public void testMissingAttribute() throws Exception { + Element control = document.createElement("foo"); + control.setAttribute("bar", "baz"); + Element test = document.createElement("foo"); + test.setAttribute("baz", "bar"); + engine.compare(control, test, listener, null); + assertEquals(ATTR_NAME_NOT_FOUND_ID, listener.comparingWhat); + } + private void listenToDifferences(String control, String test) throws SAXException, IOException { Document controlDoc = XMLUnit.buildControlDocument(control); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-06-27 11:45:21
|
Revision: 221 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=221&view=rev Author: bodewig Date: 2007-06-27 04:45:24 -0700 (Wed, 27 Jun 2007) Log Message: ----------- bump version Modified Paths: -------------- trunk/xmlunit/build.xml trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java Modified: trunk/xmlunit/build.xml =================================================================== --- trunk/xmlunit/build.xml 2007-06-27 11:44:23 UTC (rev 220) +++ trunk/xmlunit/build.xml 2007-06-27 11:45:24 UTC (rev 221) @@ -4,7 +4,7 @@ <property file="build.properties"/> <!-- Version --> - <property name="xmlunit.version" value="1.1beta3"/> + <property name="xmlunit.version" value="1.2alpha"/> <!-- some locations --> <property name="src.dir" value="src"/> Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java 2007-06-27 11:44:23 UTC (rev 220) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/XMLUnit.java 2007-06-27 11:45:24 UTC (rev 221) @@ -477,7 +477,7 @@ * @return current version */ public static String getVersion() { - return "1.1beta3"; + return "1.2alpha"; } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2007-08-10 07:30:51
|
Revision: 229 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=229&view=rev Author: bodewig Date: 2007-08-10 00:30:53 -0700 (Fri, 10 Aug 2007) Log Message: ----------- optionally ignore element content whitespace in MultiLevelElementNameAndTextQualifier Modified Paths: -------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/examples/MultiLevelElementNameAndTextQualifier.java trunk/xmlunit/src/user-guide/XMLUnit-Java.xml trunk/xmlunit/tests/java/org/custommonkey/xmlunit/examples/test_MultiLevelElementNameAndTextQualifier.java Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/examples/MultiLevelElementNameAndTextQualifier.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/examples/MultiLevelElementNameAndTextQualifier.java 2007-08-01 07:50:24 UTC (rev 228) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/examples/MultiLevelElementNameAndTextQualifier.java 2007-08-10 07:30:53 UTC (rev 229) @@ -52,7 +52,7 @@ * ElementNameQualifier} and MultiLevelElementNameQualifier(1) should * lead to the same results.</p> * - * <p>Any attribute values ar completely ignored. Only works on + * <p>Any attribute values are completely ignored. Only works on * elements with exactly one child element at each level.</p> * * <p>This class mostly exists as an example for custom ElementQualifiers.</p> @@ -61,6 +61,7 @@ implements ElementQualifier { private final int levels; + private final boolean ignoreEmptyTexts; private static final ElementNameQualifier NAME_QUALIFIER = new ElementNameQualifier(); @@ -70,13 +71,28 @@ /** * Uses element names and the text nested <code>levels</code> * child elements deeper into the element to compare elements. + * + * <p>Does not ignore empty text nodes. */ public MultiLevelElementNameAndTextQualifier(int levels) { + this(levels, false); + } + + /** + * Uses element names and the text nested <code>levels</code> + * child elements deeper into the element to compare elements. + * + * @param ignoreEmptyTexts whether whitespace-only textnodes + * should be ignored. + */ + public MultiLevelElementNameAndTextQualifier(int levels, + boolean ignoreEmptyTexts) { if (levels < 1) { throw new IllegalArgumentException("levels must be equal or" + " greater than one"); } this.levels = levels; + this.ignoreEmptyTexts = ignoreEmptyTexts; } public boolean qualifyForComparison(Element control, Element test) { @@ -89,11 +105,12 @@ currentLevel++) { stillSimilar = NAME_QUALIFIER.qualifyForComparison(currentControl, currentTest); + if (stillSimilar) { if (currentControl.hasChildNodes() && currentTest.hasChildNodes()) { - Node n1 = currentControl.getFirstChild(); - Node n2 = currentTest.getFirstChild(); + Node n1 = getFirstEligibleChild(currentControl); + Node n2 = getFirstEligibleChild(currentTest); if (n1.getNodeType() == Node.ELEMENT_NODE && n2.getNodeType() == Node.ELEMENT_NODE) { currentControl = (Element) n1; @@ -115,5 +132,17 @@ return stillSimilar; } - + + private Node getFirstEligibleChild(Node parent) { + Node n1 = parent.getFirstChild(); + if (ignoreEmptyTexts) { + while (n1.getNodeType() == Node.TEXT_NODE + && n1.getNodeValue().trim().length() == 0) { + Node n2 = n1.getNextSibling(); + if (n2 == null) break; + n1 = n2; + } + } + return n1; + } } Modified: trunk/xmlunit/src/user-guide/XMLUnit-Java.xml =================================================================== --- trunk/xmlunit/src/user-guide/XMLUnit-Java.xml 2007-08-01 07:50:24 UTC (rev 228) +++ trunk/xmlunit/src/user-guide/XMLUnit-Java.xml 2007-08-10 07:30:53 UTC (rev 229) @@ -14,8 +14,6 @@ <firstname>Tim</firstname> <surname>Bacon</surname> </author> - </authorgroup> - <authorgroup> <author> <firstname>Stefan</firstname> <surname>Bodewig</surname> @@ -36,6 +34,11 @@ <date>April 2007</date> <revremark>Documentation for XMLUnit Java 1.1</revremark> </revision> + <revision> + <revnumber>1.2</revnumber> + <date>...</date> + <revremark>Documentation for XMLUnit Java 1.2</revremark> + </revision> </revhistory> </articleinfo> @@ -1911,6 +1914,21 @@ identical to <literal>ElementNameAndTextQualifier</literal>. In <xref linkend="htmltable"/> a value of 2 would be needed.</para> + + <para>By default + <literal>MultiLevelElementNameAndTextQualifier</literal> will + not ignore whitespace between the elements leading up to the + nested text. If your piece of XML contains this sort of + whitespace (like <xref linkend="htmltable"/> which contains a + newline and several space characters between + <literal><tr></literal> and + <literal><td></literal>) you can either instruct XMLUnit + to ignore whitespace completely (see + <xref linkend="Whitespace Handling"/>) or use the two-arg + constructor of + <literal>MultiLevelElementNameAndTextQualifier</literal> + introduced with XMLUnit 1.2 and set the + <literal>ignoreEmptyTexts</literal> argument to true.</para> </section> </section> @@ -3215,6 +3233,11 @@ </itemizedlist> </section> </section> + + <section id="Changes 1.2"> + <title>Changes from XMLUnit 1.1 to 1.2</title> + </section> + </appendix> </article> Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/examples/test_MultiLevelElementNameAndTextQualifier.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/examples/test_MultiLevelElementNameAndTextQualifier.java 2007-08-01 07:50:24 UTC (rev 228) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/examples/test_MultiLevelElementNameAndTextQualifier.java 2007-08-10 07:30:53 UTC (rev 229) @@ -140,7 +140,7 @@ } - public void XtestUserGuideExample() throws Exception { + public void testUserGuideExample() throws Exception { String control = "<table>\n" + " <tr>\n" @@ -162,16 +162,21 @@ Diff d = new Diff(control, test); d.overrideElementQualifier(new MultiLevelElementNameAndTextQualifier(2)); - //assertTrue(d.toString(), d.similar()); + assertFalse(d.toString(), d.similar()); - d = new Diff(control, test); - d.overrideElementQualifier(new MultiLevelElementNameAndTextQualifier(2)); try { XMLUnit.setIgnoreWhitespace(true); + d = new Diff(control, test); + d.overrideElementQualifier(new MultiLevelElementNameAndTextQualifier(2)); assertTrue(d.toString(), d.similar()); } finally { XMLUnit.setIgnoreWhitespace(false); } + + d = new Diff(control, test); + d.overrideElementQualifier(new MultiLevelElementNameAndTextQualifier(2, + true)); + assertTrue(d.toString(), d.similar()); } public void setUp() throws Exception { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2008-01-28 14:49:46
|
Revision: 237 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=237&view=rev Author: bodewig Date: 2008-01-28 06:49:49 -0800 (Mon, 28 Jan 2008) Log Message: ----------- make stuff work with NUnit 2.4 Modified Paths: -------------- trunk/xmlunit/NUnit.ReadMe trunk/xmlunit/src/csharp/AssemblyInfo.cs trunk/xmlunit/tests/csharp/DiffConfigurationTests.cs trunk/xmlunit/tests/csharp/XmlAssertionTests.cs trunk/xmlunit/xmlunit.nant.build Modified: trunk/xmlunit/NUnit.ReadMe =================================================================== --- trunk/xmlunit/NUnit.ReadMe 2008-01-04 10:24:02 UTC (rev 236) +++ trunk/xmlunit/NUnit.ReadMe 2008-01-28 14:49:49 UTC (rev 237) @@ -2,16 +2,20 @@ ================ To run this software you will need: -- Nunit v2.1 (http://nunit.org/) -- .NET runtime v1.1 or Mono runtime v0.28 (or above) +- Nunit v2.2 or above (http://nunit.org/) +- .NET runtime v1.1 or Mono runtime v1.0 (or above) If you want to build the source code yourself you will also need NAnt (http://nant.sourceforge.net/) -This build of the source code was prepared using .NET csc 1.1.4322, NUnit2.1.4, and NAnt0.8.3 +This build of the source code was prepared using .NET csc 1.1.4322, NUnit2.4.6, and NAnt0.8.5 Enjoy! http://xmlunit.sourceforge.net/ +Changes in version 0.3.1: +- made it compile and all tests pass on .NET 1.1 as well as 2.0 and + NUnit 2.4 + Changes in version 0.3: - New XSLT assertions - New XmlOutput class @@ -23,4 +27,4 @@ - Removed (ab)use of statics - thanks Joe Changes in version 0.1: -- New classes for basic xml differencing \ No newline at end of file +- New classes for basic xml differencing Modified: trunk/xmlunit/src/csharp/AssemblyInfo.cs =================================================================== --- trunk/xmlunit/src/csharp/AssemblyInfo.cs 2008-01-04 10:24:02 UTC (rev 236) +++ trunk/xmlunit/src/csharp/AssemblyInfo.cs 2008-01-28 14:49:49 UTC (rev 237) @@ -23,7 +23,7 @@ // You can specify all values by your own or you can build default build and revision // numbers with the '*' character (the default): -[assembly: AssemblyVersion("0.3.0.0")] +[assembly: AssemblyVersion("0.3.1.0")] // The following attributes specify the key for the sign of your assembly. See the // .NET Framework documentation for more information about signing. Modified: trunk/xmlunit/tests/csharp/DiffConfigurationTests.cs =================================================================== --- trunk/xmlunit/tests/csharp/DiffConfigurationTests.cs 2008-01-04 10:24:02 UTC (rev 236) +++ trunk/xmlunit/tests/csharp/DiffConfigurationTests.cs 2008-01-28 14:49:49 UTC (rev 237) @@ -21,24 +21,30 @@ new XmlDiff("", "").OptionalDescription); } - [Test][ExpectedException(typeof(XmlSchemaValidationException))] + [Test] public void DefaultConfiguredToUseValidatingParser() { DiffConfiguration diffConfiguration = new DiffConfiguration(); Assert.AreEqual(DiffConfiguration.DEFAULT_USE_VALIDATING_PARSER, diffConfiguration.UseValidatingParser); - FileStream controlFileStream = File.Open(ValidatorTests.VALID_FILE, - FileMode.Open, FileAccess.Read); - FileStream testFileStream = File.Open(ValidatorTests.INVALID_FILE, - FileMode.Open, FileAccess.Read); - try { + bool exception = false; + using (FileStream controlFileStream = File.Open(ValidatorTests.VALID_FILE, + FileMode.Open, + FileAccess.Read)) + using (FileStream testFileStream = File.Open(ValidatorTests.INVALID_FILE, + FileMode.Open, + FileAccess.Read)) { + try { XmlDiff diff = new XmlDiff(new StreamReader(controlFileStream), new StreamReader(testFileStream)); diff.Compare(); - } finally { - controlFileStream.Close(); - testFileStream.Close(); + } catch (System.Exception) { + // should be an XmlSchemaValidationException in .NET 2.0 + // and later + exception = true; + } } + Assert.IsTrue(exception, "expected validation to fail"); } [Test] Modified: trunk/xmlunit/tests/csharp/XmlAssertionTests.cs =================================================================== --- trunk/xmlunit/tests/csharp/XmlAssertionTests.cs 2008-01-04 10:24:02 UTC (rev 236) +++ trunk/xmlunit/tests/csharp/XmlAssertionTests.cs 2008-01-28 14:49:49 UTC (rev 237) @@ -29,7 +29,7 @@ XmlAssertion.AssertXmlIdentical(diff); caughtException = false; } catch (NUnit.Framework.AssertionException e) { - Assert.IsTrue(e.Message.StartsWith(description)); + Assert.IsTrue(e.Message.IndexOf(description) > -1); } Assert.IsTrue(caughtException); } @@ -43,7 +43,7 @@ XmlAssertion.AssertXmlEquals(diff); caughtException = false; } catch (NUnit.Framework.AssertionException e) { - Assert.AreEqual(true, e.Message.StartsWith(description)); + Assert.IsTrue(e.Message.IndexOf(description) > -1); } Assert.IsTrue(caughtException); } Modified: trunk/xmlunit/xmlunit.nant.build =================================================================== --- trunk/xmlunit/xmlunit.nant.build 2008-01-04 10:24:02 UTC (rev 236) +++ trunk/xmlunit/xmlunit.nant.build 2008-01-28 14:49:49 UTC (rev 237) @@ -1,5 +1,5 @@ <project name="xmlunit" description="XmlUnit for .Net" default="compile"> - <property name="project.version" value="0.3" overwrite="false"/> + <property name="project.version" value="0.3.1" overwrite="false"/> <property name="base.dir" value="${project::get-base-directory()}" overwrite="false"/> <property name="src.dir" value="${base.dir}/src/csharp" overwrite="false"/> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2008-03-03 16:05:05
|
Revision: 240 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=240&view=rev Author: bodewig Date: 2008-03-03 08:04:35 -0800 (Mon, 03 Mar 2008) Log Message: ----------- fix XPath expressions when missing a node, issue 1860681 Modified Paths: -------------- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java trunk/xmlunit/src/user-guide/XMLUnit-Java.xml trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java Modified: trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java =================================================================== --- trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java 2008-02-04 12:04:58 UTC (rev 239) +++ trunk/xmlunit/src/java/org/custommonkey/xmlunit/DifferenceEngine.java 2008-03-03 16:04:35 UTC (rev 240) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 2001-2007, Jeff Martin, Tim Bacon +Copyright (c) 2001-2008, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without @@ -356,6 +356,7 @@ int j = 0; final int lastTestNode = testChildren.size() - 1; + controlTracker.preloadChildList(controlChildren); testTracker.preloadChildList(testChildren); HashMap/*<Node, Node>*/ matchingNodes = new HashMap(); @@ -418,19 +419,30 @@ compare(new Integer(i), testIndex, nextControl, nextTest, listener, CHILD_NODELIST_SEQUENCE); } else { - compare(nextControl.getNodeName(), null, nextControl, null, - listener, CHILD_NODE_NOT_FOUND); + missingNode(nextControl, null, listener); } } // now handle remaining unmatched test nodes for (Iterator iter = unmatchedTestNodes.iterator(); iter.hasNext();) { - Node n = (Node) iter.next(); - compare(null, n.getNodeName(), null, n, listener, - CHILD_NODE_NOT_FOUND); + missingNode(null, (Node) iter.next(), listener); } } + private void missingNode(Node control, Node test, + DifferenceListener listener) + throws DifferenceFoundException { + if (control != null) { + controlTracker.visited(control); + compare(control.getNodeName(), null, control, null, + listener, CHILD_NODE_NOT_FOUND, controlTracker, null); + } else { + testTracker.visited(test); + compare(null, test.getNodeName(), null, test, listener, + CHILD_NODE_NOT_FOUND, null, testTracker); + } + } + /** * @param aNode * @return true if the node has a namespace @@ -760,11 +772,35 @@ protected void compare(Object expected, Object actual, Node control, Node test, DifferenceListener listener, Difference difference) throws DifferenceFoundException { + compare(expected, actual, control, test, listener, difference, + controlTracker, testTracker); + } + + /** + * If the expected and actual values are unequal then inform the listener of + * a difference and throw a DifferenceFoundException. + * @param expected + * @param actual + * @param control + * @param test + * @param listener + * @param differenceType + * @throws DifferenceFoundException + */ + protected void compare(Object expected, Object actual, + Node control, Node test, DifferenceListener listener, + Difference difference, XpathNodeTracker controlLoc, + XpathNodeTracker testLoc) + throws DifferenceFoundException { if (unequal(expected, actual)) { NodeDetail controlDetail = new NodeDetail(String.valueOf(expected), - control, controlTracker.toXpathString()); + control, + controlLoc == null ? null + : controlLoc.toXpathString()); NodeDetail testDetail = new NodeDetail(String.valueOf(actual), - test, testTracker.toXpathString()); + test, + testLoc == null ? null + : testLoc.toXpathString()); Difference differenceInstance = new Difference(difference, controlDetail, testDetail); listener.differenceFound(differenceInstance); Modified: trunk/xmlunit/src/user-guide/XMLUnit-Java.xml =================================================================== --- trunk/xmlunit/src/user-guide/XMLUnit-Java.xml 2008-02-04 12:04:58 UTC (rev 239) +++ trunk/xmlunit/src/user-guide/XMLUnit-Java.xml 2008-03-03 16:04:35 UTC (rev 240) @@ -3236,6 +3236,34 @@ <section id="Changes 1.2"> <title>Changes from XMLUnit 1.1 to 1.2</title> + + <section id="Breaking Changes 1.2"> + <title>Breaking Changes</title> + + <itemizedlist> + <listitem> + If XMLUnit detects that it cannot match a certain node + (i.e. it encounters + a <literal>CHILD_NODE_NOT_FOUND</literal> + kind of difference) the XPath for the "missing" node will + be null. It used to be some random XPath of a different node. + </listitem> + </itemizedlist> + </section> + + <section id="Bugfixes 1.2"> + <title>Important Bug Fixes</title> + + <itemizedlist> + <listitem> + If XMLUnit couldn't match nodes (i.e. it encountered + a <literal>CHILD_NODE_NOT_FOUND</literal> kind of + difference), the XPath expressions of the node details + have been random. <ulink + url="https://sourceforge.net/tracker/index.php?func=detail&aid=1860681&group_id=23187&atid=377768">Issue 1860681</ulink>. + </listitem> + </itemizedlist> + </section> </section> </appendix> Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java 2008-02-04 12:04:58 UTC (rev 239) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DetailedDiff.java 2008-03-03 16:04:35 UTC (rev 240) @@ -248,7 +248,7 @@ * Bug 1860681 * @see https://sourceforge.net/tracker/index.php?func=detail&aid=1860681&group_id=23187&atid=377768 */ - public void XtestXpathOfMissingNode() throws Exception { + public void testXpathOfMissingNode() throws Exception { String control = "<books>" + " <book>" @@ -277,7 +277,9 @@ d.getId()); assertEquals("/books[1]/book[1]", d.getControlNodeDetail().getXpathLocation()); - assertNull(d.getTestNodeDetail().getXpathLocation()); + assertNull("should be null but is " + + d.getTestNodeDetail().getXpathLocation(), + d.getTestNodeDetail().getXpathLocation()); // and reverse diff = new Diff(test, control); Modified: trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java =================================================================== --- trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java 2008-02-04 12:04:58 UTC (rev 239) +++ trunk/xmlunit/tests/java/org/custommonkey/xmlunit/test_DifferenceEngine.java 2008-03-03 16:04:35 UTC (rev 240) @@ -1,6 +1,6 @@ /* ****************************************************************** -Copyright (c) 2001-2007, Jeff Martin, Tim Bacon +Copyright (c) 2001-2008, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without @@ -620,10 +620,13 @@ String control = "<stuff><item id=\"1\"/><item id=\"2\"/></stuff>"; String test = "<stuff><?item data?></stuff>"; listenToDifferences(control, test); - assertEquals("13th control xpath", "/stuff[1]/item[1]", + // mutiple Differences, we only see the last one, missing second element + assertEquals("13 difference type", + DifferenceConstants.CHILD_NODE_NOT_FOUND_ID, + listener.comparingWhat); + assertEquals("13th control xpath", "/stuff[1]/item[2]", listener.controlXpath); - assertEquals("13th test xpath", "/stuff[1]/processing-instruction()[1]", - listener.testXpath); + assertNull("13th test xpath", listener.testXpath); } public void testXpathLocation14() throws Exception { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |