From: <bo...@us...> - 2010-06-24 15:31:31
|
Revision: 405 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=405&view=rev Author: bodewig Date: 2010-06-24 15:31:25 +0000 (Thu, 24 Jun 2010) Log Message: ----------- comparisons for texts, PIs and Document Nodes (the latter lacking tests for now) Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonType.java trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonType.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonType.java 2010-06-21 14:37:51 UTC (rev 404) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonType.java 2010-06-24 15:31:25 UTC (rev 405) @@ -18,6 +18,19 @@ */ public enum ComparisonType { /** + * Do both documents specify the same version in their XML declaration? + */ + XML_VERSION, + /** + * Do both documents specify the same standalone declaration in + * their XML declaration? + */ + XML_STANDALONE, + /** + * Do both documents specify the same encoding in their XML declaration? + */ + XML_ENCODING, + /** * Do both documents have a DOCTYPE (or neither of each)? */ HAS_DOCTYPE_DECLARATION, @@ -62,17 +75,10 @@ NAMESPACE_URI, /** - * Compare content of CDATA sections. + * Compare content of text nodes, comments and CDATA sections. */ - CDATA_VALUE, - /** - * Compare content of comments. - */ - COMMENT_VALUE, - /** - * Compare content of text nodes. - */ TEXT_VALUE, + /** * Compare targets of processing instructions. */ Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java 2010-06-21 14:37:51 UTC (rev 404) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java 2010-06-24 15:31:25 UTC (rev 405) @@ -13,11 +13,15 @@ */ package net.sf.xmlunit.diff; +import javax.xml.transform.Source; import net.sf.xmlunit.util.Convert; -import javax.xml.transform.Source; +import org.w3c.dom.CharacterData; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentType; +import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import org.w3c.dom.Document; +import org.w3c.dom.ProcessingInstruction; /** * Difference engine based on DOM. @@ -90,22 +94,22 @@ ComparisonResult compareNodes(Node control, Node test) { ComparisonResult lastResult = compare(new Comparison(ComparisonType.NODE_TYPE, control, - null, control.getNodeType(), - test, null, test.getNodeType())); + null, control.getNodeType(), + test, null, test.getNodeType())); if (lastResult == ComparisonResult.CRITICAL) { return lastResult; } lastResult = compare(new Comparison(ComparisonType.NAMESPACE_URI, control, - null, control.getNamespaceURI(), - test, null, test.getNamespaceURI())); + null, control.getNamespaceURI(), + test, null, test.getNamespaceURI())); if (lastResult == ComparisonResult.CRITICAL) { return lastResult; } lastResult = compare(new Comparison(ComparisonType.NAMESPACE_PREFIX, control, - null, control.getPrefix(), - test, null, test.getPrefix())); + null, control.getPrefix(), + test, null, test.getPrefix())); if (lastResult == ComparisonResult.CRITICAL) { return lastResult; } @@ -113,15 +117,143 @@ NodeList testChildren = test.getChildNodes(); lastResult = compare(new Comparison(ComparisonType.CHILD_NODELIST_LENGTH, - control, null, controlChildren.getLength(), - test, null, testChildren.getLength())); + control, null, controlChildren.getLength(), + test, null, testChildren.getLength())); if (lastResult == ComparisonResult.CRITICAL) { return lastResult; } - /* TODO node type specific stuff */ + lastResult = nodeTypeSpecificComparison(control, test); + if (lastResult == ComparisonResult.CRITICAL) { + return lastResult; + } return compareNodeLists(controlChildren, testChildren); } + /** + * Dispatches to the node type specific comparison if one is + * defined for the given combination of nodes. + * + * <p>package private to support tests.</p> + */ + ComparisonResult nodeTypeSpecificComparison(Node control, Node test) { + switch (control.getNodeType()) { + case Node.CDATA_SECTION_NODE: + case Node.COMMENT_NODE: + case Node.TEXT_NODE: + if (test instanceof CharacterData) { + return compareCharacterData((CharacterData) control, + (CharacterData) test); + } + break; + case Node.DOCUMENT_NODE: + if (test instanceof Document) { + return compareDocuments((Document) control, + (Document) test); + } + break; + case Node.ELEMENT_NODE: + if (test instanceof Element) { + return compareElements((Element) control, + (Element) test); + } + break; + case Node.PROCESSING_INSTRUCTION_NODE: + if (test instanceof ProcessingInstruction) { + return + compareProcessingInstructions((ProcessingInstruction) control, + (ProcessingInstruction) test); + } + break; + } + return ComparisonResult.EQUAL; + } + + /** + * Compares textual content. + */ + private ComparisonResult compareCharacterData(CharacterData control, + CharacterData test) { + return compare(new Comparison(ComparisonType.TEXT_VALUE, control, + null, control.getData(), + test, null, test.getData())); + } + + ComparisonResult compareDocuments(Document control, + Document test) { + DocumentType controlDt = control.getDoctype(); + DocumentType testDt = test.getDoctype(); + ComparisonResult r = + compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, + control, null, + Boolean.valueOf(controlDt != null), + test, null, + Boolean.valueOf(testDt != null))); + if (r == ComparisonResult.CRITICAL) { + return r; + } + if (controlDt != null && testDt != null) { + r = compareDocTypes(controlDt, testDt); + } + if (r == ComparisonResult.CRITICAL) { + return r; + } + r = compare(new Comparison(ComparisonType.XML_VERSION, + control, null, control.getXmlVersion(), + test, null, test.getXmlVersion())); + if (r == ComparisonResult.CRITICAL) { + return r; + } + r = compare(new Comparison(ComparisonType.XML_STANDALONE, + control, null, control.getXmlStandalone(), + test, null, test.getXmlStandalone())); + if (r == ComparisonResult.CRITICAL) { + return r; + } + return compare(new Comparison(ComparisonType.XML_ENCODING, + control, null, control.getXmlEncoding(), + test, null, test.getXmlEncoding())); + } + + ComparisonResult compareDocTypes(DocumentType control, + DocumentType test) { + ComparisonResult r = + compare(new Comparison(ComparisonType.DOCTYPE_NAME, + control, null, control.getName(), + test, null, test.getName())); + if (r == ComparisonResult.CRITICAL) { + return r; + } + r = compare(new Comparison(ComparisonType.DOCTYPE_PUBLIC_ID, + control, null, control.getPublicId(), + test, null, test.getPublicId())); + if (r == ComparisonResult.CRITICAL) { + return r; + } + return compare(new Comparison(ComparisonType.DOCTYPE_SYSTEM_ID, + control, null, control.getSystemId(), + test, null, test.getSystemId())); + } + + ComparisonResult compareElements(Element control, + Element test) { + return ComparisonResult.EQUAL; + } + + ComparisonResult + compareProcessingInstructions(ProcessingInstruction control, + ProcessingInstruction test) { + ComparisonResult r = + compare(new Comparison(ComparisonType.PROCESSING_INSTRUCTION_TARGET, + control, null, control.getTarget(), + test, null, test.getTarget())); + if (r == ComparisonResult.CRITICAL) { + return r; + } + return compare(new Comparison(ComparisonType.PROCESSING_INSTRUCTION_DATA, + control, null, control.getData(), + test, null, test.getData())); + } + ComparisonResult compareNodeLists(NodeList control, NodeList test) { return ComparisonResult.EQUAL; } Modified: trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs 2010-06-21 14:37:51 UTC (rev 404) +++ trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs 2010-06-24 15:31:25 UTC (rev 405) @@ -63,17 +63,10 @@ NAMESPACE_URI, /// <summary> - /// Compare content of CDATA sections. + /// Compare content of text nodes, comments, CDATA sections. /// </summary> - CDATA_VALUE, - /// <summary> - /// Compare content of comments. - /// </summary> - COMMENT_VALUE, - /// <summary> - /// Compare content of text nodes. - /// </summary> TEXT_VALUE, + /// <summary> /// Compare targets of processing instructions. /// </summary> @@ -99,6 +92,7 @@ /// Compare attribute's value. /// </summary> ATTR_VALUE, + /// <summary> /// Compare number of child nodes. /// </summary> Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-06-21 14:37:51 UTC (rev 404) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-06-24 15:31:25 UTC (rev 405) @@ -17,8 +17,12 @@ import javax.xml.parsers.DocumentBuilderFactory; import org.junit.Before; import org.junit.Test; +import org.w3c.dom.CDATASection; +import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.Element; +import org.w3c.dom.ProcessingInstruction; +import org.w3c.dom.Text; import static org.junit.Assert.*; public class DOMDifferenceEngineTest { @@ -218,4 +222,88 @@ assertEquals(2, ex.invoked); } + @Test public void compareCharacterData() { + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.TEXT_VALUE, 9); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); + + Comment fooComment = doc.createComment("foo"); + Comment barComment = doc.createComment("bar"); + Text fooText = doc.createTextNode("foo"); + Text barText = doc.createTextNode("bar"); + CDATASection fooCDATASection = doc.createCDATASection("foo"); + CDATASection barCDATASection = doc.createCDATASection("bar"); + + assertEquals(ComparisonResult.EQUAL, + d.nodeTypeSpecificComparison(fooComment, fooComment)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(fooComment, barComment)); + assertEquals(ComparisonResult.EQUAL, + d.nodeTypeSpecificComparison(fooText, fooText)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(fooText, barText)); + assertEquals(ComparisonResult.EQUAL, + d.nodeTypeSpecificComparison(fooCDATASection, fooCDATASection)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(fooCDATASection, barCDATASection)); + + assertEquals(ComparisonResult.EQUAL, + d.nodeTypeSpecificComparison(fooComment, fooText)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(fooComment, barText)); + assertEquals(ComparisonResult.EQUAL, + d.nodeTypeSpecificComparison(fooComment, fooCDATASection)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(fooComment, barCDATASection)); + assertEquals(ComparisonResult.EQUAL, + d.nodeTypeSpecificComparison(fooText, fooComment)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(fooText, barComment)); + assertEquals(ComparisonResult.EQUAL, + d.nodeTypeSpecificComparison(fooText, fooCDATASection)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(fooText, barCDATASection)); + assertEquals(ComparisonResult.EQUAL, + d.nodeTypeSpecificComparison(fooCDATASection, fooText)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(fooCDATASection, barText)); + assertEquals(ComparisonResult.EQUAL, + d.nodeTypeSpecificComparison(fooCDATASection, fooComment)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(fooCDATASection, barComment)); + assertEquals(ComparisonResult.EQUAL, + d.nodeTypeSpecificComparison(fooText, + doc.createElement("bar"))); + assertEquals(9, ex.invoked); + } + + @Test public void compareProcessingInstructions() { + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.PROCESSING_INSTRUCTION_TARGET); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); + + ProcessingInstruction foo1 = doc.createProcessingInstruction("foo", "1"); + ProcessingInstruction bar1 = doc.createProcessingInstruction("bar", "1"); + assertEquals(ComparisonResult.EQUAL, + d.nodeTypeSpecificComparison(foo1, foo1)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(foo1, bar1)); + assertEquals(ComparisonResult.EQUAL, + d.nodeTypeSpecificComparison(foo1, + doc.createElement("bar"))); + assertEquals(1, ex.invoked); + + d = new DOMDifferenceEngine(); + ex = new DiffExpecter(ComparisonType.PROCESSING_INSTRUCTION_DATA); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); + ProcessingInstruction foo2 = doc.createProcessingInstruction("foo", "2"); + assertEquals(ComparisonResult.EQUAL, + d.nodeTypeSpecificComparison(foo1, foo1)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(foo1, foo2)); + assertEquals(1, ex.invoked); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-06-25 15:35:49
|
Revision: 406 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=406&view=rev Author: bodewig Date: 2010-06-25 15:35:43 +0000 (Fri, 25 Jun 2010) Log Message: ----------- port the node specific tests that already have unit tests Modified Paths: -------------- trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.cs trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs Modified: trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.cs 2010-06-24 15:31:25 UTC (rev 405) +++ trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.cs 2010-06-25 15:35:43 UTC (rev 406) @@ -98,10 +98,80 @@ if (lastResult == ComparisonResult.CRITICAL) { return lastResult; } - /* TODO node type specific stuff */ + lastResult = NodeTypeSpecificComparison(control, test); + if (lastResult == ComparisonResult.CRITICAL) { + return lastResult; + } return CompareNodeLists(controlChildren, testChildren); } + /// <summary> + /// Dispatches to the node type specific comparison if one is + /// defined for the given combination of nodes. + /// </summary> + internal ComparisonResult NodeTypeSpecificComparison(XmlNode control, + XmlNode test) { + switch (control.NodeType) { + case XmlNodeType.CDATA: + case XmlNodeType.Comment: + case XmlNodeType.Text: + if (test is XmlCharacterData) { + return CompareCharacterData((XmlCharacterData) control, + (XmlCharacterData) test); + } + break; + case XmlNodeType.Document: +#if false + if (test instanceof Document) { + return compareDocuments((Document) control, + (Document) test); + } +#endif + break; + case XmlNodeType.Element: +#if false + if (test instanceof Element) { + return compareElements((Element) control, + (Element) test); + } +#endif + break; + case XmlNodeType.ProcessingInstruction: + if (test is XmlProcessingInstruction) { + return + CompareProcessingInstructions((XmlProcessingInstruction) control, + (XmlProcessingInstruction) test); + } + break; + } + return ComparisonResult.EQUAL; + } + + /// <summary> + /// Compares textual content. + /// </summary> + private ComparisonResult CompareCharacterData(XmlCharacterData control, + XmlCharacterData test) { + return Compare(new Comparison(ComparisonType.TEXT_VALUE, control, + null, control.Data, + test, null, test.Data)); + } + + private ComparisonResult + CompareProcessingInstructions(XmlProcessingInstruction control, + XmlProcessingInstruction test) { + ComparisonResult r = + Compare(new Comparison(ComparisonType.PROCESSING_INSTRUCTION_TARGET, + control, null, control.Target, + test, null, test.Target)); + if (r == ComparisonResult.CRITICAL) { + return r; + } + return Compare(new Comparison(ComparisonType.PROCESSING_INSTRUCTION_DATA, + control, null, control.Data, + test, null, test.Data)); + } + ComparisonResult CompareNodeLists(XmlNodeList control, XmlNodeList test) { return ComparisonResult.EQUAL; Modified: trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-06-24 15:31:25 UTC (rev 405) +++ trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-06-25 15:35:43 UTC (rev 406) @@ -237,5 +237,132 @@ Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(e1, e2)); Assert.AreEqual(2, invocations); } + + [Test] + public void CompareCharacterData() { + DOMDifferenceEngine d = new DOMDifferenceEngine(); + int invocations = 0; + d.DifferenceListener += delegate(Comparison comp, + ComparisonResult r) { + Assert.Greater(9, invocations); + invocations++; + Assert.AreEqual(ComparisonType.TEXT_VALUE, + comp.Type); + Assert.AreEqual(ComparisonResult.CRITICAL, r); + }; + d.DifferenceEvaluator = + DifferenceEvaluators.DefaultStopWhenDifferent; + + XmlComment fooComment = doc.CreateComment("foo"); + XmlComment barComment = doc.CreateComment("bar"); + XmlText fooText = doc.CreateTextNode("foo"); + XmlText barText = doc.CreateTextNode("bar"); + XmlCDataSection fooCDataSection = doc.CreateCDataSection("foo"); + XmlCDataSection barCDataSection = doc.CreateCDataSection("bar"); + + Assert.AreEqual(ComparisonResult.EQUAL, + d.NodeTypeSpecificComparison(fooComment, + fooComment)); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(fooComment, + barComment)); + Assert.AreEqual(ComparisonResult.EQUAL, + d.NodeTypeSpecificComparison(fooText, fooText)); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(fooText, barText)); + Assert.AreEqual(ComparisonResult.EQUAL, + d.NodeTypeSpecificComparison(fooCDataSection, + fooCDataSection)); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(fooCDataSection, + barCDataSection)); + + Assert.AreEqual(ComparisonResult.EQUAL, + d.NodeTypeSpecificComparison(fooComment, fooText)); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(fooComment, barText)); + Assert.AreEqual(ComparisonResult.EQUAL, + d.NodeTypeSpecificComparison(fooComment, + fooCDataSection)); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(fooComment, + barCDataSection)); + Assert.AreEqual(ComparisonResult.EQUAL, + d.NodeTypeSpecificComparison(fooText, + fooComment)); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(fooText, barComment)); + Assert.AreEqual(ComparisonResult.EQUAL, + d.NodeTypeSpecificComparison(fooText, + fooCDataSection)); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(fooText, + barCDataSection)); + Assert.AreEqual(ComparisonResult.EQUAL, + d.NodeTypeSpecificComparison(fooCDataSection, + fooText)); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(fooCDataSection, + barText)); + Assert.AreEqual(ComparisonResult.EQUAL, + d.NodeTypeSpecificComparison(fooCDataSection, + fooComment)); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(fooCDataSection, + barComment)); + Assert.AreEqual(ComparisonResult.EQUAL, + d.NodeTypeSpecificComparison(fooText, + doc.CreateElement("bar"))); + Assert.AreEqual(9, invocations); + } + + [Test] public void compareProcessingInstructions() { + DOMDifferenceEngine d = new DOMDifferenceEngine(); + int invocations = 0; + d.DifferenceListener += delegate(Comparison comp, + ComparisonResult r) { + Assert.AreEqual(0, invocations); + invocations++; + Assert.AreEqual(ComparisonType.PROCESSING_INSTRUCTION_TARGET, + comp.Type); + Assert.AreEqual(ComparisonResult.CRITICAL, r); + }; + d.DifferenceEvaluator = + DifferenceEvaluators.DefaultStopWhenDifferent; + + XmlProcessingInstruction foo1 = doc.CreateProcessingInstruction("foo", + "1"); + XmlProcessingInstruction bar1 = doc.CreateProcessingInstruction("bar", + "1"); + Assert.AreEqual(ComparisonResult.EQUAL, + d.NodeTypeSpecificComparison(foo1, foo1)); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(foo1, bar1)); + Assert.AreEqual(ComparisonResult.EQUAL, + d.NodeTypeSpecificComparison(foo1, + doc.CreateElement("bar"))); + Assert.AreEqual(1, invocations); + + d = new DOMDifferenceEngine(); + invocations = 0; + d.DifferenceListener += delegate(Comparison comp, + ComparisonResult r) { + Assert.AreEqual(0, invocations); + invocations++; + Assert.AreEqual(ComparisonType.PROCESSING_INSTRUCTION_DATA, + comp.Type); + Assert.AreEqual(ComparisonResult.CRITICAL, r); + }; + d.DifferenceEvaluator = + DifferenceEvaluators.DefaultStopWhenDifferent; + XmlProcessingInstruction foo2 = doc.CreateProcessingInstruction("foo", + "2"); + Assert.AreEqual(ComparisonResult.EQUAL, + d.NodeTypeSpecificComparison(foo1, foo1)); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(foo1, foo2)); + Assert.AreEqual(1, invocations); + } + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-06-28 11:49:15
|
Revision: 407 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=407&view=rev Author: bodewig Date: 2010-06-28 11:49:08 +0000 (Mon, 28 Jun 2010) Log Message: ----------- extract an abstract difference engine implementation Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.cs trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs Added Paths: ----------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/AbstractDifferenceEngine.java trunk/xmlunit/src/main/net-core/diff/AbstractDifferenceEngine.cs trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/AbstractDifferenceEngineTest.java trunk/xmlunit/src/tests/net-core/diff/AbstractDifferenceEngineTest.cs Copied: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/AbstractDifferenceEngine.java (from rev 406, trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java) =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/AbstractDifferenceEngine.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/AbstractDifferenceEngine.java 2010-06-28 11:49:08 UTC (rev 407) @@ -0,0 +1,88 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package net.sf.xmlunit.diff; + +/** + * Useful base-implementation of some parts of the DifferenceEngine + * interface. + */ +public abstract class AbstractDifferenceEngine implements DifferenceEngine { + private final ComparisonListenerSupport listeners = + new ComparisonListenerSupport(); + private ElementSelector elementSelector = ElementSelectors.Default; + private DifferenceEvaluator diffEvaluator = DifferenceEvaluators.Default; + + public void addComparisonListener(ComparisonListener l) { + if (l == null) { + throw new IllegalArgumentException("listener must not be null"); + } + listeners.addComparisonListener(l); + } + + public void addMatchListener(ComparisonListener l) { + if (l == null) { + throw new IllegalArgumentException("listener must not be null"); + } + listeners.addMatchListener(l); + } + + public void addDifferenceListener(ComparisonListener l) { + if (l == null) { + throw new IllegalArgumentException("listener must not be null"); + } + listeners.addDifferenceListener(l); + } + + public void setElementSelector(ElementSelector s) { + if (s == null) { + throw new IllegalArgumentException("element selector must" + + " not be null"); + } + elementSelector = s; + } + + public ElementSelector getElementSelector() { + return elementSelector; + } + + public void setDifferenceEvaluator(DifferenceEvaluator e) { + if (e == null) { + throw new IllegalArgumentException("difference evaluator must" + + " not be null"); + } + diffEvaluator = e; + } + + public DifferenceEvaluator getDifferenceEvaluator() { + return diffEvaluator; + } + + /** + * Compares the detail values for object equality, lets the + * difference evaluator evaluate the result, notifies all + * listeners and returns the outcome. + */ + protected final ComparisonResult compare(Comparison comp) { + Object controlValue = comp.getControlNodeDetails().getValue(); + Object testValue = comp.getTestNodeDetails().getValue(); + boolean equal = controlValue == null + ? testValue == null : controlValue.equals(testValue); + ComparisonResult initial = + equal ? ComparisonResult.EQUAL : ComparisonResult.DIFFERENT; + ComparisonResult altered = + getDifferenceEvaluator().evaluate(comp, initial); + listeners.fireComparisonPerformed(comp, altered); + return altered; + } +} Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java 2010-06-25 15:35:43 UTC (rev 406) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java 2010-06-28 11:49:08 UTC (rev 407) @@ -26,49 +26,8 @@ /** * Difference engine based on DOM. */ -public final class DOMDifferenceEngine implements DifferenceEngine { - private final ComparisonListenerSupport listeners = - new ComparisonListenerSupport(); - private ElementSelector elementSelector = ElementSelectors.Default; - private DifferenceEvaluator diffEvaluator = DifferenceEvaluators.Default; +public final class DOMDifferenceEngine extends AbstractDifferenceEngine { - public void addComparisonListener(ComparisonListener l) { - if (l == null) { - throw new IllegalArgumentException("listener must not be null"); - } - listeners.addComparisonListener(l); - } - - public void addMatchListener(ComparisonListener l) { - if (l == null) { - throw new IllegalArgumentException("listener must not be null"); - } - listeners.addMatchListener(l); - } - - public void addDifferenceListener(ComparisonListener l) { - if (l == null) { - throw new IllegalArgumentException("listener must not be null"); - } - listeners.addDifferenceListener(l); - } - - public void setElementSelector(ElementSelector s) { - if (s == null) { - throw new IllegalArgumentException("element selector must" - + " not be null"); - } - elementSelector = s; - } - - public void setDifferenceEvaluator(DifferenceEvaluator e) { - if (e == null) { - throw new IllegalArgumentException("difference evaluator must" - + " not be null"); - } - diffEvaluator = e; - } - public void compare(Source control, Source test) { if (control == null) { throw new IllegalArgumentException("control must not be null"); @@ -257,23 +216,4 @@ ComparisonResult compareNodeLists(NodeList control, NodeList test) { return ComparisonResult.EQUAL; } - - /** - * Compares the detail values for object equality, lets the - * difference evaluator evaluate the result, notifies all - * listeners and returns the outcome. - * - * <p>package private to support tests.</p> - */ - ComparisonResult compare(Comparison comp) { - Object controlValue = comp.getControlNodeDetails().getValue(); - Object testValue = comp.getTestNodeDetails().getValue(); - boolean equal = controlValue == null - ? testValue == null : controlValue.equals(testValue); - ComparisonResult initial = - equal ? ComparisonResult.EQUAL : ComparisonResult.DIFFERENT; - ComparisonResult altered = diffEvaluator.evaluate(comp, initial); - listeners.fireComparisonPerformed(comp, altered); - return altered; - } } Copied: trunk/xmlunit/src/main/net-core/diff/AbstractDifferenceEngine.cs (from rev 406, trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.cs) =================================================================== --- trunk/xmlunit/src/main/net-core/diff/AbstractDifferenceEngine.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/diff/AbstractDifferenceEngine.cs 2010-06-28 11:49:08 UTC (rev 407) @@ -0,0 +1,86 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +using System; + +namespace net.sf.xmlunit.diff { + + /// <summary> + /// Useful base-implementation of some parts of the + /// IDifferenceEngine interface. + /// </summary> + public abstract class AbstractDifferenceEngine : IDifferenceEngine { + public event ComparisonListener ComparisonListener; + public event ComparisonListener MatchListener; + public event ComparisonListener DifferenceListener; + + private ElementSelector elementSelector = ElementSelectors.Default; + public virtual ElementSelector ElementSelector { + set { + if (value == null) { + throw new ArgumentNullException("element selector"); + } + elementSelector = value; + } + get { + return elementSelector; + } + } + + private DifferenceEvaluator diffEvaluator = DifferenceEvaluators.Default; + public virtual DifferenceEvaluator DifferenceEvaluator { + set { + if (value == null) { + throw new ArgumentNullException("difference evaluator"); + } + diffEvaluator = value; + } + get { + return diffEvaluator; + } + } + + public abstract void Compare(ISource control, ISource test); + + /// <summary> + /// Compares the detail values for object equality, lets the + /// difference evaluator evaluate the result, notifies all + /// listeners and returns the outcome. + /// </summary> + protected internal ComparisonResult Compare(Comparison comp) { + object controlValue = comp.ControlNodeDetails.Value; + object testValue = comp.TestNodeDetails.Value; + bool equal = controlValue == null + ? testValue == null : controlValue.Equals(testValue); + ComparisonResult initial = + equal ? ComparisonResult.EQUAL : ComparisonResult.DIFFERENT; + ComparisonResult altered = DifferenceEvaluator(comp, initial); + FireComparisonPerformed(comp, altered); + return altered; + } + + private void FireComparisonPerformed(Comparison comp, + ComparisonResult outcome) { + if (ComparisonListener != null) { + ComparisonListener(comp, outcome); + } + if (outcome == ComparisonResult.EQUAL && MatchListener != null) { + MatchListener(comp, outcome); + } else if (outcome != ComparisonResult.EQUAL + && DifferenceListener != null) { + DifferenceListener(comp, outcome); + } + } + } +} Modified: trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.cs 2010-06-25 15:35:43 UTC (rev 406) +++ trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.cs 2010-06-28 11:49:08 UTC (rev 407) @@ -20,32 +20,9 @@ /// <summary> /// Difference engine based on DOM. /// </summary> - public sealed class DOMDifferenceEngine : IDifferenceEngine { - public event ComparisonListener ComparisonListener; - public event ComparisonListener MatchListener; - public event ComparisonListener DifferenceListener; + public sealed class DOMDifferenceEngine : AbstractDifferenceEngine { - private ElementSelector elementSelector = ElementSelectors.Default; - public ElementSelector ElementSelector { - set { - if (value == null) { - throw new ArgumentNullException("element selector"); - } - elementSelector = value; - } - } - - private DifferenceEvaluator diffEvaluator = DifferenceEvaluators.Default; - public DifferenceEvaluator DifferenceEvaluator { - set { - if (value == null) { - throw new ArgumentNullException("difference evaluator"); - } - diffEvaluator = value; - } - } - - public void Compare(ISource control, ISource test) { + public override void Compare(ISource control, ISource test) { if (control == null) { throw new ArgumentNullException("control"); } @@ -177,34 +154,5 @@ return ComparisonResult.EQUAL; } - /// <summary> - /// Compares the detail values for object equality, lets the - /// difference evaluator evaluate the result, notifies all - /// listeners and returns the outcome. - /// </summary> - internal ComparisonResult Compare(Comparison comp) { - object controlValue = comp.ControlNodeDetails.Value; - object testValue = comp.TestNodeDetails.Value; - bool equal = controlValue == null - ? testValue == null : controlValue.Equals(testValue); - ComparisonResult initial = - equal ? ComparisonResult.EQUAL : ComparisonResult.DIFFERENT; - ComparisonResult altered = diffEvaluator(comp, initial); - FireComparisonPerformed(comp, altered); - return altered; - } - - private void FireComparisonPerformed(Comparison comp, - ComparisonResult outcome) { - if (ComparisonListener != null) { - ComparisonListener(comp, outcome); - } - if (outcome == ComparisonResult.EQUAL && MatchListener != null) { - MatchListener(comp, outcome); - } else if (outcome != ComparisonResult.EQUAL - && DifferenceListener != null) { - DifferenceListener(comp, outcome); - } - } } } Copied: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/AbstractDifferenceEngineTest.java (from rev 406, trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java) =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/AbstractDifferenceEngineTest.java (rev 0) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/AbstractDifferenceEngineTest.java 2010-06-28 11:49:08 UTC (rev 407) @@ -0,0 +1,117 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package net.sf.xmlunit.diff; + +import org.junit.Test; +import static org.junit.Assert.*; + +public abstract class AbstractDifferenceEngineTest { + + protected abstract AbstractDifferenceEngine getDifferenceEngine(); + + private static class ResultGrabber implements DifferenceEvaluator { + private ComparisonResult outcome = ComparisonResult.CRITICAL; + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult outcome) { + this.outcome = outcome; + return outcome; + } + } + + @Test public void compareTwoNulls() { + ResultGrabber g = new ResultGrabber(); + AbstractDifferenceEngine d = getDifferenceEngine(); + d.setDifferenceEvaluator(g); + assertEquals(ComparisonResult.EQUAL, + d.compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, + null, null, null, + null, null, null))); + assertEquals(ComparisonResult.EQUAL, g.outcome); + } + + @Test public void compareControlNullTestNonNull() { + ResultGrabber g = new ResultGrabber(); + AbstractDifferenceEngine d = getDifferenceEngine(); + d.setDifferenceEvaluator(g); + assertEquals(ComparisonResult.DIFFERENT, + d.compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, + null, null, null, + null, null, ""))); + assertEquals(ComparisonResult.DIFFERENT, g.outcome); + } + + @Test public void compareControlNonNullTestNull() { + ResultGrabber g = new ResultGrabber(); + AbstractDifferenceEngine d = getDifferenceEngine(); + d.setDifferenceEvaluator(g); + assertEquals(ComparisonResult.DIFFERENT, + d.compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, + null, null, "", + null, null, null))); + assertEquals(ComparisonResult.DIFFERENT, g.outcome); + } + + @Test public void compareTwoDifferentNonNulls() { + ResultGrabber g = new ResultGrabber(); + AbstractDifferenceEngine d = getDifferenceEngine(); + d.setDifferenceEvaluator(g); + assertEquals(ComparisonResult.DIFFERENT, + d.compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, + null, null, new Short("1"), + null, null, new Short("2")))); + assertEquals(ComparisonResult.DIFFERENT, g.outcome); + } + + @Test public void compareTwoEqualNonNulls() { + ResultGrabber g = new ResultGrabber(); + AbstractDifferenceEngine d = getDifferenceEngine(); + d.setDifferenceEvaluator(g); + assertEquals(ComparisonResult.EQUAL, + d.compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, + null, null, new Short("2"), + null, null, new Short("2")))); + assertEquals(ComparisonResult.EQUAL, g.outcome); + } + + @Test public void compareNotifiesListener() { + AbstractDifferenceEngine d = getDifferenceEngine(); + ComparisonListenerSupportTest.Listener l = + new ComparisonListenerSupportTest.Listener(ComparisonResult.EQUAL); + d.addComparisonListener(l); + assertEquals(ComparisonResult.EQUAL, + d.compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, + null, null, new Short("2"), + null, null, new Short("2")))); + assertEquals(1, l.getInvocations()); + } + + @Test public void compareUsesResultOfEvaluator() { + AbstractDifferenceEngine d = getDifferenceEngine(); + ComparisonListenerSupportTest.Listener l = + new ComparisonListenerSupportTest.Listener(ComparisonResult.SIMILAR); + d.addComparisonListener(l); + d.setDifferenceEvaluator(new DifferenceEvaluator() { + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult outcome) { + return ComparisonResult.SIMILAR; + } + }); + assertEquals(ComparisonResult.SIMILAR, + d.compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, + null, null, new Short("2"), + null, null, new Short("2")))); + assertEquals(1, l.getInvocations()); + } + +} Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-06-25 15:35:43 UTC (rev 406) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-06-28 11:49:08 UTC (rev 407) @@ -25,102 +25,12 @@ import org.w3c.dom.Text; import static org.junit.Assert.*; -public class DOMDifferenceEngineTest { +public class DOMDifferenceEngineTest extends AbstractDifferenceEngineTest { - private static class ResultGrabber implements DifferenceEvaluator { - private ComparisonResult outcome = ComparisonResult.CRITICAL; - public ComparisonResult evaluate(Comparison comparison, - ComparisonResult outcome) { - this.outcome = outcome; - return outcome; - } + @Override protected AbstractDifferenceEngine getDifferenceEngine() { + return new DOMDifferenceEngine(); } - @Test public void compareTwoNulls() { - ResultGrabber g = new ResultGrabber(); - DOMDifferenceEngine d = new DOMDifferenceEngine(); - d.setDifferenceEvaluator(g); - assertEquals(ComparisonResult.EQUAL, - d.compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, - null, null, null, - null, null, null))); - assertEquals(ComparisonResult.EQUAL, g.outcome); - } - - @Test public void compareControlNullTestNonNull() { - ResultGrabber g = new ResultGrabber(); - DOMDifferenceEngine d = new DOMDifferenceEngine(); - d.setDifferenceEvaluator(g); - assertEquals(ComparisonResult.DIFFERENT, - d.compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, - null, null, null, - null, null, ""))); - assertEquals(ComparisonResult.DIFFERENT, g.outcome); - } - - @Test public void compareControlNonNullTestNull() { - ResultGrabber g = new ResultGrabber(); - DOMDifferenceEngine d = new DOMDifferenceEngine(); - d.setDifferenceEvaluator(g); - assertEquals(ComparisonResult.DIFFERENT, - d.compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, - null, null, "", - null, null, null))); - assertEquals(ComparisonResult.DIFFERENT, g.outcome); - } - - @Test public void compareTwoDifferentNonNulls() { - ResultGrabber g = new ResultGrabber(); - DOMDifferenceEngine d = new DOMDifferenceEngine(); - d.setDifferenceEvaluator(g); - assertEquals(ComparisonResult.DIFFERENT, - d.compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, - null, null, new Short("1"), - null, null, new Short("2")))); - assertEquals(ComparisonResult.DIFFERENT, g.outcome); - } - - @Test public void compareTwoEqualNonNulls() { - ResultGrabber g = new ResultGrabber(); - DOMDifferenceEngine d = new DOMDifferenceEngine(); - d.setDifferenceEvaluator(g); - assertEquals(ComparisonResult.EQUAL, - d.compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, - null, null, new Short("2"), - null, null, new Short("2")))); - assertEquals(ComparisonResult.EQUAL, g.outcome); - } - - @Test public void compareNotifiesListener() { - DOMDifferenceEngine d = new DOMDifferenceEngine(); - ComparisonListenerSupportTest.Listener l = - new ComparisonListenerSupportTest.Listener(ComparisonResult.EQUAL); - d.addComparisonListener(l); - assertEquals(ComparisonResult.EQUAL, - d.compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, - null, null, new Short("2"), - null, null, new Short("2")))); - assertEquals(1, l.getInvocations()); - } - - @Test public void compareUsesResultOfEvaluator() { - DOMDifferenceEngine d = new DOMDifferenceEngine(); - ComparisonListenerSupportTest.Listener l = - new ComparisonListenerSupportTest.Listener(ComparisonResult.SIMILAR); - d.addComparisonListener(l); - d.setDifferenceEvaluator(new DifferenceEvaluator() { - public ComparisonResult evaluate(Comparison comparison, - ComparisonResult outcome) { - return ComparisonResult.SIMILAR; - } - }); - assertEquals(ComparisonResult.SIMILAR, - d.compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, - null, null, new Short("2"), - null, null, new Short("2")))); - assertEquals(1, l.getInvocations()); - } - private static class DiffExpecter implements ComparisonListener { private int invoked = 0; private final int expectedInvocations; Copied: trunk/xmlunit/src/tests/net-core/diff/AbstractDifferenceEngineTest.cs (from rev 406, trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs) =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/AbstractDifferenceEngineTest.cs (rev 0) +++ trunk/xmlunit/src/tests/net-core/diff/AbstractDifferenceEngineTest.cs 2010-06-28 11:49:08 UTC (rev 407) @@ -0,0 +1,132 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +using System; +using NUnit.Framework; + +namespace net.sf.xmlunit.diff { + + public abstract class AbstractDifferenceEngineTest { + + protected abstract AbstractDifferenceEngine DifferenceEngine { + get; + } + + private ComparisonResult outcome = ComparisonResult.CRITICAL; + private ComparisonResult ResultGrabber(Comparison comparison, + ComparisonResult outcome) { + this.outcome = outcome; + return outcome; + } + + [Test] + public void CompareTwoNulls() { + AbstractDifferenceEngine d = DifferenceEngine; + d.DifferenceEvaluator = ResultGrabber; + Assert.AreEqual(ComparisonResult.EQUAL, + d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, + null, null, null, + null, null, null))); + Assert.AreEqual(ComparisonResult.EQUAL, outcome); + } + + [Test] + public void CompareControlNullTestNonNull() { + AbstractDifferenceEngine d = DifferenceEngine; + d.DifferenceEvaluator = ResultGrabber; + Assert.AreEqual(ComparisonResult.DIFFERENT, + d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, + null, null, null, + null, null, ""))); + Assert.AreEqual(ComparisonResult.DIFFERENT, outcome); + } + + [Test] + public void CompareControlNonNullTestNull() { + AbstractDifferenceEngine d = DifferenceEngine; + d.DifferenceEvaluator = ResultGrabber; + Assert.AreEqual(ComparisonResult.DIFFERENT, + d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, + null, null, "", + null, null, null))); + Assert.AreEqual(ComparisonResult.DIFFERENT, outcome); + } + + [Test] + public void CompareTwoDifferentNonNulls() { + AbstractDifferenceEngine d = DifferenceEngine; + d.DifferenceEvaluator = ResultGrabber; + Assert.AreEqual(ComparisonResult.DIFFERENT, + d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, + null, null, + Convert.ToInt16("1"), + null, null, + Convert.ToInt16("2")))); + Assert.AreEqual(ComparisonResult.DIFFERENT, outcome); + } + + [Test] + public void CompareTwoEqualNonNulls() { + AbstractDifferenceEngine d = DifferenceEngine; + d.DifferenceEvaluator = ResultGrabber; + Assert.AreEqual(ComparisonResult.EQUAL, + d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, + null, null, + Convert.ToInt16("2"), + null, null, + Convert.ToInt16("2")))); + Assert.AreEqual(ComparisonResult.EQUAL, outcome); + } + + [Test] + public void CompareNotifiesListener() { + AbstractDifferenceEngine d = DifferenceEngine; + int invocations = 0; + d.ComparisonListener += delegate(Comparison comp, + ComparisonResult r) { + invocations++; + Assert.AreEqual(ComparisonResult.EQUAL, r); + }; + Assert.AreEqual(ComparisonResult.EQUAL, + d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, + null, null, + Convert.ToInt16("2"), + null, null, + Convert.ToInt16("2")))); + Assert.AreEqual(1, invocations); + } + + [Test] + public void CompareUsesResultOfEvaluator() { + AbstractDifferenceEngine d = DifferenceEngine; + int invocations = 0; + d.ComparisonListener += delegate(Comparison comp, + ComparisonResult r) { + invocations++; + Assert.AreEqual(ComparisonResult.SIMILAR, r); + }; + d.DifferenceEvaluator = delegate(Comparison comparison, + ComparisonResult outcome) { + return ComparisonResult.SIMILAR; + }; + Assert.AreEqual(ComparisonResult.SIMILAR, + d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, + null, null, + Convert.ToInt16("2"), + null, null, + Convert.ToInt16("2")))); + Assert.AreEqual(1, invocations); + } + + } +} Modified: trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-06-25 15:35:43 UTC (rev 406) +++ trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-06-28 11:49:08 UTC (rev 407) @@ -18,114 +18,14 @@ namespace net.sf.xmlunit.diff { [TestFixture] - public class DOMDifferenceEngineTest { + public class DOMDifferenceEngineTest : AbstractDifferenceEngineTest { - private ComparisonResult outcome = ComparisonResult.CRITICAL; - private ComparisonResult ResultGrabber(Comparison comparison, - ComparisonResult outcome) { - this.outcome = outcome; - return outcome; + protected override AbstractDifferenceEngine DifferenceEngine { + get { + return new DOMDifferenceEngine(); + } } - [Test] - public void CompareTwoNulls() { - DOMDifferenceEngine d = new DOMDifferenceEngine(); - d.DifferenceEvaluator = ResultGrabber; - Assert.AreEqual(ComparisonResult.EQUAL, - d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, - null, null, null, - null, null, null))); - Assert.AreEqual(ComparisonResult.EQUAL, outcome); - } - - [Test] - public void CompareControlNullTestNonNull() { - DOMDifferenceEngine d = new DOMDifferenceEngine(); - d.DifferenceEvaluator = ResultGrabber; - Assert.AreEqual(ComparisonResult.DIFFERENT, - d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, - null, null, null, - null, null, ""))); - Assert.AreEqual(ComparisonResult.DIFFERENT, outcome); - } - - [Test] - public void CompareControlNonNullTestNull() { - DOMDifferenceEngine d = new DOMDifferenceEngine(); - d.DifferenceEvaluator = ResultGrabber; - Assert.AreEqual(ComparisonResult.DIFFERENT, - d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, - null, null, "", - null, null, null))); - Assert.AreEqual(ComparisonResult.DIFFERENT, outcome); - } - - [Test] - public void CompareTwoDifferentNonNulls() { - DOMDifferenceEngine d = new DOMDifferenceEngine(); - d.DifferenceEvaluator = ResultGrabber; - Assert.AreEqual(ComparisonResult.DIFFERENT, - d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, - null, null, - Convert.ToInt16("1"), - null, null, - Convert.ToInt16("2")))); - Assert.AreEqual(ComparisonResult.DIFFERENT, outcome); - } - - [Test] - public void CompareTwoEqualNonNulls() { - DOMDifferenceEngine d = new DOMDifferenceEngine(); - d.DifferenceEvaluator = ResultGrabber; - Assert.AreEqual(ComparisonResult.EQUAL, - d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, - null, null, - Convert.ToInt16("2"), - null, null, - Convert.ToInt16("2")))); - Assert.AreEqual(ComparisonResult.EQUAL, outcome); - } - - [Test] - public void CompareNotifiesListener() { - DOMDifferenceEngine d = new DOMDifferenceEngine(); - int invocations = 0; - d.ComparisonListener += delegate(Comparison comp, - ComparisonResult r) { - invocations++; - Assert.AreEqual(ComparisonResult.EQUAL, r); - }; - Assert.AreEqual(ComparisonResult.EQUAL, - d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, - null, null, - Convert.ToInt16("2"), - null, null, - Convert.ToInt16("2")))); - Assert.AreEqual(1, invocations); - } - - [Test] - public void CompareUsesResultOfEvaluator() { - DOMDifferenceEngine d = new DOMDifferenceEngine(); - int invocations = 0; - d.ComparisonListener += delegate(Comparison comp, - ComparisonResult r) { - invocations++; - Assert.AreEqual(ComparisonResult.SIMILAR, r); - }; - d.DifferenceEvaluator = delegate(Comparison comparison, - ComparisonResult outcome) { - return ComparisonResult.SIMILAR; - }; - Assert.AreEqual(ComparisonResult.SIMILAR, - d.Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, - null, null, - Convert.ToInt16("2"), - null, null, - Convert.ToInt16("2")))); - Assert.AreEqual(1, invocations); - } - private XmlDocument doc; [SetUp] @@ -316,7 +216,8 @@ Assert.AreEqual(9, invocations); } - [Test] public void compareProcessingInstructions() { + [Test] + public void CompareProcessingInstructions() { DOMDifferenceEngine d = new DOMDifferenceEngine(); int invocations = 0; d.DifferenceListener += delegate(Comparison comp, This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-07-06 10:43:46
|
Revision: 410 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=410&view=rev Author: bodewig Date: 2010-07-06 10:43:39 +0000 (Tue, 06 Jul 2010) Log Message: ----------- tests for document and document type level comparisions Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/TestResources.java trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java Added Paths: ----------- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/NullNode.java Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java 2010-06-29 04:26:39 UTC (rev 409) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java 2010-07-06 10:43:39 UTC (rev 410) @@ -53,6 +53,7 @@ case NAMESPACE_PREFIX: case ATTR_VALUE_EXPLICITLY_SPECIFIED: case CHILD_NODELIST_SEQUENCE: + case XML_ENCODING: outcome = ComparisonResult.SIMILAR; break; } Added: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/NullNode.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/NullNode.java (rev 0) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/NullNode.java 2010-07-06 10:43:39 UTC (rev 410) @@ -0,0 +1,133 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package net.sf.xmlunit; + +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.UserDataHandler; + +public class NullNode implements Node { + public Node appendChild(Node n) { + return n; + } + public Node cloneNode(boolean deep) { + return this; + } + public short compareDocumentPosition(Node other) { + return 0; + } + public NamedNodeMap getAttributes() { + return null; + } + public String getBaseURI() { + return null; + } + public NodeList getChildNodes() { + return new NodeList() { + public int getLength() { + return 0; + } + public Node item(int idx) { + throw new IndexOutOfBoundsException(); + } + }; + } + public Object getFeature(String f, String v) { + return null; + } + public Node getFirstChild() { + return null; + } + public Node getLastChild() { + return null; + } + public String getLocalName() { + return null; + } + public String getNamespaceURI() { + return null; + } + public Node getNextSibling() { + return null; + } + public String getNodeName() { + return null; + } + public short getNodeType() { + return 0; + } + public String getNodeValue() { + return null; + } + public Document getOwnerDocument() { + return null; + } + public Node getParentNode() { + return null; + } + public String getPrefix() { + return null; + } + public Node getPreviousSibling() { + return null; + } + public String getTextContent() { + return null; + } + public Object getUserData(String key) { + return null; + } + public boolean hasAttributes() { + return false; + } + public boolean hasChildNodes() { + return false; + } + public Node insertBefore(Node n, Node r) { + return n; + } + public boolean isDefaultNamespace(String u) { + return false; + } + public boolean isEqualNode(Node n) { + return isSameNode(n); + } + public boolean isSameNode(Node n) { + return this == n; + } + public boolean isSupported(String f, String v) { + return false; + } + public String lookupNamespaceURI(String s) { + return null; + } + public String lookupPrefix(String s) { + return null; + } + public void normalize() { } + public Node removeChild(Node n) { + return n; + } + public Node replaceChild(Node n, Node o) { + return o; + } + public void setNodeValue(String s) { } + public void setPrefix(String s) { } + public void setTextContent(String s) { } + public Object setUserData(String k, Object d, UserDataHandler h) { + return null; + } +} Property changes on: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/NullNode.java ___________________________________________________________________ Added: svn:eol-style + native Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/TestResources.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/TestResources.java 2010-06-29 04:26:39 UTC (rev 409) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/TestResources.java 2010-07-06 10:43:39 UTC (rev 410) @@ -19,6 +19,8 @@ public static final String ANIMAL_XSL = "src/tests/resources/animal.xsl"; public static final String DOG_FILE = "src/tests/resources/testAnimal.xml"; + public static final String BOOK_DTD = "src/tests/resources/Book.dtd"; + private TestResources() { } } Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-06-29 04:26:39 UTC (rev 409) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-07-06 10:43:39 UTC (rev 410) @@ -15,12 +15,18 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; +import net.sf.xmlunit.NullNode; +import net.sf.xmlunit.TestResources; +import net.sf.xmlunit.builder.Input; +import net.sf.xmlunit.util.Convert; import org.junit.Before; import org.junit.Test; import org.w3c.dom.CDATASection; import org.w3c.dom.Comment; import org.w3c.dom.Document; +import org.w3c.dom.DocumentType; import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; import static org.junit.Assert.*; @@ -216,4 +222,150 @@ d.nodeTypeSpecificComparison(foo1, foo2)); assertEquals(1, ex.invoked); } + + @Test public void compareDocuments() { + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.HAS_DOCTYPE_DECLARATION); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(new DifferenceEvaluator() { + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult outcome) { + if (comparison.getType() + == ComparisonType.HAS_DOCTYPE_DECLARATION) { + assertEquals(ComparisonResult.DIFFERENT, outcome); + return ComparisonResult.CRITICAL; + } + assertEquals(ComparisonResult.EQUAL, outcome); + return ComparisonResult.EQUAL; + } + }); + Document d1 = Convert.toDocument(Input.fromMemory("<Book/>").build()); + Document d2 = + Convert.toDocument(Input.fromMemory("<!DOCTYPE Book PUBLIC " + + "\"XMLUNIT/TEST/PUB\" " + + "\"" + TestResources.BOOK_DTD + + "\">" + + "<Book/>") + .build()); + assertEquals(ComparisonResult.CRITICAL, d.compareDocuments(d1, d2)); + assertEquals(1, ex.invoked); + + d = new DOMDifferenceEngine(); + ex = new DiffExpecter(ComparisonType.XML_VERSION); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); + + d1 = Convert.toDocument(Input.fromMemory("<?xml version=\"1.0\"" + + " encoding=\"UTF-8\"?>" + + "<Book/>").build()); + d2 = Convert.toDocument(Input.fromMemory("<?xml version=\"1.1\"" + + " encoding=\"UTF-8\"?>" + + "<Book/>").build()); + assertEquals(ComparisonResult.CRITICAL, d.compareDocuments(d1, d2)); + assertEquals(1, ex.invoked); + + d = new DOMDifferenceEngine(); + ex = new DiffExpecter(ComparisonType.XML_STANDALONE); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); + + d1 = Convert.toDocument(Input.fromMemory("<?xml version=\"1.0\"" + + " standalone=\"yes\"?>" + + "<Book/>").build()); + d2 = Convert.toDocument(Input.fromMemory("<?xml version=\"1.0\"" + + " standalone=\"no\"?>" + + "<Book/>").build()); + assertEquals(ComparisonResult.CRITICAL, d.compareDocuments(d1, d2)); + assertEquals(1, ex.invoked); + + d = new DOMDifferenceEngine(); + ex = new DiffExpecter(ComparisonType.XML_ENCODING); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(new DifferenceEvaluator() { + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult outcome) { + if (comparison.getType() + == ComparisonType.XML_ENCODING) { + assertEquals(ComparisonResult.DIFFERENT, outcome); + return ComparisonResult.CRITICAL; + } + assertEquals(ComparisonResult.EQUAL, outcome); + return ComparisonResult.EQUAL; + } + }); + + d1 = Convert.toDocument(Input.fromMemory("<?xml version=\"1.0\"" + + " encoding=\"UTF-8\"?>" + + "<Book/>").build()); + d2 = Convert.toDocument(Input.fromMemory("<?xml version=\"1.0\"" + + " encoding=\"UTF-16\"?>" + + "<Book/>").build()); + assertEquals(ComparisonResult.CRITICAL, d.compareDocuments(d1, d2)); + assertEquals(1, ex.invoked); + } + + private static class DocType extends NullNode implements DocumentType { + private final String name, publicId, systemId; + private DocType(String name, String publicId, String systemId) { + this.name = name; + this.publicId = publicId; + this.systemId = systemId; + } + public NamedNodeMap getEntities() { + return null; + } + public String getInternalSubset() { + return null; + } + public String getName() { + return name; + } + public NamedNodeMap getNotations() { + return null; + } + public String getPublicId() { + return publicId; + } + public String getSystemId() { + return systemId; + } + } + + @Test public void compareDocTypes() { + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.DOCTYPE_NAME); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); + DocumentType dt1 = new DocType("name", "pub", "system"); + DocumentType dt2 = new DocType("name2", "pub", "system"); + assertEquals(ComparisonResult.CRITICAL, d.compareDocTypes(dt1, dt2)); + assertEquals(1, ex.invoked); + + d = new DOMDifferenceEngine(); + ex = new DiffExpecter(ComparisonType.DOCTYPE_PUBLIC_ID); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); + dt2 = new DocType("name", "pub2", "system"); + assertEquals(ComparisonResult.CRITICAL, d.compareDocTypes(dt1, dt2)); + assertEquals(1, ex.invoked); + + d = new DOMDifferenceEngine(); + ex = new DiffExpecter(ComparisonType.DOCTYPE_SYSTEM_ID); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(new DifferenceEvaluator() { + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult outcome) { + if (comparison.getType() + == ComparisonType.DOCTYPE_SYSTEM_ID) { + assertEquals(ComparisonResult.DIFFERENT, outcome); + return ComparisonResult.CRITICAL; + } + assertEquals(ComparisonResult.EQUAL, outcome); + return ComparisonResult.EQUAL; + } + }); + dt2 = new DocType("name", "pub", "system2"); + assertEquals(ComparisonResult.CRITICAL, d.compareDocTypes(dt1, dt2)); + assertEquals(1, ex.invoked); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-07-06 15:00:43
|
Revision: 411 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=411&view=rev Author: bodewig Date: 2010-07-06 15:00:37 +0000 (Tue, 06 Jul 2010) Log Message: ----------- use the more generic nodeSpecificTests method Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-07-06 10:43:39 UTC (rev 410) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-07-06 15:00:37 UTC (rev 411) @@ -103,6 +103,12 @@ (ProcessingInstruction) test); } break; + case Node.DOCUMENT_TYPE_NODE: + if (test instanceof DocumentType) { + return compareDocTypes((DocumentType) control, + (DocumentType) test); + } + break; } return ComparisonResult.EQUAL; } @@ -117,8 +123,8 @@ test, null, test.getData())); } - ComparisonResult compareDocuments(Document control, - Document test) { + private ComparisonResult compareDocuments(Document control, + Document test) { DocumentType controlDt = control.getDoctype(); DocumentType testDt = test.getDoctype(); ]]></literal> @@ -129,7 +135,7 @@ <literal><![CDATA[ if (controlDt != null && testDt != null) { ]]></literal> - <compareMethodExpr method="compareDocTypes" + <compareMethodExpr method="nodeTypeSpecificComparison" controlExpr="controlDt" testExpr="testDt"/> <literal><![CDATA[ @@ -143,8 +149,8 @@ test, null, test.getXmlEncoding())); } - ComparisonResult compareDocTypes(DocumentType control, - DocumentType test) { + private ComparisonResult compareDocTypes(DocumentType control, + DocumentType test) { ]]></literal> <lastResultDef/> <compare type="DOCTYPE_NAME" property="getName()"/> Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-07-06 10:43:39 UTC (rev 410) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-07-06 15:00:37 UTC (rev 411) @@ -27,6 +27,7 @@ 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; import static org.junit.Assert.*; @@ -247,7 +248,8 @@ + "\">" + "<Book/>") .build()); - assertEquals(ComparisonResult.CRITICAL, d.compareDocuments(d1, d2)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(d1, d2)); assertEquals(1, ex.invoked); d = new DOMDifferenceEngine(); @@ -261,7 +263,8 @@ d2 = Convert.toDocument(Input.fromMemory("<?xml version=\"1.1\"" + " encoding=\"UTF-8\"?>" + "<Book/>").build()); - assertEquals(ComparisonResult.CRITICAL, d.compareDocuments(d1, d2)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(d1, d2)); assertEquals(1, ex.invoked); d = new DOMDifferenceEngine(); @@ -275,7 +278,8 @@ d2 = Convert.toDocument(Input.fromMemory("<?xml version=\"1.0\"" + " standalone=\"no\"?>" + "<Book/>").build()); - assertEquals(ComparisonResult.CRITICAL, d.compareDocuments(d1, d2)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(d1, d2)); assertEquals(1, ex.invoked); d = new DOMDifferenceEngine(); @@ -300,7 +304,8 @@ d2 = Convert.toDocument(Input.fromMemory("<?xml version=\"1.0\"" + " encoding=\"UTF-16\"?>" + "<Book/>").build()); - assertEquals(ComparisonResult.CRITICAL, d.compareDocuments(d1, d2)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(d1, d2)); assertEquals(1, ex.invoked); } @@ -311,6 +316,9 @@ this.publicId = publicId; this.systemId = systemId; } + @Override public short getNodeType() { + return Node.DOCUMENT_TYPE_NODE; + } public NamedNodeMap getEntities() { return null; } @@ -338,7 +346,8 @@ d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); DocumentType dt1 = new DocType("name", "pub", "system"); DocumentType dt2 = new DocType("name2", "pub", "system"); - assertEquals(ComparisonResult.CRITICAL, d.compareDocTypes(dt1, dt2)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(dt1, dt2)); assertEquals(1, ex.invoked); d = new DOMDifferenceEngine(); @@ -346,7 +355,8 @@ d.addDifferenceListener(ex); d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); dt2 = new DocType("name", "pub2", "system"); - assertEquals(ComparisonResult.CRITICAL, d.compareDocTypes(dt1, dt2)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(dt1, dt2)); assertEquals(1, ex.invoked); d = new DOMDifferenceEngine(); @@ -365,7 +375,8 @@ } }); dt2 = new DocType("name", "pub", "system2"); - assertEquals(ComparisonResult.CRITICAL, d.compareDocTypes(dt1, dt2)); + assertEquals(ComparisonResult.CRITICAL, + d.nodeTypeSpecificComparison(dt1, dt2)); assertEquals(1, ex.invoked); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-07-06 15:01:34
|
Revision: 412 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=412&view=rev Author: bodewig Date: 2010-07-06 15:01:27 +0000 (Tue, 06 Jul 2010) Log Message: ----------- port DocumentType comparisons and parts of Document comparisons Modified Paths: -------------- trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs trunk/xmlunit/src/main/net-core/util/Convert.cs trunk/xmlunit/src/tests/net-core/TestResources.cs trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs Modified: trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs 2010-07-06 15:00:37 UTC (rev 411) +++ trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs 2010-07-06 15:01:27 UTC (rev 412) @@ -19,6 +19,20 @@ /// </summary> public enum ComparisonType { /// <summary> + /// Do both documents specify the same version in their XML declaration? + /// </summary> + XML_VERSION, + /// <summary> + /// Do both documents specify the same standalone declaration + /// in their XML declaration? + /// </summary> + XML_STANDALONE, + /// <summary> + /// Do both documents specify the same encoding in their XML + /// declaration? + /// </summary> + XML_ENCODING, + /// <summary> /// Do both documents have a DOCTYPE (or neither of each)? /// </summary> HAS_DOCTYPE_DECLARATION, Modified: trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-07-06 15:00:37 UTC (rev 411) +++ trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-07-06 15:01:27 UTC (rev 412) @@ -78,12 +78,10 @@ } break; case XmlNodeType.Document: -#if false - if (test instanceof Document) { - return compareDocuments((Document) control, - (Document) test); + if (test is XmlDocument) { + return CompareDocuments((XmlDocument) control, + (XmlDocument) test); } -#endif break; case XmlNodeType.Element: #if false @@ -100,6 +98,12 @@ (XmlProcessingInstruction) test); } break; + case XmlNodeType.DocumentType: + if (test is XmlDocumentType) { + return CompareDocTypes((XmlDocumentType) control, + (XmlDocumentType) test); + } + break; } return ComparisonResult.EQUAL; } @@ -114,6 +118,48 @@ test, null, test.Data)); } + private ComparisonResult CompareDocuments(XmlDocument control, + XmlDocument test) { + XmlDocumentType controlDt = control.DocumentType; + XmlDocumentType testDt = test.DocumentType; +]]></literal> + <lastResultDef/> + <compareExpr type="HAS_DOCTYPE_DECLARATION" + controlExpr="controlDt != null" + testExpr="testDt != null"/> + <literal><![CDATA[ + if (controlDt != null && testDt != null) { +]]></literal> + <compareMethodExpr method="NodeTypeSpecificComparison" + controlExpr="controlDt" + testExpr="testDt"/> + <literal><![CDATA[ + } +]]></literal> +<!-- + <compare type="XML_VERSION" property="getXmlVersion()"/> + <compare type="XML_STANDALONE" property="getXmlStandalone()"/> + <literal><![CDATA[ + return Compare(new Comparison(ComparisonType.XML_ENCODING, + control, null, control.getXmlEncoding(), + test, null, test.getXmlEncoding())); +--> + <literal><![CDATA[ + return lastResult; + } + + private ComparisonResult CompareDocTypes(XmlDocumentType control, + XmlDocumentType test) { +]]></literal> + <lastResultDef/> + <compare type="DOCTYPE_NAME" property="Name"/> + <compare type="DOCTYPE_PUBLIC_ID" property="PublicId"/> + <literal><![CDATA[ + return Compare(new Comparison(ComparisonType.DOCTYPE_SYSTEM_ID, + control, null, control.SystemId, + test, null, test.SystemId)); + } + private ComparisonResult CompareProcessingInstructions(XmlProcessingInstruction control, XmlProcessingInstruction test) { Modified: trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs 2010-07-06 15:00:37 UTC (rev 411) +++ trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs 2010-07-06 15:01:27 UTC (rev 412) @@ -43,6 +43,7 @@ outcome = ComparisonResult.SIMILAR; } break; + case ComparisonType.XML_ENCODING: case ComparisonType.HAS_DOCTYPE_DECLARATION: case ComparisonType.DOCTYPE_SYSTEM_ID: case ComparisonType.SCHEMA_LOCATION: Modified: trunk/xmlunit/src/main/net-core/util/Convert.cs =================================================================== --- trunk/xmlunit/src/main/net-core/util/Convert.cs 2010-07-06 15:00:37 UTC (rev 411) +++ trunk/xmlunit/src/main/net-core/util/Convert.cs 2010-07-06 15:01:27 UTC (rev 412) @@ -27,6 +27,13 @@ /// Creates a DOM Document from an ISource. /// </summary> public static XmlDocument ToDocument(ISource s) { + return ToDocument(s, true); + } + + /// <summary> + /// Creates a DOM Document from an ISource. + /// </summary> + public static XmlDocument ToDocument(ISource s, bool prohibitDTD) { DOMSource ds = s as DOMSource; if (ds != null) { XmlDocument doc = ds.Node as XmlDocument; @@ -35,7 +42,9 @@ } } XmlDocument d = new XmlDocument(); - d.Load(s.Reader); + XmlReaderSettings sett = new XmlReaderSettings(); + sett.ProhibitDtd = prohibitDTD; + d.Load(XmlReader.Create(s.Reader, sett)); return d; } Modified: trunk/xmlunit/src/tests/net-core/TestResources.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/TestResources.cs 2010-07-06 15:00:37 UTC (rev 411) +++ trunk/xmlunit/src/tests/net-core/TestResources.cs 2010-07-06 15:01:27 UTC (rev 412) @@ -20,6 +20,9 @@ public const string ANIMAL_XSL = "../../../src/tests/resources/animal.xsl"; public const string DOG_FILE = "../../../src/tests/resources/testAnimal.xml"; + public const string BOOK_DTD = "../../../src/tests/resources/Book.dtd"; + public const string TEST_DTD = "../../../src/tests/resources/test.dtd"; + private TestResources() { } } } Modified: trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-07-06 15:00:37 UTC (rev 411) +++ trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-07-06 15:01:27 UTC (rev 412) @@ -14,6 +14,7 @@ using System; using System.Xml; using NUnit.Framework; +using net.sf.xmlunit.builder; namespace net.sf.xmlunit.diff { @@ -265,5 +266,204 @@ Assert.AreEqual(1, invocations); } + [Test] + public void CompareDocuments() { + DOMDifferenceEngine d = new DOMDifferenceEngine(); + int invocations = 0; + d.DifferenceListener += delegate(Comparison comp, + ComparisonResult r) { + Assert.AreEqual(0, invocations); + invocations++; + Assert.AreEqual(ComparisonType.HAS_DOCTYPE_DECLARATION, + comp.Type); + Assert.AreEqual(ComparisonResult.CRITICAL, r); + }; + d.DifferenceEvaluator = delegate(Comparison comparison, + ComparisonResult outcome) { + if (comparison.Type == ComparisonType.HAS_DOCTYPE_DECLARATION) { + Assert.AreEqual(ComparisonResult.DIFFERENT, outcome); + return ComparisonResult.CRITICAL; + } + Assert.AreEqual(ComparisonResult.EQUAL, outcome); + return ComparisonResult.EQUAL; + }; + + XmlDocument d1, d2; + +#if false // ProhibitDtd needs to be handled at a lower level + d1 = net.sf.xmlunit.util.Convert + .ToDocument(Input.FromMemory("<Book/>").Build()); + d2 = net.sf.xmlunit.util.Convert + .ToDocument(Input.FromMemory("<!DOCTYPE Book PUBLIC " + + "\"XMLUNIT/TEST/PUB\" " + + "\"" + TestResources.BOOK_DTD + + "\">" + + "<Book/>") + .Build()); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(d1, d2)); + Assert.AreEqual(1, invocations); +#endif + +#if false // need a way to figure out the XML_* differences + + // .NET doesn't like XML 1.1 anyway + invocations = 0; + d = new DOMDifferenceEngine(); + d.DifferenceListener += delegate(Comparison comp, + ComparisonResult r) { + Assert.AreEqual(0, invocations); + invocations++; + Assert.AreEqual(ComparisonType.XML_VERSION, + comp.Type); + Assert.AreEqual(ComparisonResult.CRITICAL, r); + }; + d.DifferenceEvaluator = + DifferenceEvaluators.DefaultStopWhenDifferent; + + d1 = net.sf.xmlunit.util.Convert + .ToDocument(Input.FromMemory("<?xml version=\"1.0\"" + + " encoding=\"UTF-8\"?>" + + "<Book/>").Build()); + d2 = net.sf.xmlunit.util.Convert + .ToDocument(Input.FromMemory("<?xml version=\"1.1\"" + + " encoding=\"UTF-8\"?>" + + "<Book/>").Build()); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(d1, d2)); + Assert.AreEqual(1, invocations); +#endif + +#if false // need a way to figure out the XML_* differences + invocations = 0; + d = new DOMDifferenceEngine(); + d.DifferenceListener += delegate(Comparison comp, + ComparisonResult r) { + Assert.AreEqual(0, invocations); + invocations++; + Assert.AreEqual(ComparisonType.XML_STANDALONE, + comp.Type); + Assert.AreEqual(ComparisonResult.CRITICAL, r); + }; + d.DifferenceEvaluator = + DifferenceEvaluators.DefaultStopWhenDifferent; + + d1 = net.sf.xmlunit.util.Convert + .ToDocument(Input.FromMemory("<?xml version=\"1.0\"" + + " standalone=\"yes\"?>" + + "<Book/>").Build()); + d2 = net.sf.xmlunit.util.Convert + .ToDocument(Input.FromMemory("<?xml version=\"1.0\"" + + " standalone=\"no\"?>" + + "<Book/>").Build()); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(d1, d2)); + Assert.AreEqual(1, invocations); +#endif + +#if false // need a way to figure out the XML_* differences + invocations = 0; + d = new DOMDifferenceEngine(); + d.DifferenceListener += delegate(Comparison comp, + ComparisonResult r) { + Assert.AreEqual(0, invocations); + invocations++; + Assert.AreEqual(ComparisonType.XML_ENCODING, + comp.Type); + Assert.AreEqual(ComparisonResult.CRITICAL, r); + }; + d.DifferenceEvaluator = delegate(Comparison comparison, + ComparisonResult outcome) { + if (comparison.Type == ComparisonType.XML_ENCODING) { + Assert.AreEqual(ComparisonResult.DIFFERENT, outcome); + return ComparisonResult.CRITICAL; + } + Assert.AreEqual(ComparisonResult.EQUAL, outcome); + return ComparisonResult.EQUAL; + }; + + d1 = net.sf.xmlunit.util.Convert + .ToDocument(Input.FromMemory("<?xml version=\"1.0\"" + + " encoding=\"UTF-8\"?>" + + "<Book/>").Build()); + d2 = net.sf.xmlunit.util.Convert + .ToDocument(Input.FromMemory("<?xml version=\"1.0\"" + + " encoding=\"UTF-16\"?>" + + "<Book/>").Build()); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(d1, d2)); + Assert.AreEqual(1, invocations); +#endif + } + + [Test] + public void CompareDocTypes() { + int invocations = 0; + DOMDifferenceEngine d = new DOMDifferenceEngine(); + d.DifferenceListener += delegate(Comparison comp, + ComparisonResult r) { + Assert.AreEqual(0, invocations); + invocations++; + Assert.AreEqual(ComparisonType.DOCTYPE_NAME, + comp.Type); + Assert.AreEqual(ComparisonResult.CRITICAL, r); + }; + d.DifferenceEvaluator = + DifferenceEvaluators.DefaultStopWhenDifferent; + + XmlDocumentType dt1 = doc.CreateDocumentType("name", "pub", + TestResources.BOOK_DTD, + null); + XmlDocumentType dt2 = doc.CreateDocumentType("name2", "pub", + TestResources.BOOK_DTD, + null); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(dt1, dt2)); + Assert.AreEqual(1, invocations); + + invocations = 0; + d = new DOMDifferenceEngine(); + d.DifferenceListener += delegate(Comparison comp, + ComparisonResult r) { + Assert.AreEqual(0, invocations); + invocations++; + Assert.AreEqual(ComparisonType.DOCTYPE_PUBLIC_ID, + comp.Type); + Assert.AreEqual(ComparisonResult.CRITICAL, r); + }; + d.DifferenceEvaluator = + DifferenceEvaluators.DefaultStopWhenDifferent; + dt2 = doc.CreateDocumentType("name", "pub2", + TestResources.BOOK_DTD, null); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(dt1, dt2)); + Assert.AreEqual(1, invocations); + + invocations = 0; + d = new DOMDifferenceEngine(); + d.DifferenceListener += delegate(Comparison comp, + ComparisonResult r) { + Assert.AreEqual(0, invocations); + invocations++; + Assert.AreEqual(ComparisonType.DOCTYPE_SYSTEM_ID, + comp.Type); + Assert.AreEqual(ComparisonResult.CRITICAL, r); + }; + d.DifferenceEvaluator = delegate(Comparison comparison, + ComparisonResult outcome) { + if (comparison.Type == ComparisonType.DOCTYPE_SYSTEM_ID) { + Assert.AreEqual(ComparisonResult.DIFFERENT, outcome); + return ComparisonResult.CRITICAL; + } + Assert.AreEqual(ComparisonResult.EQUAL, outcome); + return ComparisonResult.EQUAL; + }; + dt2 = doc.CreateDocumentType("name", "pub", + TestResources.TEST_DTD, null); + Assert.AreEqual(ComparisonResult.CRITICAL, + d.NodeTypeSpecificComparison(dt1, dt2)); + Assert.AreEqual(1, invocations); + } + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-07-12 15:18:21
|
Revision: 413 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=413&view=rev Author: bodewig Date: 2010-07-12 15:18:14 +0000 (Mon, 12 Jul 2010) Log Message: ----------- implement element and attribute level comparisions, move tests to the compareNodes level, make .NET tests even closer to the Java ones Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-07-06 15:01:27 UTC (rev 412) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-07-12 15:18:14 UTC (rev 413) @@ -19,10 +19,12 @@ <import reference="javax.xml.transform.Source"/> <import reference="net.sf.xmlunit.util.Convert"/> + <import reference="org.w3c.dom.Attr"/> <import reference="org.w3c.dom.CharacterData"/> <import reference="org.w3c.dom.Document"/> <import reference="org.w3c.dom.DocumentType"/> <import reference="org.w3c.dom.Element"/> + <import reference="org.w3c.dom.NamedNodeMap"/> <import reference="org.w3c.dom.Node"/> <import reference="org.w3c.dom.NodeList"/> <import reference="org.w3c.dom.ProcessingInstruction"/> @@ -74,7 +76,8 @@ * * <p>package private to support tests.</p> */ - ComparisonResult nodeTypeSpecificComparison(Node control, Node test) { + private ComparisonResult nodeTypeSpecificComparison(Node control, + Node test) { switch (control.getNodeType()) { case Node.CDATA_SECTION_NODE: case Node.COMMENT_NODE: @@ -109,6 +112,12 @@ (DocumentType) test); } break; + case Node.ATTRIBUTE_NODE: + if (test instanceof Attr) { + return compareAttributes((Attr) control, + (Attr) test); + } + break; } return ComparisonResult.EQUAL; } @@ -135,7 +144,7 @@ <literal><![CDATA[ if (controlDt != null && testDt != null) { ]]></literal> - <compareMethodExpr method="nodeTypeSpecificComparison" + <compareMethodExpr method="compareNodes" controlExpr="controlDt" testExpr="testDt"/> <literal><![CDATA[ @@ -161,12 +170,61 @@ test, null, test.getSystemId())); } - ComparisonResult compareElements(Element control, - Element test) { - return ComparisonResult.EQUAL; + private ComparisonResult compareElements(Element control, + Element test) { +]]></literal> + <lastResultDef/> + <compare type="ELEMENT_TAG_NAME" property="getTagName()"/> + <literal><![CDATA[ + NamedNodeMap controlAttributes = control.getAttributes(); + NamedNodeMap testAttributes = test.getAttributes(); + final int controlAttrLen = controlAttributes.getLength(); + final int testAttrLen = testAttributes.getLength(); +]]></literal> + <compareExpr type="ELEMENT_NUM_ATTRIBUTES" + controlExpr="controlAttrLen" + testExpr="testAttrLen"/> + <literal><![CDATA[ + for (int i = 0; i < controlAttrLen; i++) { + final Attr controlAttr = (Attr) controlAttributes.item(i); + final Attr testAttr = findMatchingAttr(testAttributes, controlAttr); +]]></literal> + <compareExpr type="ATTR_NAME_LOOKUP" + controlExpr="Boolean.TRUE" + testExpr="Boolean.valueOf(testAttr != null)"/> + <literal><![CDATA[ + } +]]></literal> + <literal><![CDATA[ + for (int i = 0; i < testAttrLen; i++) { + final Attr testAttr = (Attr) testAttributes.item(i); + final Attr controlAttr = findMatchingAttr(controlAttributes, + testAttr); +]]></literal> + <compareExpr type="ATTR_NAME_LOOKUP" + controlExpr="Boolean.valueOf(controlAttr != null)" + testExpr="Boolean.TRUE"/> + <literal><![CDATA[ + } +]]></literal> + <literal><![CDATA[ + for (int i = 0; i < controlAttrLen; i++) { + final Attr controlAttr = (Attr) controlAttributes.item(i); + final Attr testAttr = findMatchingAttr(testAttributes, controlAttr); + if (testAttr != null) { +]]></literal> + <compareMethodExpr method="compareNodes" + controlExpr="controlAttr" + testExpr="testAttr"/> + <literal><![CDATA[ + } + } +]]></literal> + <literal><![CDATA[ + return lastResult; } - ComparisonResult + private ComparisonResult compareProcessingInstructions(ProcessingInstruction control, ProcessingInstruction test) { ]]></literal> @@ -178,8 +236,28 @@ test, null, test.getData())); } - ComparisonResult compareNodeLists(NodeList control, NodeList test) { + private ComparisonResult compareNodeLists(NodeList control, NodeList test) { return ComparisonResult.EQUAL; } + + private ComparisonResult compareAttributes(Attr control, Attr test) { ]]></literal> + <lastResultDef/> + <compare type="ATTR_VALUE_EXPLICITLY_SPECIFIED" property="getSpecified()"/> + <literal><![CDATA[ + return compare(new Comparison(ComparisonType.ATTR_VALUE, + control, null, control.getValue(), + test, null, test.getValue())); + } + + private static Attr findMatchingAttr(NamedNodeMap map, Attr attrToMatch) { + if (attrToMatch.getNamespaceURI() == null) { + return (Attr) map.getNamedItem(attrToMatch.getName()); + } else { + return (Attr) map.getNamedItemNS(attrToMatch.getNamespaceURI(), + attrToMatch.getLocalName()); + } + } + +]]></literal> </class> \ No newline at end of file Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java 2010-07-06 15:01:27 UTC (rev 412) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java 2010-07-12 15:18:14 UTC (rev 413) @@ -25,6 +25,17 @@ private static final Short TEXT = Node.CDATA_SECTION_NODE; /** + * Difference evaluator that just echos the result passed in. + */ + public static final DifferenceEvaluator Accept = + new DifferenceEvaluator() { + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult outcome) { + return outcome; + } + }; + + /** * The "standard" difference evaluator which decides which * differences make two XML documents really different and which * still leave them similar. Modified: trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-07-06 15:01:27 UTC (rev 412) +++ trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-07-12 15:18:14 UTC (rev 413) @@ -66,8 +66,8 @@ /// Dispatches to the node type specific comparison if one is /// defined for the given combination of nodes. /// </summary> - internal ComparisonResult NodeTypeSpecificComparison(XmlNode control, - XmlNode test) { + private ComparisonResult NodeTypeSpecificComparison(XmlNode control, + XmlNode test) { switch (control.NodeType) { case XmlNodeType.CDATA: case XmlNodeType.Comment: @@ -84,12 +84,10 @@ } break; case XmlNodeType.Element: -#if false - if (test instanceof Element) { - return compareElements((Element) control, - (Element) test); + if (test is XmlElement) { + return CompareElements((XmlElement) control, + (XmlElement) test); } -#endif break; case XmlNodeType.ProcessingInstruction: if (test is XmlProcessingInstruction) { @@ -104,6 +102,12 @@ (XmlDocumentType) test); } break; + case XmlNodeType.Attribute: + if (test is XmlAttribute) { + return CompareAttributes((XmlAttribute) control, + (XmlAttribute) test); + } + break; } return ComparisonResult.EQUAL; } @@ -130,7 +134,7 @@ <literal><![CDATA[ if (controlDt != null && testDt != null) { ]]></literal> - <compareMethodExpr method="NodeTypeSpecificComparison" + <compareMethodExpr method="CompareNodes" controlExpr="controlDt" testExpr="testDt"/> <literal><![CDATA[ @@ -160,6 +164,62 @@ test, null, test.SystemId)); } + private ComparisonResult CompareElements(XmlElement control, + XmlElement test) { +]]></literal> + <lastResultDef/> + <compare type="ELEMENT_TAG_NAME" property="Name"/> + <literal><![CDATA[ + XmlAttributeCollection controlAttributes = control.Attributes; + XmlAttributeCollection testAttributes = test.Attributes; + int controlAttrLen = controlAttributes.Count; + int testAttrLen = testAttributes.Count; +]]></literal> + <compareExpr type="ELEMENT_NUM_ATTRIBUTES" + controlExpr="controlAttrLen" + testExpr="testAttrLen"/> + <literal><![CDATA[ + for (int i = 0; i < controlAttrLen; i++) { + XmlAttribute controlAttr = controlAttributes[i]; + XmlAttribute testAttr = FindMatchingAttr(testAttributes, + controlAttr); +]]></literal> + <compareExpr type="ATTR_NAME_LOOKUP" + controlExpr="true" + testExpr="testAttr != null"/> + <literal><![CDATA[ + } +]]></literal> + <literal><![CDATA[ + for (int i = 0; i < testAttrLen; i++) { + XmlAttribute testAttr = testAttributes[i]; + XmlAttribute controlAttr = FindMatchingAttr(controlAttributes, + testAttr); +]]></literal> + <compareExpr type="ATTR_NAME_LOOKUP" + controlExpr="controlAttr != null" + testExpr="true"/> + <literal><![CDATA[ + } +]]></literal> + <literal><![CDATA[ + for (int i = 0; i < controlAttrLen; i++) { + XmlAttribute controlAttr = controlAttributes[i]; + XmlAttribute testAttr = FindMatchingAttr(testAttributes, + controlAttr); + if (testAttr != null) { +]]></literal> + <compareMethodExpr method="CompareNodes" + controlExpr="controlAttr" + testExpr="testAttr"/> + <literal><![CDATA[ + } + } +]]></literal> + <literal><![CDATA[ + return lastResult; + } + private ComparisonResult CompareProcessingInstructions(XmlProcessingInstruction control, XmlProcessingInstruction test) { @@ -172,10 +232,31 @@ test, null, test.Data)); } - ComparisonResult CompareNodeLists(XmlNodeList control, - XmlNodeList test) { + private ComparisonResult CompareNodeLists(XmlNodeList control, + XmlNodeList test) { return ComparisonResult.EQUAL; } + private ComparisonResult CompareAttributes(XmlAttribute control, + XmlAttribute test) { ]]></literal> + <lastResultDef/> + <compare type="ATTR_VALUE_EXPLICITLY_SPECIFIED" property="Specified"/> + <literal><![CDATA[ + return Compare(new Comparison(ComparisonType.ATTR_VALUE, + control, null, control.Value, + test, null, test.Value)); + } + + private static XmlAttribute FindMatchingAttr(XmlAttributeCollection map, + XmlAttribute attrToMatch) { + if (attrToMatch.NamespaceURI == null) { + return map.GetNamedItem(attrToMatch.Name) as XmlAttribute; + } else { + return map.GetNamedItem(attrToMatch.LocalName, + attrToMatch.NamespaceURI) + as XmlAttribute; + } + } +]]></literal> </class> \ No newline at end of file Modified: trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs 2010-07-06 15:01:27 UTC (rev 412) +++ trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs 2010-07-12 15:18:14 UTC (rev 413) @@ -23,6 +23,14 @@ private DifferenceEvaluators() { } /// <summary> + /// Difference evaluator that just echos the result passed in. + /// </summary> + public static ComparisonResult Accept(Comparison comparison, + ComparisonResult outcome) { + return outcome; + } + + /// <summary> /// The "standard" difference evaluator which decides which /// differences make two XML documents really different and which /// still leave them similar. Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-07-06 15:01:27 UTC (rev 412) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-07-12 15:18:14 UTC (rev 413) @@ -21,7 +21,9 @@ import net.sf.xmlunit.util.Convert; import org.junit.Before; import org.junit.Test; +import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; +import org.w3c.dom.CharacterData; import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; @@ -51,7 +53,8 @@ } public void comparisonPerformed(Comparison comparison, ComparisonResult outcome) { - assertTrue(invoked < expectedInvocations); + assertTrue(invoked + " should be less than " + expectedInvocations, + invoked < expectedInvocations); invoked++; assertEquals(type, comparison.getType()); assertEquals(ComparisonResult.CRITICAL, outcome); @@ -143,7 +146,25 @@ DOMDifferenceEngine d = new DOMDifferenceEngine(); DiffExpecter ex = new DiffExpecter(ComparisonType.TEXT_VALUE, 9); d.addDifferenceListener(ex); - d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); + d.setDifferenceEvaluator(new DifferenceEvaluator() { + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult outcome) { + if (comparison.getType() == ComparisonType.NODE_TYPE) { + if (outcome == ComparisonResult.EQUAL + || ( + comparison.getControlNodeDetails() + .getNode() instanceof CharacterData + && + comparison.getTestNodeDetails() + .getNode() instanceof CharacterData + )) { + return ComparisonResult.EQUAL; + } + } + return DifferenceEvaluators.DefaultStopWhenDifferent + .evaluate(comparison, outcome); + } + }); Comment fooComment = doc.createComment("foo"); Comment barComment = doc.createComment("bar"); @@ -153,45 +174,42 @@ CDATASection barCDATASection = doc.createCDATASection("bar"); assertEquals(ComparisonResult.EQUAL, - d.nodeTypeSpecificComparison(fooComment, fooComment)); + d.compareNodes(fooComment, fooComment)); assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(fooComment, barComment)); + d.compareNodes(fooComment, barComment)); assertEquals(ComparisonResult.EQUAL, - d.nodeTypeSpecificComparison(fooText, fooText)); + d.compareNodes(fooText, fooText)); assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(fooText, barText)); + d.compareNodes(fooText, barText)); assertEquals(ComparisonResult.EQUAL, - d.nodeTypeSpecificComparison(fooCDATASection, fooCDATASection)); + d.compareNodes(fooCDATASection, fooCDATASection)); assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(fooCDATASection, barCDATASection)); + d.compareNodes(fooCDATASection, barCDATASection)); assertEquals(ComparisonResult.EQUAL, - d.nodeTypeSpecificComparison(fooComment, fooText)); + d.compareNodes(fooComment, fooText)); assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(fooComment, barText)); + d.compareNodes(fooComment, barText)); assertEquals(ComparisonResult.EQUAL, - d.nodeTypeSpecificComparison(fooComment, fooCDATASection)); + d.compareNodes(fooComment, fooCDATASection)); assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(fooComment, barCDATASection)); + d.compareNodes(fooComment, barCDATASection)); assertEquals(ComparisonResult.EQUAL, - d.nodeTypeSpecificComparison(fooText, fooComment)); + d.compareNodes(fooText, fooComment)); assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(fooText, barComment)); + d.compareNodes(fooText, barComment)); assertEquals(ComparisonResult.EQUAL, - d.nodeTypeSpecificComparison(fooText, fooCDATASection)); + d.compareNodes(fooText, fooCDATASection)); assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(fooText, barCDATASection)); + d.compareNodes(fooText, barCDATASection)); assertEquals(ComparisonResult.EQUAL, - d.nodeTypeSpecificComparison(fooCDATASection, fooText)); + d.compareNodes(fooCDATASection, fooText)); assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(fooCDATASection, barText)); + d.compareNodes(fooCDATASection, barText)); assertEquals(ComparisonResult.EQUAL, - d.nodeTypeSpecificComparison(fooCDATASection, fooComment)); + d.compareNodes(fooCDATASection, fooComment)); assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(fooCDATASection, barComment)); - assertEquals(ComparisonResult.EQUAL, - d.nodeTypeSpecificComparison(fooText, - doc.createElement("bar"))); + d.compareNodes(fooCDATASection, barComment)); assertEquals(9, ex.invoked); } @@ -203,13 +221,8 @@ ProcessingInstruction foo1 = doc.createProcessingInstruction("foo", "1"); ProcessingInstruction bar1 = doc.createProcessingInstruction("bar", "1"); - assertEquals(ComparisonResult.EQUAL, - d.nodeTypeSpecificComparison(foo1, foo1)); - assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(foo1, bar1)); - assertEquals(ComparisonResult.EQUAL, - d.nodeTypeSpecificComparison(foo1, - doc.createElement("bar"))); + assertEquals(ComparisonResult.EQUAL, d.compareNodes(foo1, foo1)); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(foo1, bar1)); assertEquals(1, ex.invoked); d = new DOMDifferenceEngine(); @@ -217,10 +230,8 @@ d.addDifferenceListener(ex); d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); ProcessingInstruction foo2 = doc.createProcessingInstruction("foo", "2"); - assertEquals(ComparisonResult.EQUAL, - d.nodeTypeSpecificComparison(foo1, foo1)); - assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(foo1, foo2)); + assertEquals(ComparisonResult.EQUAL, d.compareNodes(foo1, foo1)); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(foo1, foo2)); assertEquals(1, ex.invoked); } @@ -232,11 +243,18 @@ public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome) { if (comparison.getType() + == ComparisonType.CHILD_NODELIST_LENGTH) { + assertEquals(ComparisonResult.DIFFERENT, outcome); + return ComparisonResult.EQUAL; + } + if (comparison.getType() == ComparisonType.HAS_DOCTYPE_DECLARATION) { assertEquals(ComparisonResult.DIFFERENT, outcome); return ComparisonResult.CRITICAL; } - assertEquals(ComparisonResult.EQUAL, outcome); + assertEquals("Expected EQUAL for " + comparison.getType() + + " comparison.", + ComparisonResult.EQUAL, outcome); return ComparisonResult.EQUAL; } }); @@ -248,8 +266,7 @@ + "\">" + "<Book/>") .build()); - assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(d1, d2)); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(d1, d2)); assertEquals(1, ex.invoked); d = new DOMDifferenceEngine(); @@ -264,7 +281,7 @@ + " encoding=\"UTF-8\"?>" + "<Book/>").build()); assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(d1, d2)); + d.compareNodes(d1, d2)); assertEquals(1, ex.invoked); d = new DOMDifferenceEngine(); @@ -279,7 +296,7 @@ + " standalone=\"no\"?>" + "<Book/>").build()); assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(d1, d2)); + d.compareNodes(d1, d2)); assertEquals(1, ex.invoked); d = new DOMDifferenceEngine(); @@ -305,7 +322,7 @@ + " encoding=\"UTF-16\"?>" + "<Book/>").build()); assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(d1, d2)); + d.compareNodes(d1, d2)); assertEquals(1, ex.invoked); } @@ -346,8 +363,7 @@ d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); DocumentType dt1 = new DocType("name", "pub", "system"); DocumentType dt2 = new DocType("name2", "pub", "system"); - assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(dt1, dt2)); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(dt1, dt2)); assertEquals(1, ex.invoked); d = new DOMDifferenceEngine(); @@ -355,8 +371,7 @@ d.addDifferenceListener(ex); d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); dt2 = new DocType("name", "pub2", "system"); - assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(dt1, dt2)); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(dt1, dt2)); assertEquals(1, ex.invoked); d = new DOMDifferenceEngine(); @@ -375,8 +390,81 @@ } }); dt2 = new DocType("name", "pub", "system2"); - assertEquals(ComparisonResult.CRITICAL, - d.nodeTypeSpecificComparison(dt1, dt2)); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(dt1, dt2)); assertEquals(1, ex.invoked); } + + @Test public void compareElements() { + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.ELEMENT_TAG_NAME); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); + Element e1 = doc.createElement("foo"); + Element e2 = doc.createElement("foo"); + Element e3 = doc.createElement("bar"); + assertEquals(ComparisonResult.EQUAL, d.compareNodes(e1, e2)); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(e1, e3)); + assertEquals(1, ex.invoked); + + d = new DOMDifferenceEngine(); + ex = new DiffExpecter(ComparisonType.ELEMENT_NUM_ATTRIBUTES); + e1.setAttribute("attr1", "value1"); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(e1, e2)); + assertEquals(1, ex.invoked); + + d = new DOMDifferenceEngine(); + ex = new DiffExpecter(ComparisonType.ATTR_NAME_LOOKUP); + e2.setAttributeNS("urn:xmlunit:test", "attr1", "value1"); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(e1, e2)); + assertEquals(1, ex.invoked); + + + d = new DOMDifferenceEngine(); + d.addDifferenceListener(new ComparisonListener() { + public void comparisonPerformed(Comparison comparison, + ComparisonResult outcome) { + fail("unexpected Comparison of type " + comparison.getType() + + " with outcome " + outcome + " and values '" + + comparison.getControlNodeDetails().getValue() + + "' and '" + + comparison.getTestNodeDetails().getValue() + "'"); + } + }); + e1.setAttributeNS("urn:xmlunit:test", "attr1", "value1"); + e2.setAttributeNS(null, "attr1", "value1"); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); + assertEquals(ComparisonResult.EQUAL, d.compareNodes(e1, e2)); + } + + @Test public void compareAttributes() { + Attr a1 = doc.createAttribute("foo"); + Attr a2 = doc.createAttribute("foo"); + + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.ATTR_VALUE_EXPLICITLY_SPECIFIED); + /* Can't reset "explicitly set" state for Documents created via API + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(DifferenceEvaluators.Accept); + a2.setValue(""); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(a1, a2)); + assertEquals(1, ex.invoked); + + d = new DOMDifferenceEngine(); + */ + ex = new DiffExpecter(ComparisonType.ATTR_VALUE); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); + Attr a3 = doc.createAttribute("foo"); + a1.setValue("foo"); + a2.setValue("foo"); + a3.setValue("bar"); + assertEquals(ComparisonResult.EQUAL, d.compareNodes(a1, a2)); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(a1, a3)); + assertEquals(1, ex.invoked); + } } Modified: trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-07-06 15:01:27 UTC (rev 412) +++ trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-07-12 15:18:14 UTC (rev 413) @@ -27,6 +27,24 @@ } } + private class DiffExpecter { + internal int invoked = 0; + private readonly int expectedInvocations; + private readonly ComparisonType type; + internal DiffExpecter(ComparisonType type) : this(type, 1) { } + internal DiffExpecter(ComparisonType type, int expected) { + this.type = type; + this.expectedInvocations = expected; + } + public void ComparisonPerformed(Comparison comparison, + ComparisonResult outcome) { + Assert.Greater(expectedInvocations, invoked); + invoked++; + Assert.AreEqual(type, comparison.Type); + Assert.AreEqual(ComparisonResult.CRITICAL, outcome); + } + } + private XmlDocument doc; [SetUp] @@ -37,20 +55,14 @@ [Test] public void CompareNodesOfDifferentType() { DOMDifferenceEngine d = new DOMDifferenceEngine(); - int invocations = 0; - d.DifferenceListener += delegate(Comparison comp, - ComparisonResult r) { - Assert.AreEqual(0, invocations); - invocations++; - Assert.AreEqual(ComparisonType.NODE_TYPE, comp.Type); - Assert.AreEqual(ComparisonResult.CRITICAL, r); - }; + DiffExpecter ex = new DiffExpecter(ComparisonType.NODE_TYPE); + d.DifferenceListener += ex.ComparisonPerformed; d.DifferenceEvaluator = DifferenceEvaluators.DefaultStopWhenDifferent; Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(doc.CreateElement("x"), doc.CreateComment("x"))); - Assert.AreEqual(1, invocations); + Assert.AreEqual(1, ex.invoked); } [Test] @@ -70,33 +82,21 @@ [Test] public void CompareNodesDifferentNS() { DOMDifferenceEngine d = new DOMDifferenceEngine(); - int invocations = 0; - d.DifferenceListener += delegate(Comparison comp, - ComparisonResult r) { - Assert.AreEqual(0, invocations); - invocations++; - Assert.AreEqual(ComparisonType.NAMESPACE_URI, comp.Type); - Assert.AreEqual(ComparisonResult.CRITICAL, r); - }; + DiffExpecter ex = new DiffExpecter(ComparisonType.NAMESPACE_URI); + d.DifferenceListener += ex.ComparisonPerformed; d.DifferenceEvaluator = DifferenceEvaluators.DefaultStopWhenDifferent; Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(doc.CreateElement("y", "x"), doc.CreateElement("y", "z"))); - Assert.AreEqual(1, invocations); + Assert.AreEqual(1, ex.invoked); } [Test] public void CompareNodesDifferentPrefix() { DOMDifferenceEngine d = new DOMDifferenceEngine(); - int invocations = 0; - d.DifferenceListener += delegate(Comparison comp, - ComparisonResult r) { - Assert.AreEqual(0, invocations); - invocations++; - Assert.AreEqual(ComparisonType.NAMESPACE_PREFIX, comp.Type); - Assert.AreEqual(ComparisonResult.CRITICAL, r); - }; + DiffExpecter ex = new DiffExpecter(ComparisonType.NAMESPACE_PREFIX); + d.DifferenceListener += ex.ComparisonPerformed; d.DifferenceEvaluator = delegate(Comparison comparison, ComparisonResult outcome) { if (comparison.Type == ComparisonType.NAMESPACE_PREFIX) { @@ -109,21 +109,15 @@ Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(doc.CreateElement("x:y", "x"), doc.CreateElement("z:y", "x"))); - Assert.AreEqual(1, invocations); + Assert.AreEqual(1, ex.invoked); } [Test] public void CompareNodesDifferentNumberOfChildren() { DOMDifferenceEngine d = new DOMDifferenceEngine(); - int invocations = 0; - d.DifferenceListener += delegate(Comparison comp, - ComparisonResult r) { - Assert.Greater(2, invocations); - invocations++; - Assert.AreEqual(ComparisonType.CHILD_NODELIST_LENGTH, - comp.Type); - Assert.AreEqual(ComparisonResult.CRITICAL, r); - }; + DiffExpecter ex = + new DiffExpecter(ComparisonType.CHILD_NODELIST_LENGTH, 2); + d.DifferenceListener += ex.ComparisonPerformed; d.DifferenceEvaluator = DifferenceEvaluators.DefaultStopWhenDifferent; XmlElement e1 = doc.CreateElement("x"); @@ -131,28 +125,35 @@ Assert.AreEqual(ComparisonResult.EQUAL, d.CompareNodes(e1, e2)); e1.AppendChild(doc.CreateElement("x")); Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(e1, e2)); - Assert.AreEqual(1, invocations); + Assert.AreEqual(1, ex.invoked); e2.AppendChild(doc.CreateElement("x")); Assert.AreEqual(ComparisonResult.EQUAL, d.CompareNodes(e1, e2)); e2.AppendChild(doc.CreateElement("x")); Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(e1, e2)); - Assert.AreEqual(2, invocations); + Assert.AreEqual(2, ex.invoked); } [Test] public void CompareCharacterData() { DOMDifferenceEngine d = new DOMDifferenceEngine(); - int invocations = 0; - d.DifferenceListener += delegate(Comparison comp, - ComparisonResult r) { - Assert.Greater(9, invocations); - invocations++; - Assert.AreEqual(ComparisonType.TEXT_VALUE, - comp.Type); - Assert.AreEqual(ComparisonResult.CRITICAL, r); + DiffExpecter ex = new DiffExpecter(ComparisonType.TEXT_VALUE, 9); + d.DifferenceListener += ex.ComparisonPerformed; + d.DifferenceEvaluator = delegate(Comparison comparison, + ComparisonResult outcome) { + if (comparison.Type == ComparisonType.NODE_TYPE) { + if (outcome == ComparisonResult.EQUAL + || ( + comparison.ControlNodeDetails.Node + is XmlCharacterData + && + comparison.TestNodeDetails.Node is XmlCharacterData + )) { + return ComparisonResult.EQUAL; + } + } + return DifferenceEvaluators.DefaultStopWhenDifferent(comparison, + outcome); }; - d.DifferenceEvaluator = - DifferenceEvaluators.DefaultStopWhenDifferent; XmlComment fooComment = doc.CreateComment("foo"); XmlComment barComment = doc.CreateComment("bar"); @@ -162,73 +163,51 @@ XmlCDataSection barCDataSection = doc.CreateCDataSection("bar"); Assert.AreEqual(ComparisonResult.EQUAL, - d.NodeTypeSpecificComparison(fooComment, - fooComment)); + d.CompareNodes(fooComment, fooComment)); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(fooComment, - barComment)); + d.CompareNodes(fooComment, barComment)); Assert.AreEqual(ComparisonResult.EQUAL, - d.NodeTypeSpecificComparison(fooText, fooText)); + d.CompareNodes(fooText, fooText)); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(fooText, barText)); + d.CompareNodes(fooText, barText)); Assert.AreEqual(ComparisonResult.EQUAL, - d.NodeTypeSpecificComparison(fooCDataSection, - fooCDataSection)); + d.CompareNodes(fooCDataSection, fooCDataSection)); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(fooCDataSection, - barCDataSection)); + d.CompareNodes(fooCDataSection, barCDataSection)); Assert.AreEqual(ComparisonResult.EQUAL, - d.NodeTypeSpecificComparison(fooComment, fooText)); + d.CompareNodes(fooComment, fooText)); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(fooComment, barText)); + d.CompareNodes(fooComment, barText)); Assert.AreEqual(ComparisonResult.EQUAL, - d.NodeTypeSpecificComparison(fooComment, - fooCDataSection)); + d.CompareNodes(fooComment, fooCDataSection)); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(fooComment, - barCDataSection)); + d.CompareNodes(fooComment, barCDataSection)); Assert.AreEqual(ComparisonResult.EQUAL, - d.NodeTypeSpecificComparison(fooText, - fooComment)); + d.CompareNodes(fooText, fooComment)); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(fooText, barComment)); + d.CompareNodes(fooText, barComment)); Assert.AreEqual(ComparisonResult.EQUAL, - d.NodeTypeSpecificComparison(fooText, - fooCDataSection)); + d.CompareNodes(fooText, fooCDataSection)); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(fooText, - barCDataSection)); + d.CompareNodes(fooText, barCDataSection)); Assert.AreEqual(ComparisonResult.EQUAL, - d.NodeTypeSpecificComparison(fooCDataSection, - fooText)); + d.CompareNodes(fooCDataSection, fooText)); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(fooCDataSection, - barText)); + d.CompareNodes(fooCDataSection, barText)); Assert.AreEqual(ComparisonResult.EQUAL, - d.NodeTypeSpecificComparison(fooCDataSection, - fooComment)); + d.CompareNodes(fooCDataSection, fooComment)); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(fooCDataSection, - barComment)); - Assert.AreEqual(ComparisonResult.EQUAL, - d.NodeTypeSpecificComparison(fooText, - doc.CreateElement("bar"))); - Assert.AreEqual(9, invocations); + d.CompareNodes(fooCDataSection, barComment)); + Assert.AreEqual(9, ex.invoked); } [Test] public void CompareProcessingInstructions() { DOMDifferenceEngine d = new DOMDifferenceEngine(); - int invocations = 0; - d.DifferenceListener += delegate(Comparison comp, - ComparisonResult r) { - Assert.AreEqual(0, invocations); - invocations++; - Assert.AreEqual(ComparisonType.PROCESSING_INSTRUCTION_TARGET, - comp.Type); - Assert.AreEqual(ComparisonResult.CRITICAL, r); - }; + DiffExpecter ex = + new DiffExpecter(ComparisonType.PROCESSING_INSTRUCTION_TARGET); + d.DifferenceListener += ex.ComparisonPerformed; d.DifferenceEvaluator = DifferenceEvaluators.DefaultStopWhenDifferent; @@ -237,47 +216,30 @@ XmlProcessingInstruction bar1 = doc.CreateProcessingInstruction("bar", "1"); Assert.AreEqual(ComparisonResult.EQUAL, - d.NodeTypeSpecificComparison(foo1, foo1)); + d.CompareNodes(foo1, foo1)); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(foo1, bar1)); - Assert.AreEqual(ComparisonResult.EQUAL, - d.NodeTypeSpecificComparison(foo1, - doc.CreateElement("bar"))); - Assert.AreEqual(1, invocations); + d.CompareNodes(foo1, bar1)); + Assert.AreEqual(1, ex.invoked); d = new DOMDifferenceEngine(); - invocations = 0; - d.DifferenceListener += delegate(Comparison comp, - ComparisonResult r) { - Assert.AreEqual(0, invocations); - invocations++; - Assert.AreEqual(ComparisonType.PROCESSING_INSTRUCTION_DATA, - comp.Type); - Assert.AreEqual(ComparisonResult.CRITICAL, r); - }; + ex = new DiffExpecter(ComparisonType.PROCESSING_INSTRUCTION_DATA); + d.DifferenceListener += ex.ComparisonPerformed; d.DifferenceEvaluator = DifferenceEvaluators.DefaultStopWhenDifferent; XmlProcessingInstruction foo2 = doc.CreateProcessingInstruction("foo", "2"); - Assert.AreEqual(ComparisonResult.EQUAL, - d.NodeTypeSpecificComparison(foo1, foo1)); + Assert.AreEqual(ComparisonResult.EQUAL, d.CompareNodes(foo1, foo1)); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(foo1, foo2)); - Assert.AreEqual(1, invocations); + d.CompareNodes(foo1, foo2)); + Assert.AreEqual(1, ex.invoked); } [Test] public void CompareDocuments() { DOMDifferenceEngine d = new DOMDifferenceEngine(); - int invocations = 0; - d.DifferenceListener += delegate(Comparison comp, - ComparisonResult r) { - Assert.AreEqual(0, invocations); - invocations++; - Assert.AreEqual(ComparisonType.HAS_DOCTYPE_DECLARATION, - comp.Type); - Assert.AreEqual(ComparisonResult.CRITICAL, r); - }; + DiffExpecter ex = + new DiffExpecter(ComparisonType.HAS_DOCTYPE_DECLARATION); + d.DifferenceListener += ex.ComparisonPerformed; d.DifferenceEvaluator = delegate(Comparison comparison, ComparisonResult outcome) { if (comparison.Type == ComparisonType.HAS_DOCTYPE_DECLARATION) { @@ -301,23 +263,16 @@ + "<Book/>") .Build()); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(d1, d2)); - Assert.AreEqual(1, invocations); + d.CompareNodes(d1, d2)); + Assert.AreEqual(1, ex.invoked); #endif #if false // need a way to figure out the XML_* differences // .NET doesn't like XML 1.1 anyway - invocations = 0; d = new DOMDifferenceEngine(); - d.DifferenceListener += delegate(Comparison comp, - ComparisonResult r) { - Assert.AreEqual(0, invocations); - invocations++; - Assert.AreEqual(ComparisonType.XML_VERSION, - comp.Type); - Assert.AreEqual(ComparisonResult.CRITICAL, r); - }; + ex = new DiffExpecter(ComparisonType.XML_VERSION); + d.DifferenceListener += ex.ComparisonPerformed; d.DifferenceEvaluator = DifferenceEvaluators.DefaultStopWhenDifferent; @@ -330,21 +285,14 @@ + " encoding=\"UTF-8\"?>" + "<Book/>").Build()); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(d1, d2)); - Assert.AreEqual(1, invocations); + d.CompareNodes(d1, d2)); + Assert.AreEqual(1, ex.invoked); #endif #if false // need a way to figure out the XML_* differences - invocations = 0; d = new DOMDifferenceEngine(); - d.DifferenceListener += delegate(Comparison comp, - ComparisonResult r) { - Assert.AreEqual(0, invocations); - invocations++; - Assert.AreEqual(ComparisonType.XML_STANDALONE, - comp.Type); - Assert.AreEqual(ComparisonResult.CRITICAL, r); - }; + ex = new DiffExpecter(ComparisonType.XML_STANDALONE); + d.DifferenceListener += ex.ComparisonPerformed; d.DifferenceEvaluator = DifferenceEvaluators.DefaultStopWhenDifferent; @@ -357,21 +305,14 @@ + " standalone=\"no\"?>" + "<Book/>").Build()); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(d1, d2)); - Assert.AreEqual(1, invocations); + d.CompareNodes(d1, d2)); + Assert.AreEqual(1, ex.invoked); #endif #if false // need a way to figure out the XML_* differences - invocations = 0; d = new DOMDifferenceEngine(); - d.DifferenceListener += delegate(Comparison comp, - ComparisonResult r) { - Assert.AreEqual(0, invocations); - invocations++; - Assert.AreEqual(ComparisonType.XML_ENCODING, - comp.Type); - Assert.AreEqual(ComparisonResult.CRITICAL, r); - }; + ex = new DiffExpecter(ComparisonType.XML_ENCODING); + d.DifferenceListener += ex.ComparisonPerformed; d.DifferenceEvaluator = delegate(Comparison comparison, ComparisonResult outcome) { if (comparison.Type == ComparisonType.XML_ENCODING) { @@ -391,23 +332,16 @@ + " encoding=\"UTF-16\"?>" + "<Book/>").Build()); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(d1, d2)); - Assert.AreEqual(1, invocations); + d.CompareNodes(d1, d2)); + Assert.AreEqual(1, ex.invoked); #endif } [Test] public void CompareDocTypes() { - int invocations = 0; DOMDifferenceEngine d = new DOMDifferenceEngine(); - d.DifferenceListener += delegate(Comparison comp, - ComparisonResult r) { - Assert.AreEqual(0, invocations); - invocations++; - Assert.AreEqual(ComparisonType.DOCTYPE_NAME, - comp.Type); - Assert.AreEqual(ComparisonResult.CRITICAL, r); - }; + DiffExpecter ex = new DiffExpecter(ComparisonType.DOCTYPE_NAME); + d.DifferenceListener += ex.ComparisonPerformed; d.DifferenceEvaluator = DifferenceEvaluators.DefaultStopWhenDifferent; @@ -418,37 +352,23 @@ TestResources.BOOK_DTD, null); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(dt1, dt2)); - Assert.AreEqual(1, invocations); + d.CompareNodes(dt1, dt2)); + Assert.AreEqual(1, ex.invoked); - invocations = 0; d = new DOMDifferenceEngine(); - d.DifferenceListener += delegate(Comparison comp, - ComparisonResult r) { - Assert.AreEqual(0, invocations); - invocations++; - Assert.AreEqual(ComparisonType.DOCTYPE_PUBLIC_ID, - comp.Type); - Assert.AreEqual(ComparisonResult.CRITICAL, r); - }; + ex = new DiffExpecter(ComparisonType.DOCTYPE_PUBLIC_ID); + d.DifferenceListener += ex.ComparisonPerformed; d.DifferenceEvaluator = DifferenceEvaluators.DefaultStopWhenDifferent; dt2 = doc.CreateDocumentType("name", "pub2", TestResources.BOOK_DTD, null); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(dt1, dt2)); - Assert.AreEqual(1, invocations); + d.CompareNodes(dt1, dt2)); + Assert.AreEqual(1, ex.invoked); - invocations = 0; d = new DOMDifferenceEngine(); - d.DifferenceListener += delegate(Comparison comp, - ComparisonResult r) { - Assert.AreEqual(0, invocations); - invocations++; - Assert.AreEqual(ComparisonType.DOCTYPE_SYSTEM_ID, - comp.Type); - Assert.AreEqual(ComparisonResult.CRITICAL, r); - }; + ex = new DiffExpecter(ComparisonType.DOCTYPE_SYSTEM_ID); + d.DifferenceListener += ex.ComparisonPerformed; d.DifferenceEvaluator = delegate(Comparison comparison, ComparisonResult outcome) { if (comparison.Type == ComparisonType.DOCTYPE_SYSTEM_ID) { @@ -461,9 +381,86 @@ dt2 = doc.CreateDocumentType("name", "pub", TestResources.TEST_DTD, null); Assert.AreEqual(ComparisonResult.CRITICAL, - d.NodeTypeSpecificComparison(dt1, dt2)); - Assert.AreEqual(1, invocations); + d.CompareNodes(dt1, dt2)); + Assert.AreEqual(1, ex.invoked); } + [Test] + public void CompareElements() { + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.ELEMENT_TAG_NAME); + d.DifferenceListener += ex.ComparisonPerformed; + d.DifferenceEvaluator = + DifferenceEvaluators.DefaultStopWhenDifferent; + + XmlElement e1 = doc.CreateElement("foo"); + XmlElement e2 = doc.CreateElement("foo"); + XmlElement e3 = doc.CreateElement("bar"); + Assert.AreEqual(ComparisonResult.EQUAL, d.CompareNodes(e1, e2)); + Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(e1, e3)); + Assert.AreEqual(1, ex.invoked); + + d = new DOMDifferenceEngine(); + ex = new DiffExpecter(ComparisonType.ELEMENT_NUM_ATTRIBUTES); + d.DifferenceListener += ex.ComparisonPerformed; + d.DifferenceEvaluator = + DifferenceEvaluators.DefaultStopWhenDifferent; + e1.SetAttribute("attr1", "value1"); + Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(e1, e2)); + Assert.AreEqual(1, ex.invoked); + + d = new DOMDifferenceEngine(); + ex = new DiffExpecter(ComparisonType.ATTR_NAME_LOOKUP); + d.DifferenceListener += ex.ComparisonPerformed; + d.DifferenceEvaluator = + DifferenceEvaluators.DefaultStopWhenDifferent; + e2.SetAttribute("attr1", "urn:xmlunit:test", "value1"); + Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(e1, e2)); + Assert.AreEqual(1, ex.invoked); + + d = new DOMDifferenceEngine(); + d.DifferenceListener += delegate(Comparison comp, + ComparisonResult r) { + Assert.Fail("unexpected Comparison of type " + comp.Type + + " with outcome " + r + " and values '" + + comp.ControlNodeDetails.Value + + "' and '" + + comp.TestNodeDetails.Value + "'"); + }; + d.DifferenceEvaluator = + DifferenceEvaluators.DefaultStopWhenDifferent; + e1.SetAttribute("attr1", "urn:xmlunit:test", "value1"); + e2.SetAttribute("attr1", null, "value1"); + Assert.AreEqual(ComparisonResult.EQUAL, d.CompareNodes(e1, e2)); + } + + [Test] + public void CompareAttributes() { + XmlAttribute a1 = doc.CreateAttribute("foo"); + XmlAttribute a2 = doc.CreateAttribute("foo"); + + DOMDifferenceEngine d = new DOMDifferenceEngine(); +#if false // Can't reset "explicitly set" state for Documents created via API + DiffExpecter ex = new DiffExpecter(ComparisonType.ATTR_VALUE_EXPLICITLY_SPECIFIED); + d.DifferenceListener += ex.ComparisonPerformed; + d.DifferenceEvaluator = DifferenceEvaluators.Accept; + a2.Value = string.Empty; + Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(a1, a2)); + Assert.AreEqual(1, ex.invoked); +#endif + + d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.ATTR_VALUE); + d.DifferenceListener += ex.ComparisonPerformed; + d.DifferenceEvaluator = + DifferenceEvaluators.DefaultStopWhenDifferent; + XmlAttribute a3 = doc.CreateAttribute("foo"); + a1.Value = "foo"; + a2.Value = "foo"; + a3.Value = "bar"; + Assert.AreEqual(ComparisonResult.EQUAL, d.CompareNodes(a1, a2)); + Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(a1, a3)); + Assert.AreEqual(1, ex.invoked); + } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-07-20 17:33:44
|
Revision: 417 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=417&view=rev Author: bodewig Date: 2010-07-20 17:33:37 +0000 (Tue, 20 Jul 2010) Log Message: ----------- make directory references more regular for tests - location itself is not the problem on Mono, it seems xsi:schemaLocation is Modified Paths: -------------- trunk/xmlunit/src/main/net-core/input/AbstractSource.cs trunk/xmlunit/src/tests/net-core/TestResources.cs trunk/xmlunit/src/tests/net-core/builder/InputTest.cs trunk/xmlunit/src/tests/net-core/validation/ValidatorTest.cs Modified: trunk/xmlunit/src/main/net-core/input/AbstractSource.cs =================================================================== --- trunk/xmlunit/src/main/net-core/input/AbstractSource.cs 2010-07-15 06:41:10 UTC (rev 416) +++ trunk/xmlunit/src/main/net-core/input/AbstractSource.cs 2010-07-20 17:33:37 UTC (rev 417) @@ -38,5 +38,9 @@ systemId = value; } } + public override string ToString() { + return string.Format("{0} with systemId {1}", GetType().Name, + SystemId); + } } } Modified: trunk/xmlunit/src/tests/net-core/TestResources.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/TestResources.cs 2010-07-15 06:41:10 UTC (rev 416) +++ trunk/xmlunit/src/tests/net-core/TestResources.cs 2010-07-20 17:33:37 UTC (rev 417) @@ -11,18 +11,27 @@ See the License for the specific language governing permissions and limitations under the License. */ + +using System; + namespace net.sf.xmlunit { public sealed class TestResources { - public const string ANIMAL_FILE = "../../../src/tests/resources/test1.xml"; - public const string BLAME_FILE = "../../../src/tests/resources/test.blame.html"; + private static readonly string PREFIX = "../../../"; - public const string ANIMAL_XSL = "../../../src/tests/resources/animal.xsl"; - public const string DOG_FILE = "../../../src/tests/resources/testAnimal.xml"; + public static readonly string TESTS_DIR = + PREFIX + "src/tests/resources/"; - public const string BOOK_DTD = "../../../src/tests/resources/Book.dtd"; - public const string TEST_DTD = "../../../src/tests/resources/test.dtd"; + public static readonly string ANIMAL_FILE = TESTS_DIR + "test1.xml"; + public static readonly string BLAME_FILE = + TESTS_DIR + "test.blame.html"; + public static readonly string ANIMAL_XSL = TESTS_DIR + "animal.xsl"; + public static readonly string DOG_FILE = TESTS_DIR + "testAnimal.xml"; + + public static readonly string BOOK_DTD = TESTS_DIR + "Book.dtd"; + public static readonly string TEST_DTD = TESTS_DIR + "test.dtd"; + private TestResources() { } } } Modified: trunk/xmlunit/src/tests/net-core/builder/InputTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/builder/InputTest.cs 2010-07-15 06:41:10 UTC (rev 416) +++ trunk/xmlunit/src/tests/net-core/builder/InputTest.cs 2010-07-20 17:33:37 UTC (rev 417) @@ -88,7 +88,7 @@ [Test] public void ShouldParseATransformationFromSource() { ISource input = Input.FromMemory("<animal>furry</animal>").Build(); ISource s = Input.ByTransforming(input) - .WithStylesheet(Input.FromFile("../../../src/tests/resources/animal.xsl") + .WithStylesheet(Input.FromFile(TestResources.TESTS_DIR + "animal.xsl") .Build()) .Build(); Assert.That(s, Is.Not.Null); @@ -100,7 +100,7 @@ [Test] public void ShouldParseATransformationFromBuilder() { Input.IBuilder input = Input.FromMemory("<animal>furry</animal>"); ISource s = Input.ByTransforming(input) - .WithStylesheet(Input.FromFile("../../../src/tests/resources/animal.xsl")) + .WithStylesheet(Input.FromFile(TestResources.TESTS_DIR + "animal.xsl")) .Build(); Assert.That(s, Is.Not.Null); XmlDocument d = Parse(s); Modified: trunk/xmlunit/src/tests/net-core/validation/ValidatorTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/validation/ValidatorTest.cs 2010-07-15 06:41:10 UTC (rev 416) +++ trunk/xmlunit/src/tests/net-core/validation/ValidatorTest.cs 2010-07-20 17:33:37 UTC (rev 417) @@ -23,7 +23,7 @@ [Test] public void ShouldSuccessfullyValidateSchema() { Validator v = Validator.ForLanguage(Languages.W3C_XML_SCHEMA_NS_URI); - v.SchemaSource = new StreamSource("../../../src/tests/resources/Book.xsd"); + v.SchemaSource = new StreamSource(TestResources.TESTS_DIR + "Book.xsd"); ValidationResult r = v.ValidateSchema(); Assert.IsTrue(r.Valid); Assert.IsFalse(r.Problems.GetEnumerator().MoveNext()); @@ -32,8 +32,8 @@ [Test] public void ShouldSuccessfullyValidateInstance() { Validator v = Validator.ForLanguage(Languages.W3C_XML_SCHEMA_NS_URI); - v.SchemaSource = new StreamSource("../../../src/tests/resources/Book.xsd"); - ValidationResult r = v.ValidateInstance(new StreamSource("../../../src/tests/resources/BookXsdGenerated.xml")); + v.SchemaSource = new StreamSource(TestResources.TESTS_DIR + "Book.xsd"); + ValidationResult r = v.ValidateInstance(new StreamSource(TestResources.TESTS_DIR + "BookXsdGenerated.xml")); IEnumerator<ValidationProblem> problems = r.Problems.GetEnumerator(); bool haveErrors = problems.MoveNext(); @@ -47,7 +47,7 @@ [Test] public void ShouldFailOnBrokenSchema() { Validator v = Validator.ForLanguage(Languages.W3C_XML_SCHEMA_NS_URI); - v.SchemaSource = new StreamSource("../../../src/tests/resources/broken.xsd"); + v.SchemaSource = new StreamSource(TestResources.TESTS_DIR + "broken.xsd"); ValidationResult r = v.ValidateSchema(); Assert.IsFalse(r.Valid); Assert.IsTrue(r.Problems.GetEnumerator().MoveNext()); @@ -56,8 +56,8 @@ [Test] public void ShouldFailOnBrokenInstance() { Validator v = Validator.ForLanguage(Languages.W3C_XML_SCHEMA_NS_URI); - v.SchemaSource = new StreamSource("../../../src/tests/resources/Book.xsd"); - ValidationResult r = v.ValidateInstance(new StreamSource("../../../src/tests/resources/invalidBook.xml")); + v.SchemaSource = new StreamSource(TestResources.TESTS_DIR + "Book.xsd"); + ValidationResult r = v.ValidateInstance(new StreamSource(TestResources.TESTS_DIR + "invalidBook.xml")); Assert.IsFalse(r.Valid); Assert.IsTrue(r.Problems.GetEnumerator().MoveNext()); } @@ -65,9 +65,9 @@ [Test] public void ShouldThrowWhenValidatingInstanceAndSchemaIsInvalid() { Validator v = Validator.ForLanguage(Languages.W3C_XML_SCHEMA_NS_URI); - v.SchemaSource = new StreamSource("../../../src/tests/resources/broken.xsd"); + v.SchemaSource = new StreamSource(TestResources.TESTS_DIR + "broken.xsd"); Assert.Throws(typeof(XMLUnitException), delegate() { - v.ValidateInstance(new StreamSource("../../../src/tests/resources/BookXsdGenerated.xml")); + v.ValidateInstance(new StreamSource(TestResources.TESTS_DIR + "BookXsdGenerated.xml")); }); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-08-13 11:54:20
|
Revision: 424 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=424&view=rev Author: bodewig Date: 2010-08-13 11:54:14 +0000 (Fri, 13 Aug 2010) Log Message: ----------- don't tie the DifferenceEngine's interface to DOM Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/AbstractDifferenceEngine.java trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/Comparison.java trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java trunk/xmlunit/src/main/net-core/diff/AbstractDifferenceEngine.cs trunk/xmlunit/src/main/net-core/diff/Comparison.cs trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/AbstractDifferenceEngine.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/AbstractDifferenceEngine.java 2010-08-10 16:12:49 UTC (rev 423) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/AbstractDifferenceEngine.java 2010-08-13 11:54:14 UTC (rev 424) @@ -74,8 +74,8 @@ * listeners and returns the outcome. */ protected final ComparisonResult compare(Comparison comp) { - Object controlValue = comp.getControlNodeDetails().getValue(); - Object testValue = comp.getTestNodeDetails().getValue(); + Object controlValue = comp.getControlDetails().getValue(); + Object testValue = comp.getTestDetails().getValue(); boolean equal = controlValue == null ? testValue == null : controlValue.equals(testValue); ComparisonResult initial = Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/Comparison.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/Comparison.java 2010-08-10 16:12:49 UTC (rev 423) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/Comparison.java 2010-08-13 11:54:14 UTC (rev 424) @@ -13,37 +13,36 @@ */ package net.sf.xmlunit.diff; -import org.w3c.dom.Node; - /** * Details of a single comparison XMLUnit has performed. */ public class Comparison { /** - * The details of a Node that took part in the comparision. + * The details of a target (usually some representation of an XML + * Node) that took part in the comparison. */ public static class Detail { - private final Node node; + private final Object target; private final String xpath; private final Object value; - private Detail(Node n, String x, Object v) { - node = n; + private Detail(Object n, String x, Object v) { + target = n; xpath = x; value = v; } /** - * The actual Node. + * The actual target. */ - public Node getNode() { return node; } + public Object getTarget() { return target; } /** - * XPath leading to the Node. + * XPath leading to the target. */ public String getXPath() { return xpath; } /** - * The value for comparision found at the current node. + * The value for comparison found at the current target. */ public Object getValue() { return value; } } @@ -51,32 +50,32 @@ private final Detail control, test; private final ComparisonType type; - public Comparison(ComparisonType t, Node controlNode, + public Comparison(ComparisonType t, Object controlTarget, String controlXPath, Object controlValue, - Node testNode, String testXPath, Object testValue) { + Object testTarget, String testXPath, Object testValue) { type = t; - control = new Detail(controlNode, controlXPath, controlValue); - test = new Detail(testNode, testXPath, testValue); + control = new Detail(controlTarget, controlXPath, controlValue); + test = new Detail(testTarget, testXPath, testValue); } /** - * The kind of comparision performed. + * The kind of comparison performed. */ public ComparisonType getType() { return type; } /** - * Details of the control node. + * Details of the control target. */ - public Detail getControlNodeDetails() { + public Detail getControlDetails() { return control; } /** - * Details of the test node. + * Details of the test target. */ - public Detail getTestNodeDetails() { + public Detail getTestDetails() { return test; } Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java 2010-08-10 16:12:49 UTC (rev 423) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java 2010-08-13 11:54:14 UTC (rev 424) @@ -48,9 +48,9 @@ switch (comparison.getType()) { case NODE_TYPE: Short control = (Short) comparison - .getControlNodeDetails().getValue(); + .getControlDetails().getValue(); Short test = (Short) comparison - .getTestNodeDetails().getValue(); + .getTestDetails().getValue(); if ((control.equals(TEXT) && test.equals(CDATA)) || (control.equals(CDATA) && test.equals(TEXT))) { Modified: trunk/xmlunit/src/main/net-core/diff/AbstractDifferenceEngine.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/AbstractDifferenceEngine.cs 2010-08-10 16:12:49 UTC (rev 423) +++ trunk/xmlunit/src/main/net-core/diff/AbstractDifferenceEngine.cs 2010-08-13 11:54:14 UTC (rev 424) @@ -59,8 +59,8 @@ /// listeners and returns the outcome. /// </summary> protected internal ComparisonResult Compare(Comparison comp) { - object controlValue = comp.ControlNodeDetails.Value; - object testValue = comp.TestNodeDetails.Value; + object controlValue = comp.ControlDetails.Value; + object testValue = comp.TestDetails.Value; bool equal = controlValue == null ? testValue == null : controlValue.Equals(testValue); ComparisonResult initial = Modified: trunk/xmlunit/src/main/net-core/diff/Comparison.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/Comparison.cs 2010-08-10 16:12:49 UTC (rev 423) +++ trunk/xmlunit/src/main/net-core/diff/Comparison.cs 2010-08-13 11:54:14 UTC (rev 424) @@ -12,8 +12,6 @@ limitations under the License. */ -using System.Xml; - namespace net.sf.xmlunit.diff { /// <summary> @@ -22,29 +20,30 @@ public class Comparison { /// <summary> - /// The details of a Node that took part in the comparision. + /// The details of a target (usually a representation of an + /// XML node) that took part in the comparison. /// </summary> public sealed class Detail { - private readonly XmlNode node; + private readonly object target; private readonly string xpath; private readonly object value; - internal Detail(XmlNode n, string x, object v) { - node = n; + internal Detail(object t, string x, object v) { + target = t; xpath = x; value = v; } /// <summary> - /// The actual Node. + /// The actual target. /// </summary> - public XmlNode Node { get { return node; } } + public object Target { get { return target; } } /// <summary> - /// XPath leading to the Node. + /// XPath leading to the target. /// </summary> public string XPath { get { return xpath; } } /// <summary> - /// The value for comparision found at the current node. + /// The value for comparison found at the current target. /// </summary> public object Value { get { return value; } } } @@ -52,17 +51,17 @@ private readonly Detail control, test; private readonly ComparisonType type; - public Comparison(ComparisonType t, XmlNode controlNode, + public Comparison(ComparisonType t, object controlTarget, string controlXPath, object controlValue, - XmlNode testNode, string testXPath, + object testTarget, string testXPath, object testValue) { type = t; - control = new Detail(controlNode, controlXPath, controlValue); - test = new Detail(testNode, testXPath, testValue); + control = new Detail(controlTarget, controlXPath, controlValue); + test = new Detail(testTarget, testXPath, testValue); } /// <summary> - /// The kind of comparision performed. + /// The kind of comparison performed. /// </summary> public ComparisonType Type { get { @@ -71,18 +70,18 @@ } /// <summary> - /// Details of the control node. + /// Details of the control target. /// </summary> - public Detail ControlNodeDetails { + public Detail ControlDetails { get { return control; } } /// <summary> - /// Details of the test node. + /// Details of the test target. /// </summary> - public Detail TestNodeDetails { + public Detail TestDetails { get { return test; } Modified: trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs 2010-08-10 16:12:49 UTC (rev 423) +++ trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs 2010-08-13 11:54:14 UTC (rev 424) @@ -41,9 +41,9 @@ switch (comparison.Type) { case ComparisonType.NODE_TYPE: XmlNodeType control = - (XmlNodeType) comparison.ControlNodeDetails.Value; + (XmlNodeType) comparison.ControlDetails.Value; XmlNodeType test = - (XmlNodeType) comparison.TestNodeDetails.Value; + (XmlNodeType) comparison.TestDetails.Value; if ((control == XmlNodeType.Text && test == XmlNodeType.CDATA) || (control == XmlNodeType.CDATA && test == XmlNodeType.Text) Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-08-10 16:12:49 UTC (rev 423) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-08-13 11:54:14 UTC (rev 424) @@ -152,11 +152,11 @@ if (comparison.getType() == ComparisonType.NODE_TYPE) { if (outcome == ComparisonResult.EQUAL || ( - comparison.getControlNodeDetails() - .getNode() instanceof CharacterData + comparison.getControlDetails() + .getTarget() instanceof CharacterData && - comparison.getTestNodeDetails() - .getNode() instanceof CharacterData + comparison.getTestDetails() + .getTarget() instanceof CharacterData )) { return ComparisonResult.EQUAL; } @@ -429,9 +429,9 @@ ComparisonResult outcome) { fail("unexpected Comparison of type " + comparison.getType() + " with outcome " + outcome + " and values '" - + comparison.getControlNodeDetails().getValue() + + comparison.getControlDetails().getValue() + "' and '" - + comparison.getTestNodeDetails().getValue() + "'"); + + comparison.getTestDetails().getValue() + "'"); } }); e1.setAttributeNS("urn:xmlunit:test", "attr1", "value1"); Modified: trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-10 16:12:49 UTC (rev 423) +++ trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-13 11:54:14 UTC (rev 424) @@ -143,11 +143,9 @@ if (comparison.Type == ComparisonType.NODE_TYPE) { if (outcome == ComparisonResult.EQUAL || ( - comparison.ControlNodeDetails.Node - is XmlCharacterData + comparison.ControlDetails.Target is XmlCharacterData && - comparison.TestNodeDetails.Node is XmlCharacterData - )) { + comparison.TestDetails.Target is XmlCharacterData)) { return ComparisonResult.EQUAL; } } @@ -423,9 +421,9 @@ ComparisonResult r) { Assert.Fail("unexpected Comparison of type " + comp.Type + " with outcome " + r + " and values '" - + comp.ControlNodeDetails.Value + + comp.ControlDetails.Value + "' and '" - + comp.TestNodeDetails.Value + "'"); + + comp.TestDetails.Value + "'"); }; d.DifferenceEvaluator = DifferenceEvaluators.DefaultStopWhenDifferent; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-08-13 13:10:22
|
Revision: 425 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=425&view=rev Author: bodewig Date: 2010-08-13 13:10:16 +0000 (Fri, 13 Aug 2010) Log Message: ----------- start recursion support Modified Paths: -------------- trunk/xmlunit/src/buildtools/codegen.xslt trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/IterableNodeList.java trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml trunk/xmlunit/src/main/net-core/util/Convert.cs trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs Modified: trunk/xmlunit/src/buildtools/codegen.xslt =================================================================== --- trunk/xmlunit/src/buildtools/codegen.xslt 2010-08-13 11:54:14 UTC (rev 424) +++ trunk/xmlunit/src/buildtools/codegen.xslt 2010-08-13 13:10:16 UTC (rev 425) @@ -122,6 +122,10 @@ <xsl:call-template name="if-return-boilerplate"/> </xsl:template> + <xsl:template match="if-return-boilerplate"> + <xsl:call-template name="if-return-boilerplate"/> + </xsl:template> + <xsl:template name="if-return-boilerplate"> if (lastResult == ComparisonResult.CRITICAL) { return lastResult; Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-08-13 11:54:14 UTC (rev 424) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-08-13 13:10:16 UTC (rev 425) @@ -17,8 +17,10 @@ summary="Difference engine based on DOM." extends="AbstractDifferenceEngine"> + <import reference="java.util.List"/> <import reference="javax.xml.transform.Source"/> <import reference="net.sf.xmlunit.util.Convert"/> + <import reference="net.sf.xmlunit.util.IterableNodeList"/> <import reference="org.w3c.dom.Attr"/> <import reference="org.w3c.dom.CharacterData"/> <import reference="org.w3c.dom.Document"/> @@ -237,7 +239,36 @@ } private ComparisonResult compareNodeLists(NodeList control, NodeList test) { - return ComparisonResult.EQUAL; + List<Node> controlList = IterableNodeList.asList(control); + List<Node> testList = IterableNodeList.asList(test); + Match lastMatch = new Match(null, -1); +]]></literal> + <lastResultDef/> + // if there are no children on either Node, the result is equal + lastResult = ComparisonResult.EQUAL; + <literal><![CDATA[ + for (int i = 0; i < controlList.size(); i++) { + Match testMatch = findMatchingNode(controlList.get(i), testList, + lastMatch.index); + if (testMatch != null) { +]]></literal> + <compareMethodExpr method="compareNodes" + controlExpr="controlList.get(i)" + testExpr="testMatch.node"/> + <literal><![CDATA[ + lastMatch = testMatch; + } else { + lastResult = + compare(new Comparison(ComparisonType.CHILD_LOOKUP, + controlList.get(i), null, + controlList.get(i), + null, null, null)); +]]></literal> + <if-return-boilerplate/> + <literal><![CDATA[ + } + } + return lastResult; } private ComparisonResult compareAttributes(Attr control, Attr test) { @@ -250,7 +281,8 @@ test, null, test.getValue())); } - private static Attr findMatchingAttr(NamedNodeMap map, Attr attrToMatch) { + private static Attr findMatchingAttr(final NamedNodeMap map, + final Attr attrToMatch) { if (attrToMatch.getNamespaceURI() == null) { return (Attr) map.getNamedItem(attrToMatch.getName()); } else { @@ -259,5 +291,39 @@ } } + private Match findMatchingNode(final Node searchFor, + final List<Node> searchIn, + final int indexOfLastMatch) { + final int searchSize = searchIn.size(); + for (int i = indexOfLastMatch + 1; i < searchSize; i++) { + if (nodesMatch(searchFor, searchIn.get(i))) { + return new Match(searchIn.get(i), i); + } + } + for (int i = 0; i < indexOfLastMatch; i++) { + if (nodesMatch(searchFor, searchIn.get(i))) { + return new Match(searchIn.get(i), i); + } + } + return null; + } + + private boolean nodesMatch(final Node n1, final Node n2) { + ComparisonResult r = + compare(new Comparison(ComparisonType.NODE_TYPE, + n1, null, n1.getNodeType(), + n2, null, n2.getNodeType())); + return r == ComparisonResult.EQUAL; + } + + private class Match { + private final Node node; + private final int index; + private Match(Node match, int index) { + this.node = match; + this.index = index; + } + } + ]]></literal> </class> \ No newline at end of file Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/IterableNodeList.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/IterableNodeList.java 2010-08-13 11:54:14 UTC (rev 424) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/IterableNodeList.java 2010-08-13 13:10:16 UTC (rev 425) @@ -13,7 +13,9 @@ */ package net.sf.xmlunit.util; +import java.util.ArrayList; import java.util.Iterator; +import java.util.List; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -46,4 +48,22 @@ return current < length; } } + + /** + * Turns the iterable into a list. + */ + public static List<Node> asList(IterableNodeList l) { + ArrayList<Node> a = new ArrayList<Node>(l.length); + for (Node n : l) { + a.add(n); + } + return a; + } + + /** + * Turns the NodeList into a list. + */ + public static List<Node> asList(NodeList l) { + return asList(new IterableNodeList(l)); + } } Modified: trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-13 11:54:14 UTC (rev 424) +++ trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-13 13:10:16 UTC (rev 425) @@ -18,6 +18,7 @@ extends="AbstractDifferenceEngine"> <import reference="System"/> + <import reference="System.Collections.Generic"/> <import reference="System.Xml"/> <literal><![CDATA[ @@ -234,7 +235,40 @@ private ComparisonResult CompareNodeLists(XmlNodeList control, XmlNodeList test) { - return ComparisonResult.EQUAL; + List<XmlNode> controlList = + new List<XmlNode>(net.sf.xmlunit.util.Convert + .Cast<XmlNode>(control)); + List<XmlNode> testList = + new List<XmlNode>(net.sf.xmlunit.util.Convert + .Cast<XmlNode>(test)); + Match lastMatch = new Match(null, -1); +]]></literal> + <lastResultDef/> + // if there are no children on either Node, the result is equal + lastResult = ComparisonResult.EQUAL; + <literal><![CDATA[ + for (int i = 0; i < controlList.Count; i++) { + Match testMatch = FindMatchingNode(controlList[i], testList, + lastMatch.index); + if (testMatch != null) { +]]></literal> + <compareMethodExpr method="CompareNodes" + controlExpr="controlList[i]" + testExpr="testMatch.node"/> + <literal><![CDATA[ + lastMatch = testMatch; + } else { + lastResult = + Compare(new Comparison(ComparisonType.CHILD_LOOKUP, + controlList[i], null, + controlList[i], + null, null, null)); +]]></literal> + <if-return-boilerplate/> + <literal><![CDATA[ + } + } + return lastResult; } private ComparisonResult CompareAttributes(XmlAttribute control, @@ -258,5 +292,39 @@ as XmlAttribute; } } + + private Match FindMatchingNode(XmlNode searchFor, + IList<XmlNode> searchIn, + int indexOfLastMatch) { + int searchSize = searchIn.Count; + for (int i = indexOfLastMatch + 1; i < searchSize; i++) { + if (NodesMatch(searchFor, searchIn[i])) { + return new Match(searchIn[i], i); + } + } + for (int i = 0; i < indexOfLastMatch; i++) { + if (NodesMatch(searchFor, searchIn[i])) { + return new Match(searchIn[i], i); + } + } + return null; + } + + private bool NodesMatch(XmlNode n1, XmlNode n2) { + ComparisonResult r = + Compare(new Comparison(ComparisonType.NODE_TYPE, + n1, null, n1.NodeType, + n2, null, n2.NodeType)); + return r == ComparisonResult.EQUAL; + } + + internal class Match { + internal readonly XmlNode node; + internal readonly int index; + internal Match(XmlNode match, int index) { + this.node = match; + this.index = index; + } + } ]]></literal> </class> \ No newline at end of file Modified: trunk/xmlunit/src/main/net-core/util/Convert.cs =================================================================== --- trunk/xmlunit/src/main/net-core/util/Convert.cs 2010-08-13 11:54:14 UTC (rev 424) +++ trunk/xmlunit/src/main/net-core/util/Convert.cs 2010-08-13 13:10:16 UTC (rev 425) @@ -12,6 +12,7 @@ limitations under the License. */ +using System.Collections; using System.Collections.Generic; using System.Xml; using net.sf.xmlunit.input; @@ -72,5 +73,11 @@ } return man; } + + public static IEnumerable<T> Cast<T>(IEnumerable i) { + foreach (T t in i) { + yield return t; + } + } } } Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-08-13 11:54:14 UTC (rev 424) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-08-13 13:10:16 UTC (rev 425) @@ -185,7 +185,7 @@ d.compareNodes(fooCDATASection, fooCDATASection)); assertEquals(ComparisonResult.CRITICAL, d.compareNodes(fooCDATASection, barCDATASection)); - + assertEquals(ComparisonResult.EQUAL, d.compareNodes(fooComment, fooText)); assertEquals(ComparisonResult.CRITICAL, @@ -467,4 +467,36 @@ assertEquals(ComparisonResult.CRITICAL, d.compareNodes(a1, a3)); assertEquals(1, ex.invoked); } + + @Test public void naiveRecursion() { + Element e1 = doc.createElement("foo"); + Element e2 = doc.createElement("foo"); + Element c1 = doc.createElement("bar"); + e1.appendChild(c1); + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.CHILD_LOOKUP); + d.addDifferenceListener(ex); + DifferenceEvaluator ev = new DifferenceEvaluator() { + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult outcome) { + if (comparison.getType() == ComparisonType.CHILD_NODELIST_LENGTH) { + return ComparisonResult.EQUAL; + } + return DifferenceEvaluators.DefaultStopWhenDifferent + .evaluate(comparison, outcome); + } + }; + d.setDifferenceEvaluator(ev); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(e1, e2)); + assertEquals(1, ex.invoked); + + Element c2 = doc.createElement("bar"); + e2.appendChild(c2); + d = new DOMDifferenceEngine(); + ex = new DiffExpecter(ComparisonType.CHILD_LOOKUP); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(ev); + assertEquals(ComparisonResult.EQUAL, d.compareNodes(e1, e2)); + assertEquals(0, ex.invoked); + } } Modified: trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-13 11:54:14 UTC (rev 424) +++ trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-13 13:10:16 UTC (rev 425) @@ -172,7 +172,7 @@ d.CompareNodes(fooCDataSection, fooCDataSection)); Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(fooCDataSection, barCDataSection)); - + Assert.AreEqual(ComparisonResult.EQUAL, d.CompareNodes(fooComment, fooText)); Assert.AreEqual(ComparisonResult.CRITICAL, @@ -460,5 +460,37 @@ Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(a1, a3)); Assert.AreEqual(1, ex.invoked); } + + [Test] + public void NaiveRecursion() { + XmlElement e1 = doc.CreateElement("foo"); + XmlElement e2 = doc.CreateElement("foo"); + XmlElement c1 = doc.CreateElement("bar"); + e1.AppendChild(c1); + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.CHILD_LOOKUP); + d.DifferenceListener += ex.ComparisonPerformed; + DifferenceEvaluator ev = delegate(Comparison comparison, + ComparisonResult outcome) { + if (comparison.Type == ComparisonType.CHILD_NODELIST_LENGTH) { + return ComparisonResult.EQUAL; + } + return DifferenceEvaluators.DefaultStopWhenDifferent(comparison, + outcome); + }; + d.DifferenceEvaluator = ev; + Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(e1, e2)); + Assert.AreEqual(1, ex.invoked); + + XmlElement c2 = doc.CreateElement("bar"); + e2.AppendChild(c2); + d = new DOMDifferenceEngine(); + ex = new DiffExpecter(ComparisonType.CHILD_LOOKUP); + d.DifferenceListener += ex.ComparisonPerformed; + d.DifferenceEvaluator = ev; + Assert.AreEqual(ComparisonResult.EQUAL, d.CompareNodes(e1, e2)); + Assert.AreEqual(0, ex.invoked); + } + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-08-18 14:06:12
|
Revision: 426 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=426&view=rev Author: bodewig Date: 2010-08-18 14:06:06 +0000 (Wed, 18 Aug 2010) Log Message: ----------- make NodeList comparison symmetric Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-08-13 13:10:16 UTC (rev 425) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-08-18 14:06:06 UTC (rev 426) @@ -18,6 +18,8 @@ extends="AbstractDifferenceEngine"> <import reference="java.util.List"/> + <import reference="java.util.Set"/> + <import reference="java.util.TreeSet"/> <import reference="javax.xml.transform.Source"/> <import reference="net.sf.xmlunit.util.Convert"/> <import reference="net.sf.xmlunit.util.IterableNodeList"/> @@ -241,13 +243,19 @@ private ComparisonResult compareNodeLists(NodeList control, NodeList test) { List<Node> controlList = IterableNodeList.asList(control); List<Node> testList = IterableNodeList.asList(test); - Match lastMatch = new Match(null, -1); + final int testSize = testList.size(); + Set<Integer> unmatchedTestIndexes = new TreeSet<Integer>(); + for (int i = 0; i < testSize; i++) { + unmatchedTestIndexes.add(Integer.valueOf(i)); + } ]]></literal> <lastResultDef/> + <literal><![CDATA[ // if there are no children on either Node, the result is equal lastResult = ComparisonResult.EQUAL; - <literal><![CDATA[ - for (int i = 0; i < controlList.size(); i++) { + final int controlSize = controlList.size(); + Match lastMatch = new Match(null, -1); + for (int i = 0; i < controlSize; i++) { Match testMatch = findMatchingNode(controlList.get(i), testList, lastMatch.index); if (testMatch != null) { @@ -256,6 +264,7 @@ controlExpr="controlList.get(i)" testExpr="testMatch.node"/> <literal><![CDATA[ + unmatchedTestIndexes.remove(Integer.valueOf(testMatch.index)); lastMatch = testMatch; } else { lastResult = @@ -268,6 +277,16 @@ <literal><![CDATA[ } } + for (Integer I : unmatchedTestIndexes) { + int i = I.intValue(); + lastResult = + compare(new Comparison(ComparisonType.CHILD_LOOKUP, + null, null, null, + testList.get(i), null, testList.get(i))); +]]></literal> + <if-return-boilerplate/> + <literal><![CDATA[ + } return lastResult; } Modified: trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-13 13:10:16 UTC (rev 425) +++ trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-18 14:06:06 UTC (rev 426) @@ -233,29 +233,37 @@ test, null, test.Data)); } + private static readonly object DUMMY = new object(); + private ComparisonResult CompareNodeLists(XmlNodeList control, XmlNodeList test) { - List<XmlNode> controlList = + IList<XmlNode> controlList = new List<XmlNode>(net.sf.xmlunit.util.Convert .Cast<XmlNode>(control)); - List<XmlNode> testList = + IList<XmlNode> testList = new List<XmlNode>(net.sf.xmlunit.util.Convert .Cast<XmlNode>(test)); - Match lastMatch = new Match(null, -1); + IDictionary<int, object> unmatchedTestIndexes = + new SortedDictionary<int, object>(); + for (int i = 0; i < testList.Count; i++) { + unmatchedTestIndexes.Add(i, DUMMY); + } ]]></literal> <lastResultDef/> + <literal><![CDATA[ // if there are no children on either Node, the result is equal lastResult = ComparisonResult.EQUAL; - <literal><![CDATA[ + Match lastMatch = new Match(null, -1); for (int i = 0; i < controlList.Count; i++) { Match testMatch = FindMatchingNode(controlList[i], testList, - lastMatch.index); + lastMatch.Index); if (testMatch != null) { ]]></literal> <compareMethodExpr method="CompareNodes" controlExpr="controlList[i]" - testExpr="testMatch.node"/> + testExpr="testMatch.Node"/> <literal><![CDATA[ + unmatchedTestIndexes.Remove(testMatch.Index); lastMatch = testMatch; } else { lastResult = @@ -268,6 +276,15 @@ <literal><![CDATA[ } } + foreach (int i in unmatchedTestIndexes.Keys) { + lastResult = + Compare(new Comparison(ComparisonType.CHILD_LOOKUP, + null, null, null, + testList[i], null, testList[i])); +]]></literal> + <if-return-boilerplate/> + <literal><![CDATA[ + } return lastResult; } @@ -319,11 +336,11 @@ } internal class Match { - internal readonly XmlNode node; - internal readonly int index; + internal readonly XmlNode Node; + internal readonly int Index; internal Match(XmlNode match, int index) { - this.node = match; - this.index = index; + Node = match; + Index = index; } } ]]></literal> Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-08-13 13:10:16 UTC (rev 425) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-08-18 14:06:06 UTC (rev 426) @@ -490,6 +490,14 @@ assertEquals(ComparisonResult.CRITICAL, d.compareNodes(e1, e2)); assertEquals(1, ex.invoked); + // symmetric? + d = new DOMDifferenceEngine(); + ex = new DiffExpecter(ComparisonType.CHILD_LOOKUP); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(ev); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(e2, e1)); + assertEquals(1, ex.invoked); + Element c2 = doc.createElement("bar"); e2.appendChild(c2); d = new DOMDifferenceEngine(); Modified: trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-13 13:10:16 UTC (rev 425) +++ trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-18 14:06:06 UTC (rev 426) @@ -482,6 +482,14 @@ Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(e1, e2)); Assert.AreEqual(1, ex.invoked); + // symmetric? + d = new DOMDifferenceEngine(); + ex = new DiffExpecter(ComparisonType.CHILD_LOOKUP); + d.DifferenceListener += ex.ComparisonPerformed; + d.DifferenceEvaluator = ev; + Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(e2, e1)); + Assert.AreEqual(1, ex.invoked); + XmlElement c2 = doc.CreateElement("bar"); e2.AppendChild(c2); d = new DOMDifferenceEngine(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-08-18 14:27:34
|
Revision: 427 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=427&view=rev Author: bodewig Date: 2010-08-18 14:27:27 +0000 (Wed, 18 Aug 2010) Log Message: ----------- allow CData to match Text nodes in recursion Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-08-18 14:06:06 UTC (rev 426) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-08-18 14:27:27 UTC (rev 427) @@ -332,7 +332,7 @@ compare(new Comparison(ComparisonType.NODE_TYPE, n1, null, n1.getNodeType(), n2, null, n2.getNodeType())); - return r == ComparisonResult.EQUAL; + return r != ComparisonResult.CRITICAL; } private class Match { Modified: trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-18 14:06:06 UTC (rev 426) +++ trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-18 14:27:27 UTC (rev 427) @@ -332,7 +332,7 @@ Compare(new Comparison(ComparisonType.NODE_TYPE, n1, null, n1.NodeType, n2, null, n2.NodeType)); - return r == ComparisonResult.EQUAL; + return r != ComparisonResult.CRITICAL; } internal class Match { Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-08-18 14:06:06 UTC (rev 426) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-08-18 14:27:27 UTC (rev 427) @@ -505,6 +505,19 @@ d.addDifferenceListener(ex); d.setDifferenceEvaluator(ev); assertEquals(ComparisonResult.EQUAL, d.compareNodes(e1, e2)); + assertEquals(ComparisonResult.EQUAL, d.compareNodes(e2, e1)); assertEquals(0, ex.invoked); } + + @Test public void textAndCDataMatchRecursively() { + Element e1 = doc.createElement("foo"); + Element e2 = doc.createElement("foo"); + Text fooText = doc.createTextNode("foo"); + e1.appendChild(fooText); + CDATASection fooCDATASection = doc.createCDATASection("foo"); + e2.appendChild(fooCDATASection); + DOMDifferenceEngine d = new DOMDifferenceEngine(); + assertEquals(ComparisonResult.EQUAL, d.compareNodes(e1, e2)); + assertEquals(ComparisonResult.EQUAL, d.compareNodes(e2, e1)); + } } Modified: trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-18 14:06:06 UTC (rev 426) +++ trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-18 14:27:27 UTC (rev 427) @@ -497,8 +497,21 @@ d.DifferenceListener += ex.ComparisonPerformed; d.DifferenceEvaluator = ev; Assert.AreEqual(ComparisonResult.EQUAL, d.CompareNodes(e1, e2)); + Assert.AreEqual(ComparisonResult.EQUAL, d.CompareNodes(e2, e1)); Assert.AreEqual(0, ex.invoked); } + [Test] + public void textAndCDataMatchRecursively() { + XmlElement e1 = doc.CreateElement("foo"); + XmlElement e2 = doc.CreateElement("foo"); + XmlText fooText = doc.CreateTextNode("foo"); + e1.AppendChild(fooText); + XmlCDataSection fooCDATASection = doc.CreateCDataSection("foo"); + e2.AppendChild(fooCDATASection); + DOMDifferenceEngine d = new DOMDifferenceEngine(); + Assert.AreEqual(ComparisonResult.EQUAL, d.CompareNodes(e1, e2)); + Assert.AreEqual(ComparisonResult.EQUAL, d.CompareNodes(e2, e1)); + } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-08-18 14:45:56
|
Revision: 428 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=428&view=rev Author: bodewig Date: 2010-08-18 14:45:50 +0000 (Wed, 18 Aug 2010) Log Message: ----------- use element selector during recursion Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-08-18 14:27:27 UTC (rev 427) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-08-18 14:45:50 UTC (rev 428) @@ -328,6 +328,10 @@ } private boolean nodesMatch(final Node n1, final Node n2) { + if (n1 instanceof Element && n2 instanceof Element) { + return getElementSelector() + .canBeCompared((Element) n1, (Element) n2); + } ComparisonResult r = compare(new Comparison(ComparisonType.NODE_TYPE, n1, null, n1.getNodeType(), Modified: trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-18 14:27:27 UTC (rev 427) +++ trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-18 14:45:50 UTC (rev 428) @@ -328,6 +328,9 @@ } private bool NodesMatch(XmlNode n1, XmlNode n2) { + if (n1 is XmlElement && n2 is XmlElement) { + return ElementSelector(n1 as XmlElement, n2 as XmlElement); + } ComparisonResult r = Compare(new Comparison(ComparisonType.NODE_TYPE, n1, null, n1.NodeType, Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-08-18 14:27:27 UTC (rev 427) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-08-18 14:45:50 UTC (rev 428) @@ -520,4 +520,27 @@ assertEquals(ComparisonResult.EQUAL, d.compareNodes(e1, e2)); assertEquals(ComparisonResult.EQUAL, d.compareNodes(e2, e1)); } + + @Test public void recursionUsesElementSelector() { + Element e1 = doc.createElement("foo"); + Element e2 = doc.createElement("foo"); + Element e3 = doc.createElement("bar"); + e1.appendChild(e3); + Element e4 = doc.createElement("baz"); + e2.appendChild(e4); + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.ELEMENT_TAG_NAME); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(e1, e2)); + assertEquals(1, ex.invoked); + + d = new DOMDifferenceEngine(); + d.setElementSelector(ElementSelectors.byName); + ex = new DiffExpecter(ComparisonType.CHILD_LOOKUP); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(DifferenceEvaluators.DefaultStopWhenDifferent); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(e1, e2)); + assertEquals(1, ex.invoked); + } } Modified: trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-18 14:27:27 UTC (rev 427) +++ trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-18 14:45:50 UTC (rev 428) @@ -502,7 +502,7 @@ } [Test] - public void textAndCDataMatchRecursively() { + public void TextAndCDataMatchRecursively() { XmlElement e1 = doc.CreateElement("foo"); XmlElement e2 = doc.CreateElement("foo"); XmlText fooText = doc.CreateTextNode("foo"); @@ -513,5 +513,31 @@ Assert.AreEqual(ComparisonResult.EQUAL, d.CompareNodes(e1, e2)); Assert.AreEqual(ComparisonResult.EQUAL, d.CompareNodes(e2, e1)); } + + [Test] + public void RecursionUsesElementSelector() { + XmlElement e1 = doc.CreateElement("foo"); + XmlElement e2 = doc.CreateElement("foo"); + XmlElement e3 = doc.CreateElement("bar"); + e1.AppendChild(e3); + XmlElement e4 = doc.CreateElement("baz"); + e2.AppendChild(e4); + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.ELEMENT_TAG_NAME); + d.DifferenceListener += ex.ComparisonPerformed; + d.DifferenceEvaluator = + DifferenceEvaluators.DefaultStopWhenDifferent; + Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(e1, e2)); + Assert.AreEqual(1, ex.invoked); + + d = new DOMDifferenceEngine(); + d.ElementSelector = ElementSelectors.ByName; + ex = new DiffExpecter(ComparisonType.CHILD_LOOKUP); + d.DifferenceListener += ex.ComparisonPerformed; + d.DifferenceEvaluator = + DifferenceEvaluators.DefaultStopWhenDifferent; + Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(e1, e2)); + Assert.AreEqual(1, ex.invoked); + } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-08-19 14:04:23
|
Revision: 429 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=429&view=rev Author: bodewig Date: 2010-08-19 14:04:16 +0000 (Thu, 19 Aug 2010) Log Message: ----------- treat XML NS Declarations and XML Schema Instance Namespaces differently Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-08-18 14:45:50 UTC (rev 428) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-08-19 14:04:16 UTC (rev 429) @@ -17,9 +17,12 @@ summary="Difference engine based on DOM." extends="AbstractDifferenceEngine"> + <import reference="java.util.HashSet"/> + <import reference="java.util.LinkedList"/> <import reference="java.util.List"/> <import reference="java.util.Set"/> <import reference="java.util.TreeSet"/> + <import reference="javax.xml.XMLConstants"/> <import reference="javax.xml.transform.Source"/> <import reference="net.sf.xmlunit.util.Convert"/> <import reference="net.sf.xmlunit.util.IterableNodeList"/> @@ -180,51 +183,41 @@ <lastResultDef/> <compare type="ELEMENT_TAG_NAME" property="getTagName()"/> <literal><![CDATA[ - NamedNodeMap controlAttributes = control.getAttributes(); - NamedNodeMap testAttributes = test.getAttributes(); - final int controlAttrLen = controlAttributes.getLength(); - final int testAttrLen = testAttributes.getLength(); + Attributes controlAttributes = splitAttributes(control.getAttributes()); + Attributes testAttributes = splitAttributes(test.getAttributes()); + Set<Attr> foundTestAttributes = new HashSet<Attr>(); ]]></literal> <compareExpr type="ELEMENT_NUM_ATTRIBUTES" - controlExpr="controlAttrLen" - testExpr="testAttrLen"/> + controlExpr="controlAttributes.remainingAttributes.size()" + testExpr="testAttributes.remainingAttributes.size()"/> <literal><![CDATA[ - for (int i = 0; i < controlAttrLen; i++) { - final Attr controlAttr = (Attr) controlAttributes.item(i); - final Attr testAttr = findMatchingAttr(testAttributes, controlAttr); + for (Attr controlAttr : controlAttributes.remainingAttributes) { + final Attr testAttr = + findMatchingAttr(testAttributes.remainingAttributes, + controlAttr); ]]></literal> <compareExpr type="ATTR_NAME_LOOKUP" controlExpr="Boolean.TRUE" testExpr="Boolean.valueOf(testAttr != null)"/> <literal><![CDATA[ - } -]]></literal> - <literal><![CDATA[ - for (int i = 0; i < testAttrLen; i++) { - final Attr testAttr = (Attr) testAttributes.item(i); - final Attr controlAttr = findMatchingAttr(controlAttributes, - testAttr); -]]></literal> - <compareExpr type="ATTR_NAME_LOOKUP" - controlExpr="Boolean.valueOf(controlAttr != null)" - testExpr="Boolean.TRUE"/> - <literal><![CDATA[ - } -]]></literal> - <literal><![CDATA[ - for (int i = 0; i < controlAttrLen; i++) { - final Attr controlAttr = (Attr) controlAttributes.item(i); - final Attr testAttr = findMatchingAttr(testAttributes, controlAttr); if (testAttr != null) { ]]></literal> <compareMethodExpr method="compareNodes" controlExpr="controlAttr" testExpr="testAttr"/> <literal><![CDATA[ + foundTestAttributes.add(testAttr); } } ]]></literal> <literal><![CDATA[ + for (Attr testAttr : testAttributes.remainingAttributes) { +]]></literal> + <compareExpr type="ATTR_NAME_LOOKUP" + controlExpr="Boolean.valueOf(foundTestAttributes.contains(testAttr))" + testExpr="Boolean.TRUE"/> + <literal><![CDATA[ + } return lastResult; } @@ -300,14 +293,58 @@ test, null, test.getValue())); } - private static Attr findMatchingAttr(final NamedNodeMap map, + private static Attributes splitAttributes(final NamedNodeMap map) { + Attr sLoc = (Attr) map.getNamedItemNS(XMLConstants + .W3C_XML_SCHEMA_INSTANCE_NS_URI, + "schemaLocation"); + Attr nNsLoc = (Attr) map.getNamedItemNS(XMLConstants + .W3C_XML_SCHEMA_INSTANCE_NS_URI, + "noNamespaceSchemaLocation"); + List<Attr> rest = new LinkedList<Attr>(); + final int len = map.getLength(); + for (int i = 0; i < len; i++) { + Attr a = (Attr) map.item(i); + if (!XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(a.getNamespaceURI()) + && + !XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI + .equals(a.getNamespaceURI())) { + rest.add(a); + } + } + return new Attributes(sLoc, nNsLoc, rest); + } + + private static class Attributes { + private final Attr schemaLocation; + private final Attr noNamespaceSchemaLocation; + private final List<Attr> remainingAttributes; + private Attributes(Attr schemaLocation, Attr noNamespaceSchemaLocation, + List<Attr> remainingAttributes) { + this.schemaLocation = schemaLocation; + this.noNamespaceSchemaLocation = noNamespaceSchemaLocation; + this.remainingAttributes = remainingAttributes; + } + } + + private static Attr findMatchingAttr(final List<Attr> attrs, final Attr attrToMatch) { - if (attrToMatch.getNamespaceURI() == null) { - return (Attr) map.getNamedItem(attrToMatch.getName()); - } else { - return (Attr) map.getNamedItemNS(attrToMatch.getNamespaceURI(), - attrToMatch.getLocalName()); + final boolean hasNs = attrToMatch.getNamespaceURI() != null; + final String nsToMatch = attrToMatch.getNamespaceURI(); + final String nameToMatch = hasNs ? attrToMatch.getLocalName() + : attrToMatch.getName(); + for (Attr a : attrs) { + if (((!hasNs && a.getNamespaceURI() == null) + || + (hasNs && nsToMatch.equals(a.getNamespaceURI()))) + && + ((hasNs && nameToMatch.equals(a.getLocalName())) + || + (!hasNs && nameToMatch.equals(a.getName()))) + ) { + return a; + } } + return null; } private Match findMatchingNode(final Node searchFor, Modified: trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-18 14:45:50 UTC (rev 428) +++ trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-19 14:04:16 UTC (rev 429) @@ -20,9 +20,12 @@ <import reference="System"/> <import reference="System.Collections.Generic"/> <import reference="System.Xml"/> + <import reference="System.Xml.Schema"/> <literal><![CDATA[ + private static readonly object DUMMY = new object(); + public override void Compare(ISource control, ISource test) { if (control == null) { throw new ArgumentNullException("control"); @@ -171,55 +174,46 @@ <lastResultDef/> <compare type="ELEMENT_TAG_NAME" property="Name"/> <literal><![CDATA[ - XmlAttributeCollection controlAttributes = control.Attributes; - XmlAttributeCollection testAttributes = test.Attributes; - int controlAttrLen = controlAttributes.Count; - int testAttrLen = testAttributes.Count; + Attributes controlAttributes = SplitAttributes(control.Attributes); + Attributes testAttributes = SplitAttributes(test.Attributes); + IDictionary<XmlAttribute, object> foundTestAttributes = + new Dictionary<XmlAttribute, object>(); ]]></literal> <compareExpr type="ELEMENT_NUM_ATTRIBUTES" - controlExpr="controlAttrLen" - testExpr="testAttrLen"/> + controlExpr="controlAttributes.RemainingAttributes.Count" + testExpr="testAttributes.RemainingAttributes.Count"/> <literal><![CDATA[ - for (int i = 0; i < controlAttrLen; i++) { - XmlAttribute controlAttr = controlAttributes[i]; - XmlAttribute testAttr = FindMatchingAttr(testAttributes, - controlAttr); + foreach (XmlAttribute controlAttr in controlAttributes.RemainingAttributes) { + XmlAttribute testAttr = + FindMatchingAttr(testAttributes.RemainingAttributes, + controlAttr); ]]></literal> <compareExpr type="ATTR_NAME_LOOKUP" controlExpr="true" testExpr="testAttr != null"/> <literal><![CDATA[ - } + if (testAttr != null) { ]]></literal> + <compareMethodExpr method="CompareNodes" + controlExpr="controlAttr" + testExpr="testAttr"/> <literal><![CDATA[ - for (int i = 0; i < testAttrLen; i++) { - XmlAttribute testAttr = testAttributes[i]; - XmlAttribute controlAttr = FindMatchingAttr(controlAttributes, - testAttr); + foundTestAttributes[testAttr] = DUMMY; + } + } ]]></literal> + <literal><![CDATA[ + foreach (XmlAttribute testAttr in testAttributes.RemainingAttributes) { +]]></literal> <compareExpr type="ATTR_NAME_LOOKUP" - controlExpr="controlAttr != null" + controlExpr="foundTestAttributes.ContainsKey(testAttr)" testExpr="true"/> <literal><![CDATA[ - } + } ]]></literal> <literal><![CDATA[ - for (int i = 0; i < controlAttrLen; i++) { - XmlAttribute controlAttr = controlAttributes[i]; - XmlAttribute testAttr = FindMatchingAttr(testAttributes, - controlAttr); - if (testAttr != null) { -]]></literal> - <compareMethodExpr method="CompareNodes" - controlExpr="controlAttr" - testExpr="testAttr"/> - <literal><![CDATA[ - } + return lastResult; } -]]></literal> - <literal><![CDATA[ - return lastResult; - } private ComparisonResult CompareProcessingInstructions(XmlProcessingInstruction control, @@ -233,8 +227,6 @@ test, null, test.Data)); } - private static readonly object DUMMY = new object(); - private ComparisonResult CompareNodeLists(XmlNodeList control, XmlNodeList test) { IList<XmlNode> controlList = @@ -299,15 +291,56 @@ test, null, test.Value)); } - private static XmlAttribute FindMatchingAttr(XmlAttributeCollection map, + private static Attributes SplitAttributes(XmlAttributeCollection map) { + XmlAttribute sLoc = map.GetNamedItem("schemaLocation", + XmlSchema.InstanceNamespace) + as XmlAttribute; + XmlAttribute nNsLoc = map.GetNamedItem("noNamespaceSchemaLocation", + XmlSchema.InstanceNamespace) + as XmlAttribute; + List<XmlAttribute> rest = new List<XmlAttribute>(); + foreach (XmlAttribute a in map) { + if (XmlSchema.InstanceNamespace != a.NamespaceURI + && + "http://www.w3.org/2000/xmlns/" != a.NamespaceURI) { + rest.Add(a); + } + } + return new Attributes(sLoc, nNsLoc, rest); + } + + internal class Attributes { + internal readonly XmlAttribute SchemaLocation; + internal readonly XmlAttribute NoNamespaceSchemaLocation; + internal readonly IList<XmlAttribute> RemainingAttributes; + internal Attributes(XmlAttribute schemaLocation, + XmlAttribute noNamespaceSchemaLocation, + IList<XmlAttribute> remainingAttributes) { + this.SchemaLocation = schemaLocation; + this.NoNamespaceSchemaLocation = noNamespaceSchemaLocation; + this.RemainingAttributes = remainingAttributes; + } + } + + private static XmlAttribute FindMatchingAttr(IList<XmlAttribute> attrs, XmlAttribute attrToMatch) { - if (attrToMatch.NamespaceURI == null) { - return map.GetNamedItem(attrToMatch.Name) as XmlAttribute; - } else { - return map.GetNamedItem(attrToMatch.LocalName, - attrToMatch.NamespaceURI) - as XmlAttribute; + bool hasNs = !string.IsNullOrEmpty(attrToMatch.NamespaceURI); + string nsToMatch = attrToMatch.NamespaceURI; + string nameToMatch = hasNs ? attrToMatch.LocalName + : attrToMatch.Name; + foreach (XmlAttribute a in attrs) { + if (((!hasNs && string.IsNullOrEmpty(a.NamespaceURI)) + || + (hasNs && nsToMatch == a.NamespaceURI)) + && + ((hasNs && nameToMatch == a.LocalName) + || + (!hasNs && nameToMatch == a.Name)) + ) { + return a; + } } + return null; } private Match FindMatchingNode(XmlNode searchFor, Modified: trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-18 14:45:50 UTC (rev 428) +++ trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-19 14:04:16 UTC (rev 429) @@ -423,7 +423,8 @@ + " with outcome " + r + " and values '" + comp.ControlDetails.Value + "' and '" - + comp.TestDetails.Value + "'"); + + comp.TestDetails.Value + "'" + + " on '" + comp.ControlDetails.Target + "'"); }; d.DifferenceEvaluator = DifferenceEvaluators.DefaultStopWhenDifferent; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-08-19 14:28:57
|
Revision: 430 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=430&view=rev Author: bodewig Date: 2010-08-19 14:28:50 +0000 (Thu, 19 Aug 2010) Log Message: ----------- schema location comparisons Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-08-19 14:04:16 UTC (rev 429) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-08-19 14:28:50 UTC (rev 430) @@ -218,6 +218,16 @@ testExpr="Boolean.TRUE"/> <literal><![CDATA[ } +]]></literal> + <compareExpr type="SCHEMA_LOCATION" + controlExpr="controlAttributes.schemaLocation != null ? controlAttributes.schemaLocation.getValue() : null" + testExpr="testAttributes.schemaLocation != null ? testAttributes.schemaLocation.getValue() : null" + /> + <compareExpr type="NO_NAMESPACE_SCHEMA_LOCATION" + controlExpr="controlAttributes.noNamespaceSchemaLocation != null ? controlAttributes.noNamespaceSchemaLocation.getValue() : null" + testExpr="testAttributes.noNamespaceSchemaLocation != null ? testAttributes.noNamespaceSchemaLocation.getValue() : null" + /> + <literal><![CDATA[ return lastResult; } @@ -320,9 +330,9 @@ private final List<Attr> remainingAttributes; private Attributes(Attr schemaLocation, Attr noNamespaceSchemaLocation, List<Attr> remainingAttributes) { - this.schemaLocation = schemaLocation; + this.schemaLocation = schemaLocation; this.noNamespaceSchemaLocation = noNamespaceSchemaLocation; - this.remainingAttributes = remainingAttributes; + this.remainingAttributes = remainingAttributes; } } Modified: trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-19 14:04:16 UTC (rev 429) +++ trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-19 14:28:50 UTC (rev 430) @@ -211,6 +211,14 @@ <literal><![CDATA[ } ]]></literal> + <compareExpr type="SCHEMA_LOCATION" + controlExpr="controlAttributes.SchemaLocation != null ? controlAttributes.SchemaLocation.Value : null" + testExpr="testAttributes.SchemaLocation != null ? testAttributes.SchemaLocation.Value : null" + /> + <compareExpr type="NO_NAMESPACE_SCHEMA_LOCATION" + controlExpr="controlAttributes.NoNamespaceSchemaLocation != null ? controlAttributes.NoNamespaceSchemaLocation.Value : null" + testExpr="testAttributes.NoNamespaceSchemaLocation != null ? testAttributes.NoNamespaceSchemaLocation.Value : null" + /> <literal><![CDATA[ return lastResult; } @@ -316,9 +324,9 @@ internal Attributes(XmlAttribute schemaLocation, XmlAttribute noNamespaceSchemaLocation, IList<XmlAttribute> remainingAttributes) { - this.SchemaLocation = schemaLocation; + this.SchemaLocation = schemaLocation; this.NoNamespaceSchemaLocation = noNamespaceSchemaLocation; - this.RemainingAttributes = remainingAttributes; + this.RemainingAttributes = remainingAttributes; } } Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-08-19 14:04:16 UTC (rev 429) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-08-19 14:28:50 UTC (rev 430) @@ -543,4 +543,53 @@ assertEquals(ComparisonResult.CRITICAL, d.compareNodes(e1, e2)); assertEquals(1, ex.invoked); } + + @Test public void schemaLocationDifferences() { + Element e1 = doc.createElement("foo"); + Element e2 = doc.createElement("foo"); + e1.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", + "schemaLocation", "somewhere"); + e2.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", + "schemaLocation", "somewhere else"); + + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.SCHEMA_LOCATION); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(new DifferenceEvaluator() { + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult outcome) { + if (comparison.getType() == ComparisonType.SCHEMA_LOCATION) { + assertEquals(ComparisonResult.DIFFERENT, outcome); + return ComparisonResult.CRITICAL; + } + assertEquals(ComparisonResult.EQUAL, outcome); + return ComparisonResult.EQUAL; + } + }); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(e1, e2)); + assertEquals(1, ex.invoked); + + e1 = doc.createElement("foo"); + e2 = doc.createElement("foo"); + e1.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", + "noNamespaceSchemaLocation", "somewhere"); + e2.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", + "noNamespaceSchemaLocation", "somewhere else"); + d = new DOMDifferenceEngine(); + ex = new DiffExpecter(ComparisonType.NO_NAMESPACE_SCHEMA_LOCATION); + d.addDifferenceListener(ex); + d.setDifferenceEvaluator(new DifferenceEvaluator() { + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult outcome) { + if (comparison.getType() == ComparisonType.NO_NAMESPACE_SCHEMA_LOCATION) { + assertEquals(ComparisonResult.DIFFERENT, outcome); + return ComparisonResult.CRITICAL; + } + assertEquals(ComparisonResult.EQUAL, outcome); + return ComparisonResult.EQUAL; + } + }); + assertEquals(ComparisonResult.CRITICAL, d.compareNodes(e1, e2)); + assertEquals(1, ex.invoked); + } } Modified: trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-19 14:04:16 UTC (rev 429) +++ trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-19 14:28:50 UTC (rev 430) @@ -540,5 +540,55 @@ Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(e1, e2)); Assert.AreEqual(1, ex.invoked); } + + [Test] + public void SchemaLocationDifferences() { + XmlElement e1 = doc.CreateElement("foo"); + XmlElement e2 = doc.CreateElement("foo"); + e1.SetAttribute("schemaLocation", + "http://www.w3.org/2001/XMLSchema-instance", + "somewhere"); + e2.SetAttribute("schemaLocation", + "http://www.w3.org/2001/XMLSchema-instance", + "somewhere else"); + + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.SCHEMA_LOCATION); + d.DifferenceListener += ex.ComparisonPerformed; + d.DifferenceEvaluator = delegate(Comparison comparison, + ComparisonResult outcome) { + if (comparison.Type == ComparisonType.SCHEMA_LOCATION) { + Assert.AreEqual(ComparisonResult.DIFFERENT, outcome); + return ComparisonResult.CRITICAL; + } + Assert.AreEqual(ComparisonResult.EQUAL, outcome); + return ComparisonResult.EQUAL; + }; + Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(e1, e2)); + Assert.AreEqual(1, ex.invoked); + + e1 = doc.CreateElement("foo"); + e2 = doc.CreateElement("foo"); + e1.SetAttribute("noNamespaceSchemaLocation", + "http://www.w3.org/2001/XMLSchema-instance", + "somewhere"); + e2.SetAttribute("noNamespaceSchemaLocation", + "http://www.w3.org/2001/XMLSchema-instance", + "somewhere else"); + d = new DOMDifferenceEngine(); + ex = new DiffExpecter(ComparisonType.NO_NAMESPACE_SCHEMA_LOCATION); + d.DifferenceListener += ex.ComparisonPerformed; + d.DifferenceEvaluator = delegate(Comparison comparison, + ComparisonResult outcome) { + if (comparison.Type == ComparisonType.NO_NAMESPACE_SCHEMA_LOCATION) { + Assert.AreEqual(ComparisonResult.DIFFERENT, outcome); + return ComparisonResult.CRITICAL; + } + Assert.AreEqual(ComparisonResult.EQUAL, outcome); + return ComparisonResult.EQUAL; + }; + Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(e1, e2)); + Assert.AreEqual(1, ex.invoked); + } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-08-19 14:52:34
|
Revision: 431 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=431&view=rev Author: bodewig Date: 2010-08-19 14:52:28 +0000 (Thu, 19 Aug 2010) Log Message: ----------- XML Declaration differences for .NET as well Modified Paths: -------------- trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs Modified: trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-19 14:28:50 UTC (rev 430) +++ trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-19 14:52:28 UTC (rev 431) @@ -143,16 +143,13 @@ testExpr="testDt"/> <literal><![CDATA[ } + XmlDeclaration controlDecl = control.FirstChild as XmlDeclaration; + XmlDeclaration testDecl = test.FirstChild as XmlDeclaration; ]]></literal> -<!-- - <compare type="XML_VERSION" property="getXmlVersion()"/> - <compare type="XML_STANDALONE" property="getXmlStandalone()"/> + <compareMethodExpr method="CompareDeclarations" + controlExpr="controlDecl" + testExpr="testDecl"/> <literal><![CDATA[ - return Compare(new Comparison(ComparisonType.XML_ENCODING, - control, null, control.getXmlEncoding(), - test, null, test.getXmlEncoding())); ---> - <literal><![CDATA[ return lastResult; } @@ -168,6 +165,37 @@ test, null, test.SystemId)); } + private ComparisonResult CompareDeclarations(XmlDeclaration control, + XmlDeclaration test) { +]]></literal> + <lastResultDef/> + <literal><![CDATA[ + string controlVersion = + control == null ? "1.0" : control.Version; + string testVersion = + test == null ? "1.0" : test.Version; +]]></literal> + <compareExpr type="XML_VERSION" + controlExpr="controlVersion" + testExpr="testVersion"/> + <literal><![CDATA[ + string controlStandalone = + control == null ? string.Empty : control.Standalone; + string testStandalone = + test == null ? string.Empty : test.Standalone; +]]></literal> + <compareExpr type="XML_STANDALONE" + controlExpr="controlStandalone" + testExpr="testStandalone"/> + <literal><![CDATA[ + string controlEncoding = + control != null ? control.Encoding : string.Empty; + string testEncoding = test != null ? test.Encoding : string.Empty; + return Compare(new Comparison(ComparisonType.XML_ENCODING, + control, null, controlEncoding, + test, null, testEncoding)); + } + private ComparisonResult CompareElements(XmlElement control, XmlElement test) { ]]></literal> Modified: trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-19 14:28:50 UTC (rev 430) +++ trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-19 14:52:28 UTC (rev 431) @@ -265,9 +265,7 @@ Assert.AreEqual(1, ex.invoked); #endif -#if false // need a way to figure out the XML_* differences - - // .NET doesn't like XML 1.1 anyway +#if false // .NET doesn't like XML 1.1 anyway d = new DOMDifferenceEngine(); ex = new DiffExpecter(ComparisonType.XML_VERSION); d.DifferenceListener += ex.ComparisonPerformed; @@ -287,7 +285,6 @@ Assert.AreEqual(1, ex.invoked); #endif -#if false // need a way to figure out the XML_* differences d = new DOMDifferenceEngine(); ex = new DiffExpecter(ComparisonType.XML_STANDALONE); d.DifferenceListener += ex.ComparisonPerformed; @@ -305,9 +302,7 @@ Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(d1, d2)); Assert.AreEqual(1, ex.invoked); -#endif -#if false // need a way to figure out the XML_* differences d = new DOMDifferenceEngine(); ex = new DiffExpecter(ComparisonType.XML_ENCODING); d.DifferenceListener += ex.ComparisonPerformed; @@ -332,7 +327,6 @@ Assert.AreEqual(ComparisonResult.CRITICAL, d.CompareNodes(d1, d2)); Assert.AreEqual(1, ex.invoked); -#endif } [Test] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-08-20 10:07:55
|
Revision: 432 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=432&view=rev Author: bodewig Date: 2010-08-20 10:07:48 +0000 (Fri, 20 Aug 2010) Log Message: ----------- prepare for XPath tracking in difference engine Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/AbstractDifferenceEngine.java trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEngine.java trunk/xmlunit/src/main/net-core/diff/AbstractDifferenceEngine.cs trunk/xmlunit/src/main/net-core/diff/IDifferenceEngine.cs Added Paths: ----------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/XPathContext.java trunk/xmlunit/src/main/net-core/diff/XPathContext.cs trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/XPathContextTest.java trunk/xmlunit/src/tests/net-core/diff/XPathContextTest.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/AbstractDifferenceEngine.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/AbstractDifferenceEngine.java 2010-08-19 14:52:28 UTC (rev 431) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/AbstractDifferenceEngine.java 2010-08-20 10:07:48 UTC (rev 432) @@ -13,6 +13,9 @@ */ package net.sf.xmlunit.diff; +import java.util.Collections; +import java.util.Map; + /** * Useful base-implementation of some parts of the DifferenceEngine * interface. @@ -22,6 +25,7 @@ new ComparisonListenerSupport(); private ElementSelector elementSelector = ElementSelectors.Default; private DifferenceEvaluator diffEvaluator = DifferenceEvaluators.Default; + private Map<String, String> uri2Prefix = Collections.emptyMap(); public void addComparisonListener(ComparisonListener l) { if (l == null) { @@ -68,6 +72,10 @@ return diffEvaluator; } + public void setNamespaceContext(Map<String, String> uri2Prefix) { + this.uri2Prefix = Collections.unmodifiableMap(uri2Prefix); + } + /** * Compares the detail values for object equality, lets the * difference evaluator evaluate the result, notifies all Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEngine.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEngine.java 2010-08-19 14:52:28 UTC (rev 431) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEngine.java 2010-08-20 10:07:48 UTC (rev 432) @@ -13,6 +13,7 @@ */ package net.sf.xmlunit.diff; +import java.util.Map; import javax.xml.transform.Source; /** @@ -48,6 +49,18 @@ void setDifferenceEvaluator(DifferenceEvaluator e); /** + * Establish a namespace context that will be used in {@link + * Comparison.Detail#getXPath Comparison.Detail#getXPath}. + * + * <p>Without a namespace context (or with an empty context) the + * XPath expressions will only use local names for elements and + * attributes.</p> + * + * @param uri2Prefix maps from namespace URI to prefix. + */ + void setNamespaceContext(Map<String, String> uri2Prefix); + + /** * Compares two pieces of XML and invokes the registered listeners. */ void compare(Source control, Source test); Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/XPathContext.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/XPathContext.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/XPathContext.java 2010-08-20 10:07:48 UTC (rev 432) @@ -0,0 +1,148 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package net.sf.xmlunit.diff; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Deque; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import javax.xml.namespace.QName; +import net.sf.xmlunit.util.Nodes; +import org.w3c.dom.Node; + +public class XPathContext { + private final Deque<Level> path = new LinkedList<Level>(); + private final Map<String, String> uri2Prefix; + + public XPathContext() { + this(null); + } + + public XPathContext(Map<String, String> uri2Prefix) { + if (uri2Prefix == null) { + this.uri2Prefix = Collections.emptyMap(); + } else { + this.uri2Prefix = Collections.unmodifiableMap(uri2Prefix); + } + path.addLast(new Level("")); + } + + public void navigateToChild(int index) { + path.addLast(path.getLast().children.get(index)); + } + + public void navigateToAttribute(QName attribute) { + path.addLast(path.getLast().attributes.get(attribute)); + } + + public void navigateToParent() { + path.removeLast(); + } + + public void registerAttributes(Iterable<? extends QName> attributes) { + Level current = path.getLast(); + for (QName attribute : attributes) { + current.attributes.put(attribute, + new Level("@" + getName(attribute))); + } + } + + public void registerChildren(Iterable<? extends NodeInfo> children) { + Level current = path.getLast(); + int comments, pis, texts; + comments = pis = texts = 0; + Map<String, Integer> elements = new HashMap<String, Integer>(); + for (NodeInfo child : children) { + Level l = null; + switch (child.getType()) { + case Node.COMMENT_NODE: + l = new Level("comment()[" + (++comments) + "]"); + break; + case Node.PROCESSING_INSTRUCTION_NODE: + l = new Level("processing-instruction()[" + (++pis) + "]"); + break; + case Node.CDATA_SECTION_NODE: + case Node.TEXT_NODE: + l = new Level("text()[" + (++texts) + "]"); + break; + case Node.ELEMENT_NODE: + String name = getName(child.getName()); + Integer old = elements.get(name); + int index = old == null ? 0 : old.intValue(); + l = new Level(name + "[" + (++index) + "]"); + elements.put(name, Integer.valueOf(index)); + break; + default: + throw new IllegalArgumentException("unknown node type " + + child.getType()); + } + current.children.add(l); + } + } + + public String getXPath() { + StringBuilder sb = new StringBuilder(); + boolean first = true, second = false; + for (Level l : path) { + if (!second) { + sb.append("/"); + } + sb.append(l.expression); + if (first) { + second = true; + } else { + second = false; + } + first = false; + } + return sb.toString(); + } + + private String getName(QName name) { + String ns = name.getNamespaceURI(); + String p = null; + if (ns != null) { + p = uri2Prefix.get(ns); + } + return (p == null ? "" : p + ":") + name.getLocalPart(); + } + + private static class Level { + private final String expression; + private List<Level> children = new ArrayList<Level>(); + private Map<QName, Level> attributes = new HashMap<QName, Level>(); + private Level(String expression) { + this.expression = expression; + } + } + + public static interface NodeInfo { + QName getName(); + short getType(); + } + + public static final class DOMNodeInfo implements NodeInfo { + private QName name; + private short type; + public DOMNodeInfo(Node n) { + name = Nodes.getQName(n); + type = n.getNodeType(); + } + public QName getName() { return name; } + public short getType() { return type; } + } +} Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/XPathContext.java ___________________________________________________________________ Added: svn:eol-style + native Modified: trunk/xmlunit/src/main/net-core/diff/AbstractDifferenceEngine.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/AbstractDifferenceEngine.cs 2010-08-19 14:52:28 UTC (rev 431) +++ trunk/xmlunit/src/main/net-core/diff/AbstractDifferenceEngine.cs 2010-08-20 10:07:48 UTC (rev 432) @@ -13,6 +13,7 @@ */ using System; +using System.Collections.Generic; namespace net.sf.xmlunit.diff { @@ -53,6 +54,14 @@ public abstract void Compare(ISource control, ISource test); + private IDictionary<string, string> namespaceContext; + + public IDictionary<string, string> NamespaceContext { + set { + namespaceContext = value; + } + } + /// <summary> /// Compares the detail values for object equality, lets the /// difference evaluator evaluate the result, notifies all Modified: trunk/xmlunit/src/main/net-core/diff/IDifferenceEngine.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/IDifferenceEngine.cs 2010-08-19 14:52:28 UTC (rev 431) +++ trunk/xmlunit/src/main/net-core/diff/IDifferenceEngine.cs 2010-08-20 10:07:48 UTC (rev 432) @@ -12,6 +12,8 @@ limitations under the License. */ +using System.Collections.Generic; + namespace net.sf.xmlunit.diff { /// <summary> @@ -47,6 +49,17 @@ DifferenceEvaluator DifferenceEvaluator { set; } /// <summary> + /// Establish a namespace context mapping from URI to prefix + /// that will be used in Comparison.Detail.XPath. + /// </summary> + /// <remarks> + /// Without a namespace context (or with an empty context) the + /// XPath expressions will only use local names for elements and + /// attributes. + /// </remarks> + IDictionary<string, string> NamespaceContext { set; } + + /// <summary> /// Compares two pieces of XML and invokes the registered listeners. /// </summary> void Compare(ISource control, ISource test); Added: trunk/xmlunit/src/main/net-core/diff/XPathContext.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/XPathContext.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/diff/XPathContext.cs 2010-08-20 10:07:48 UTC (rev 432) @@ -0,0 +1,150 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +using System; +using System.Collections.Generic; +using System.Text; +using System.Xml; +using net.sf.xmlunit.util; + +namespace net.sf.xmlunit.diff { + public class XPathContext { + private readonly LinkedList<Level> path = new LinkedList<Level>(); + private readonly IDictionary<string, string> uri2Prefix; + + public XPathContext() : this(null) { + } + + public XPathContext(IDictionary<string, string> uri2Prefix) { + if (uri2Prefix == null) { + this.uri2Prefix = new Dictionary<string, string>(); + } else { + this.uri2Prefix = new Dictionary<string, string>(uri2Prefix); + } + path.AddLast(new Level("")); + } + + public void NavigateToChild(int index) { + path.AddLast(path.Last.Value.Children[index]); + } + + public void NavigateToAttribute(XmlQualifiedName attribute) { + path.AddLast(path.Last.Value.Attributes[attribute]); + } + + public void NavigateToParent() { + path.RemoveLast(); + } + + public void RegisterAttributes<Q>(IEnumerable<Q> attributes) + where Q : XmlQualifiedName { + Level current = path.Last.Value; + foreach (XmlQualifiedName attribute in attributes) { + current.Attributes[attribute] = + new Level("@" + GetName(attribute)); + } + } + + public void RegisterChildren<N>(IEnumerable<N> children) + where N : INodeInfo { + Level current = path.Last.Value; + int comments, pis, texts; + comments = pis = texts = 0; + IDictionary<string, int> elements = new Dictionary<string, int>(); + foreach (INodeInfo child in children) { + Level l = null; + switch (child.Type) { + case XmlNodeType.Comment: + l = new Level("comment()[" + (++comments) + "]"); + break; + case XmlNodeType.ProcessingInstruction: + l = new Level("processing-instruction()[" + (++pis) + "]"); + break; + case XmlNodeType.CDATA: + case XmlNodeType.Text: + l = new Level("text()[" + (++texts) + "]"); + break; + case XmlNodeType.Element: + string name = GetName(child.Name); + int old; + if (!elements.TryGetValue(name, out old)) { + old = 0; + } + l = new Level(name + "[" + (++old) + "]"); + elements[name] = old; + break; + default: + throw new ArgumentException("unknown node type " + + child.Type); + } + current.Children.Add(l); + } + } + + public string XPath { + get { + StringBuilder sb = new StringBuilder(); + bool first = true, second = false; + foreach (Level l in path) { + if (!second) { + sb.Append("/"); + } + sb.Append(l.Expression); + if (first) { + second = true; + } else { + second = false; + } + first = false; + } + return sb.ToString(); + } + } + + private string GetName(XmlQualifiedName name) { + string ns = name.Namespace; + string p = null; + if (ns != null) { + uri2Prefix.TryGetValue(ns, out p); + } + return (p == null ? "" : p + ":") + name.Name; + } + + internal class Level { + internal readonly string Expression; + internal readonly IList<Level> Children = new List<Level>(); + internal readonly IDictionary<XmlQualifiedName, Level> Attributes = + new Dictionary<XmlQualifiedName, Level>(); + internal Level(string expression) { + this.Expression = expression; + } + } + + public interface INodeInfo { + XmlQualifiedName Name { get; } + XmlNodeType Type { get; } + } + + public class DOMNodeInfo : INodeInfo { + private XmlQualifiedName name; + private XmlNodeType type; + public DOMNodeInfo(XmlNode n) { + name = Nodes.GetQName(n); + type = n.NodeType; + } + public XmlQualifiedName Name { get { return name; } } + public XmlNodeType Type { get { return type; } } + } + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/main/net-core/diff/XPathContext.cs ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/XPathContextTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/XPathContextTest.java (rev 0) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/XPathContextTest.java 2010-08-20 10:07:48 UTC (rev 432) @@ -0,0 +1,185 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package net.sf.xmlunit.diff; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import javax.xml.namespace.QName; +import org.junit.Test; +import org.w3c.dom.Node; + +import static org.junit.Assert.*; + +public class XPathContextTest { + @Test public void empty() { + assertEquals("/", new XPathContext().getXPath()); + } + + @Test public void oneLevelOfElements() { + ArrayList<Element> l = new ArrayList<Element>(); + l.add(new Element("foo")); + l.add(new Element("foo")); + l.add(new Element("bar")); + l.add(new Element("foo")); + XPathContext ctx = new XPathContext(); + ctx.registerChildren(l); + ctx.navigateToChild(0); + assertEquals("/foo[1]", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToChild(1); + assertEquals("/foo[2]", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToChild(2); + assertEquals("/bar[1]", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToChild(3); + assertEquals("/foo[3]", ctx.getXPath()); + } + + @Test public void twoLevelsOfElements() { + ArrayList<Element> l = new ArrayList<Element>(); + l.add(new Element("foo")); + l.add(new Element("foo")); + l.add(new Element("bar")); + l.add(new Element("foo")); + XPathContext ctx = new XPathContext(); + ctx.registerChildren(l); + ctx.navigateToChild(0); + assertEquals("/foo[1]", ctx.getXPath()); + ctx.registerChildren(l); + ctx.navigateToChild(3); + assertEquals("/foo[1]/foo[3]", ctx.getXPath()); + ctx.navigateToParent(); + assertEquals("/foo[1]", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToChild(2); + assertEquals("/bar[1]", ctx.getXPath()); + } + + @Test public void attributes() { + XPathContext ctx = new XPathContext(); + ctx.registerChildren(Collections.singletonList(new Element("foo"))); + ctx.navigateToChild(0); + ArrayList<QName> l = new ArrayList<QName>(); + l.add(new QName("bar")); + ctx.registerAttributes(l); + ctx.navigateToAttribute(new QName("bar")); + assertEquals("/foo[1]/@bar", ctx.getXPath()); + } + + @Test public void mixed() { + ArrayList<XPathContext.NodeInfo> l = new ArrayList<XPathContext.NodeInfo>(); + l.add(new Text()); + l.add(new Comment()); + l.add(new CDATA()); + l.add(new PI()); + l.add(new CDATA()); + l.add(new Comment()); + l.add(new PI()); + l.add(new Text()); + XPathContext ctx = new XPathContext(); + ctx.registerChildren(l); + ctx.navigateToChild(0); + assertEquals("/text()[1]", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToChild(1); + assertEquals("/comment()[1]", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToChild(2); + assertEquals("/text()[2]", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToChild(3); + assertEquals("/processing-instruction()[1]", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToChild(4); + assertEquals("/text()[3]", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToChild(5); + assertEquals("/comment()[2]", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToChild(6); + assertEquals("/processing-instruction()[2]", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToChild(7); + assertEquals("/text()[4]", ctx.getXPath()); + } + + @Test public void elementsAndNs() { + ArrayList<Element> l = new ArrayList<Element>(); + l.add(new Element("foo", "urn:foo:foo")); + l.add(new Element("foo")); + l.add(new Element("foo", "urn:foo:bar")); + HashMap<String, String> m = new HashMap<String, String>(); + m.put("urn:foo:bar", "bar"); + XPathContext ctx = new XPathContext(m); + ctx.registerChildren(l); + ctx.navigateToChild(0); + assertEquals("/foo[1]", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToChild(1); + assertEquals("/foo[2]", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToChild(2); + assertEquals("/bar:foo[1]", ctx.getXPath()); + } + + @Test public void attributesAndNs() { + HashMap<String, String> m = new HashMap<String, String>(); + m.put("urn:foo:bar", "bar"); + XPathContext ctx = new XPathContext(m); + ctx.registerChildren(Collections.singletonList(new Element("foo", + "urn:foo:bar")) + ); + ctx.navigateToChild(0); + ArrayList<QName> l = new ArrayList<QName>(); + l.add(new QName("baz")); + l.add(new QName("urn:foo:bar", "baz")); + ctx.registerAttributes(l); + ctx.navigateToAttribute(new QName("baz")); + assertEquals("/bar:foo[1]/@baz", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToAttribute(new QName("urn:foo:bar", "baz")); + assertEquals("/bar:foo[1]/@bar:baz", ctx.getXPath()); + ctx.navigateToParent(); + } + + private static class Element implements XPathContext.NodeInfo { + private final QName name; + private Element(String name) { + this.name = new QName(name); + } + private Element(String name, String ns) { + this.name = new QName(ns, name); + } + public QName getName() { return name; } + public short getType() { return Node.ELEMENT_NODE; } + } + + private static abstract class NonElement implements XPathContext.NodeInfo { + public QName getName() { return null; } + } + private static class Text extends NonElement { + public short getType() { return Node.TEXT_NODE; } + } + private static class Comment extends NonElement { + public short getType() { return Node.COMMENT_NODE; } + } + private static class PI extends NonElement { + public short getType() { return Node.PROCESSING_INSTRUCTION_NODE; } + } + private static class CDATA extends NonElement { + public short getType() { return Node.CDATA_SECTION_NODE; } + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/XPathContextTest.java ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/tests/net-core/diff/XPathContextTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/XPathContextTest.cs (rev 0) +++ trunk/xmlunit/src/tests/net-core/diff/XPathContextTest.cs 2010-08-20 10:07:48 UTC (rev 432) @@ -0,0 +1,201 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +using System; +using System.Collections.Generic; +using System.Xml; +using NUnit.Framework; + +namespace net.sf.xmlunit.diff { + + [TestFixture] + public class XPathContextTest { + [Test] + public void Empty() { + Assert.AreEqual("/", new XPathContext().XPath); + } + + [Test] + public void OneLevelOfElements() { + List<Element> l = new List<Element>(); + l.Add(new Element("foo")); + l.Add(new Element("foo")); + l.Add(new Element("bar")); + l.Add(new Element("foo")); + XPathContext ctx = new XPathContext(); + ctx.RegisterChildren(l); + ctx.NavigateToChild(0); + Assert.AreEqual("/foo[1]", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToChild(1); + Assert.AreEqual("/foo[2]", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToChild(2); + Assert.AreEqual("/bar[1]", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToChild(3); + Assert.AreEqual("/foo[3]", ctx.XPath); + } + + [Test] + public void TwoLevelsOfElements() { + List<Element> l = new List<Element>(); + l.Add(new Element("foo")); + l.Add(new Element("foo")); + l.Add(new Element("bar")); + l.Add(new Element("foo")); + XPathContext ctx = new XPathContext(); + ctx.RegisterChildren(l); + ctx.NavigateToChild(0); + Assert.AreEqual("/foo[1]", ctx.XPath); + ctx.RegisterChildren(l); + ctx.NavigateToChild(3); + Assert.AreEqual("/foo[1]/foo[3]", ctx.XPath); + ctx.NavigateToParent(); + Assert.AreEqual("/foo[1]", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToChild(2); + Assert.AreEqual("/bar[1]", ctx.XPath); + } + + [Test] + public void Attributes() { + XPathContext ctx = new XPathContext(); + ctx.RegisterChildren(Singleton(new Element("foo"))); + ctx.NavigateToChild(0); + List<XmlQualifiedName> l = new List<XmlQualifiedName>(); + l.Add(new XmlQualifiedName("bar")); + ctx.RegisterAttributes(l); + ctx.NavigateToAttribute(new XmlQualifiedName("bar")); + Assert.AreEqual("/foo[1]/@bar", ctx.XPath); + } + + private static IEnumerable<T> Singleton<T>(T t) { + yield return t; + } + + [Test] + public void Mixed() { + List<XPathContext.INodeInfo> l = new List<XPathContext.INodeInfo>(); + l.Add(new Text()); + l.Add(new Comment()); + l.Add(new CDATA()); + l.Add(new PI()); + l.Add(new CDATA()); + l.Add(new Comment()); + l.Add(new PI()); + l.Add(new Text()); + XPathContext ctx = new XPathContext(); + ctx.RegisterChildren(l); + ctx.NavigateToChild(0); + Assert.AreEqual("/text()[1]", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToChild(1); + Assert.AreEqual("/comment()[1]", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToChild(2); + Assert.AreEqual("/text()[2]", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToChild(3); + Assert.AreEqual("/processing-instruction()[1]", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToChild(4); + Assert.AreEqual("/text()[3]", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToChild(5); + Assert.AreEqual("/comment()[2]", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToChild(6); + Assert.AreEqual("/processing-instruction()[2]", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToChild(7); + Assert.AreEqual("/text()[4]", ctx.XPath); + } + + [Test] + public void ElementsAndNs() { + List<Element> l = new List<Element>(); + l.Add(new Element("foo", "urn:foo:foo")); + l.Add(new Element("foo")); + l.Add(new Element("foo", "urn:foo:bar")); + Dictionary<string, string> m = new Dictionary<string, string>(); + m["urn:foo:bar"] = "bar"; + XPathContext ctx = new XPathContext(m); + ctx.RegisterChildren(l); + ctx.NavigateToChild(0); + Assert.AreEqual("/foo[1]", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToChild(1); + Assert.AreEqual("/foo[2]", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToChild(2); + Assert.AreEqual("/bar:foo[1]", ctx.XPath); + } + + [Test] + public void AttributesAndNs() { + Dictionary<string, string> m = new Dictionary<string, string>(); + m["urn:foo:bar"] = "bar"; + XPathContext ctx = new XPathContext(m); + ctx.RegisterChildren(Singleton(new Element("foo", "urn:foo:bar"))); + ctx.NavigateToChild(0); + List<XmlQualifiedName> l = new List<XmlQualifiedName>(); + l.Add(new XmlQualifiedName("baz")); + l.Add(new XmlQualifiedName("baz", "urn:foo:bar")); + ctx.RegisterAttributes(l); + ctx.NavigateToAttribute(new XmlQualifiedName("baz")); + Assert.AreEqual("/bar:foo[1]/@baz", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToAttribute(new XmlQualifiedName("baz", "urn:foo:bar")); + Assert.AreEqual("/bar:foo[1]/@bar:baz", ctx.XPath); + ctx.NavigateToParent(); + } + + internal class Element : XPathContext.INodeInfo { + private readonly XmlQualifiedName name; + internal Element(string name) { + this.name = new XmlQualifiedName(name); + } + internal Element(string name, string ns) { + this.name = new XmlQualifiedName(name, ns); + } + public XmlQualifiedName Name { get { return name; } } + public XmlNodeType Type { get { return XmlNodeType.Element; } } + } + + internal abstract class NonElement : XPathContext.INodeInfo { + public XmlQualifiedName Name { get { return null; } } + public abstract XmlNodeType Type { get; } + } + internal class Text : NonElement { + public override XmlNodeType Type { + get { return XmlNodeType.Text; } + } + } + internal class Comment : NonElement { + public override XmlNodeType Type { + get { return XmlNodeType.Comment; } + } + } + internal class PI : NonElement { + public override XmlNodeType Type { + get { return XmlNodeType.ProcessingInstruction;} + } + } + internal class CDATA : NonElement { + public override XmlNodeType Type { + get { return XmlNodeType.CDATA; } + } + } + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/tests/net-core/diff/XPathContextTest.cs ___________________________________________________________________ Added: 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...> - 2010-08-20 12:56:23
|
Revision: 433 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=433&view=rev Author: bodewig Date: 2010-08-20 12:56:17 +0000 (Fri, 20 Aug 2010) Log Message: ----------- cleanup Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/XPathContext.java trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/IterableNodeList.java trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml trunk/xmlunit/src/main/net-core/diff/XPathContext.cs trunk/xmlunit/src/main/net-core/util/Convert.cs trunk/xmlunit/src/tests/net-core/diff/XPathContextTest.cs Added Paths: ----------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Linqy.java trunk/xmlunit/src/main/net-core/util/Linqy.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/XPathContext.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/XPathContext.java 2010-08-20 10:07:48 UTC (rev 432) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/XPathContext.java 2010-08-20 12:56:17 UTC (rev 433) @@ -96,20 +96,10 @@ public String getXPath() { StringBuilder sb = new StringBuilder(); - boolean first = true, second = false; for (Level l : path) { - if (!second) { - sb.append("/"); - } - sb.append(l.expression); - if (first) { - second = true; - } else { - second = false; - } - first = false; + sb.append("/").append(l.expression); } - return sb.toString(); + return sb.toString().replace("//", "/"); } private String getName(QName name) { Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/IterableNodeList.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/IterableNodeList.java 2010-08-20 10:07:48 UTC (rev 432) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/IterableNodeList.java 2010-08-20 12:56:17 UTC (rev 433) @@ -13,7 +13,6 @@ */ package net.sf.xmlunit.util; -import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.w3c.dom.Node; @@ -50,20 +49,9 @@ } /** - * Turns the iterable into a list. - */ - public static List<Node> asList(IterableNodeList l) { - ArrayList<Node> a = new ArrayList<Node>(l.length); - for (Node n : l) { - a.add(n); - } - return a; - } - - /** * Turns the NodeList into a list. */ public static List<Node> asList(NodeList l) { - return asList(new IterableNodeList(l)); + return Linqy.asList(new IterableNodeList(l)); } } Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Linqy.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Linqy.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Linqy.java 2010-08-20 12:56:17 UTC (rev 433) @@ -0,0 +1,30 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package net.sf.xmlunit.util; + +import java.util.ArrayList; +import java.util.List; + +public final class Linqy { + /** + * Turns the iterable into a list. + */ + public static <E> List<E> asList(Iterable<E> i) { + ArrayList<E> a = new ArrayList<E>(); + for (E e : i) { + a.add(e); + } + return a; + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Linqy.java ___________________________________________________________________ Added: svn:eol-style + native Modified: trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-20 10:07:48 UTC (rev 432) +++ trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-20 12:56:17 UTC (rev 433) @@ -21,6 +21,7 @@ <import reference="System.Collections.Generic"/> <import reference="System.Xml"/> <import reference="System.Xml.Schema"/> + <import reference="net.sf.xmlunit.util"/> <literal><![CDATA[ @@ -266,11 +267,9 @@ private ComparisonResult CompareNodeLists(XmlNodeList control, XmlNodeList test) { IList<XmlNode> controlList = - new List<XmlNode>(net.sf.xmlunit.util.Convert - .Cast<XmlNode>(control)); + new List<XmlNode>(Linqy.Cast<XmlNode>(control)); IList<XmlNode> testList = - new List<XmlNode>(net.sf.xmlunit.util.Convert - .Cast<XmlNode>(test)); + new List<XmlNode>(Linqy.Cast<XmlNode>(test)); IDictionary<int, object> unmatchedTestIndexes = new SortedDictionary<int, object>(); for (int i = 0; i < testList.Count; i++) { Modified: trunk/xmlunit/src/main/net-core/diff/XPathContext.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/XPathContext.cs 2010-08-20 10:07:48 UTC (rev 432) +++ trunk/xmlunit/src/main/net-core/diff/XPathContext.cs 2010-08-20 12:56:17 UTC (rev 433) @@ -95,20 +95,10 @@ public string XPath { get { StringBuilder sb = new StringBuilder(); - bool first = true, second = false; foreach (Level l in path) { - if (!second) { - sb.Append("/"); - } - sb.Append(l.Expression); - if (first) { - second = true; - } else { - second = false; - } - first = false; + sb.AppendFormat("/{0}", l.Expression); } - return sb.ToString(); + return sb.Replace("//", "/").ToString(); } } Modified: trunk/xmlunit/src/main/net-core/util/Convert.cs =================================================================== --- trunk/xmlunit/src/main/net-core/util/Convert.cs 2010-08-20 10:07:48 UTC (rev 432) +++ trunk/xmlunit/src/main/net-core/util/Convert.cs 2010-08-20 12:56:17 UTC (rev 433) @@ -12,7 +12,6 @@ limitations under the License. */ -using System.Collections; using System.Collections.Generic; using System.Xml; using net.sf.xmlunit.input; @@ -73,11 +72,5 @@ } return man; } - - public static IEnumerable<T> Cast<T>(IEnumerable i) { - foreach (T t in i) { - yield return t; - } - } } } Added: trunk/xmlunit/src/main/net-core/util/Linqy.cs =================================================================== --- trunk/xmlunit/src/main/net-core/util/Linqy.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/util/Linqy.cs 2010-08-20 12:56:17 UTC (rev 433) @@ -0,0 +1,34 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +using System.Collections; +using System.Collections.Generic; + +namespace net.sf.xmlunit.util { + /// <summary> + /// Conversion methods. + /// </summary> + public sealed class Linqy { + public static IEnumerable<T> Cast<T>(IEnumerable i) { + foreach (T t in i) { + yield return t; + } + } + + public static IEnumerable<T> Singleton<T>(T t) { + yield return t; + } + + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/main/net-core/util/Linqy.cs ___________________________________________________________________ Added: svn:eol-style + native Modified: trunk/xmlunit/src/tests/net-core/diff/XPathContextTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/XPathContextTest.cs 2010-08-20 10:07:48 UTC (rev 432) +++ trunk/xmlunit/src/tests/net-core/diff/XPathContextTest.cs 2010-08-20 12:56:17 UTC (rev 433) @@ -14,6 +14,7 @@ using System; using System.Collections.Generic; using System.Xml; +using net.sf.xmlunit.util; using NUnit.Framework; namespace net.sf.xmlunit.diff { @@ -71,7 +72,7 @@ [Test] public void Attributes() { XPathContext ctx = new XPathContext(); - ctx.RegisterChildren(Singleton(new Element("foo"))); + ctx.RegisterChildren(Linqy.Singleton(new Element("foo"))); ctx.NavigateToChild(0); List<XmlQualifiedName> l = new List<XmlQualifiedName>(); l.Add(new XmlQualifiedName("bar")); @@ -80,10 +81,6 @@ Assert.AreEqual("/foo[1]/@bar", ctx.XPath); } - private static IEnumerable<T> Singleton<T>(T t) { - yield return t; - } - [Test] public void Mixed() { List<XPathContext.INodeInfo> l = new List<XPathContext.INodeInfo>(); @@ -147,7 +144,8 @@ Dictionary<string, string> m = new Dictionary<string, string>(); m["urn:foo:bar"] = "bar"; XPathContext ctx = new XPathContext(m); - ctx.RegisterChildren(Singleton(new Element("foo", "urn:foo:bar"))); + ctx.RegisterChildren(Linqy.Singleton(new Element("foo", + "urn:foo:bar"))); ctx.NavigateToChild(0); List<XmlQualifiedName> l = new List<XmlQualifiedName>(); l.Add(new XmlQualifiedName("baz")); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-08-26 14:47:00
|
Revision: 436 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=436&view=rev Author: bodewig Date: 2010-08-26 14:46:54 +0000 (Thu, 26 Aug 2010) Log Message: ----------- allow child elements to be added incrementally in XPathContext Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/XPathContext.java trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Linqy.java trunk/xmlunit/src/main/net-core/diff/XPathContext.cs trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/XPathContextTest.java trunk/xmlunit/src/tests/net-core/diff/XPathContextTest.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/XPathContext.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/XPathContext.java 2010-08-23 08:42:44 UTC (rev 435) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/XPathContext.java 2010-08-26 14:46:54 UTC (rev 436) @@ -28,6 +28,15 @@ private final Deque<Level> path = new LinkedList<Level>(); private final Map<String, String> uri2Prefix; + private static final String COMMENT = "comment()"; + private static final String PI = "processing-instruction()"; + private static final String TEXT = "text()"; + private static final String OPEN = "["; + private static final String CLOSE = "]"; + private static final String SEP = "/"; + private static final String ATTR = "@"; + private static final String EMPTY = ""; + public XPathContext() { this(null); } @@ -38,7 +47,7 @@ } else { this.uri2Prefix = Collections.unmodifiableMap(uri2Prefix); } - path.addLast(new Level("")); + path.addLast(new Level(EMPTY)); } public void navigateToChild(int index) { @@ -53,42 +62,63 @@ path.removeLast(); } - public void registerAttributes(Iterable<? extends QName> attributes) { + public void addAttributes(Iterable<? extends QName> attributes) { Level current = path.getLast(); for (QName attribute : attributes) { current.attributes.put(attribute, - new Level("@" + getName(attribute))); + new Level(ATTR + getName(attribute))); } } - public void registerChildren(Iterable<? extends NodeInfo> children) { + public void setChildren(Iterable<? extends NodeInfo> children) { Level current = path.getLast(); + current.children.clear(); + appendChildren(children); + } + + public void appendChildren(Iterable<? extends NodeInfo> children) { + Level current = path.getLast(); int comments, pis, texts; comments = pis = texts = 0; Map<String, Integer> elements = new HashMap<String, Integer>(); + + for (Level l : current.children) { + String childName = l.expression; + if (childName.startsWith(COMMENT)) { + comments++; + } else if (childName.startsWith(PI)) { + pis++; + } else if (childName.startsWith(TEXT)) { + texts++; + } else { + childName = childName.substring(0, childName.indexOf(OPEN)); + add1OrIncrement(childName, elements); + } + } + for (NodeInfo child : children) { Level l = null; switch (child.getType()) { case Node.COMMENT_NODE: - l = new Level("comment()[" + (++comments) + "]"); + l = new Level(COMMENT + OPEN + (++comments) + CLOSE); break; case Node.PROCESSING_INSTRUCTION_NODE: - l = new Level("processing-instruction()[" + (++pis) + "]"); + l = new Level(PI + OPEN + (++pis) + CLOSE); break; case Node.CDATA_SECTION_NODE: case Node.TEXT_NODE: - l = new Level("text()[" + (++texts) + "]"); + l = new Level(TEXT + OPEN + (++texts) + CLOSE); break; case Node.ELEMENT_NODE: String name = getName(child.getName()); - Integer old = elements.get(name); - int index = old == null ? 0 : old.intValue(); - l = new Level(name + "[" + (++index) + "]"); - elements.put(name, Integer.valueOf(index)); + l = new Level(name + OPEN + add1OrIncrement(name, elements) + + CLOSE); break; default: - throw new IllegalArgumentException("unknown node type " + - child.getType()); + // more or less ignore + // FIXME: is this a good thing? + l = new Level(EMPTY); + break; } current.children.add(l); } @@ -97,9 +127,9 @@ public String getXPath() { StringBuilder sb = new StringBuilder(); for (Level l : path) { - sb.append("/").append(l.expression); + sb.append(SEP).append(l.expression); } - return sb.toString().replace("//", "/"); + return sb.toString().replace(SEP + SEP, SEP); } private String getName(QName name) { @@ -108,9 +138,22 @@ if (ns != null) { p = uri2Prefix.get(ns); } - return (p == null ? "" : p + ":") + name.getLocalPart(); + return (p == null ? EMPTY : p + ":") + name.getLocalPart(); } + /** + * Increments the value name maps to or adds 1 as value if name + * isn't present inside the map. + * + * @return the new mapping for name + */ + private static int add1OrIncrement(String name, Map<String, Integer> map) { + Integer old = map.get(name); + int index = old == null ? 1 : (old.intValue() + 1); + map.put(name, Integer.valueOf(index)); + return index; + } + private static class Level { private final String expression; private List<Level> children = new ArrayList<Level>(); Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Linqy.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Linqy.java 2010-08-23 08:42:44 UTC (rev 435) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Linqy.java 2010-08-26 14:46:54 UTC (rev 436) @@ -16,6 +16,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.NoSuchElementException; public final class Linqy { /** @@ -37,6 +38,14 @@ }; } + public static <E> Iterable<E> singleton(final E single) { + return new Iterable<E>() { + public Iterator<E> iterator() { + return new OnceOnlyIterator<E>(single); + } + }; + } + private static class CastingIterator<E> implements Iterator<E> { private final Iterator i; private CastingIterator(Iterator i) { @@ -52,4 +61,25 @@ return i.hasNext(); } } + + private static class OnceOnlyIterator<E> implements Iterator<E> { + private final E element; + private boolean iterated = false; + private OnceOnlyIterator(E element) { + this.element = element; + } + public void remove() { + throw new UnsupportedOperationException(); + } + public E next() { + if (iterated) { + throw new NoSuchElementException(); + } + iterated = true; + return element; + } + public boolean hasNext() { + return !iterated; + } + } } \ No newline at end of file Modified: trunk/xmlunit/src/main/net-core/diff/XPathContext.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/XPathContext.cs 2010-08-23 08:42:44 UTC (rev 435) +++ trunk/xmlunit/src/main/net-core/diff/XPathContext.cs 2010-08-26 14:46:54 UTC (rev 436) @@ -23,6 +23,14 @@ private readonly LinkedList<Level> path = new LinkedList<Level>(); private readonly IDictionary<string, string> uri2Prefix; + private const string COMMENT = "comment()"; + private const string PI = "processing-instruction()"; + private const string TEXT = "text()"; + private const string OPEN = "["; + private const string CLOSE = "]"; + private const string SEP = "/"; + private const string ATTR = "@"; + public XPathContext() : this(null) { } @@ -47,46 +55,66 @@ path.RemoveLast(); } - public void RegisterAttributes<Q>(IEnumerable<Q> attributes) + public void AddAttributes<Q>(IEnumerable<Q> attributes) where Q : XmlQualifiedName { Level current = path.Last.Value; foreach (XmlQualifiedName attribute in attributes) { current.Attributes[attribute] = - new Level("@" + GetName(attribute)); + new Level(ATTR + GetName(attribute)); } } - public void RegisterChildren<N>(IEnumerable<N> children) + public void SetChildren<N>(IEnumerable<N> children) where N : INodeInfo { Level current = path.Last.Value; + current.Children.Clear(); + AppendChildren(children); + } + + public void AppendChildren<N>(IEnumerable<N> children) + where N : INodeInfo { + Level current = path.Last.Value; int comments, pis, texts; comments = pis = texts = 0; IDictionary<string, int> elements = new Dictionary<string, int>(); + + foreach (Level l in current.Children) { + string childName = l.Expression; + if (childName.StartsWith(COMMENT)) { + comments++; + } else if (childName.StartsWith(PI)) { + pis++; + } else if (childName.StartsWith(TEXT)) { + texts++; + } else { + childName = childName.Substring(0, childName.IndexOf(OPEN)); + Add1OrIncrement(childName, elements); + } + } + foreach (INodeInfo child in children) { Level l = null; switch (child.Type) { case XmlNodeType.Comment: - l = new Level("comment()[" + (++comments) + "]"); + l = new Level(COMMENT + OPEN + (++comments) + CLOSE); break; case XmlNodeType.ProcessingInstruction: - l = new Level("processing-instruction()[" + (++pis) + "]"); + l = new Level(PI + OPEN + (++pis) + CLOSE); break; case XmlNodeType.CDATA: case XmlNodeType.Text: - l = new Level("text()[" + (++texts) + "]"); + l = new Level(TEXT + OPEN + (++texts) + CLOSE); break; case XmlNodeType.Element: string name = GetName(child.Name); - int old; - if (!elements.TryGetValue(name, out old)) { - old = 0; - } - l = new Level(name + "[" + (++old) + "]"); - elements[name] = old; + l = new Level(name + OPEN + Add1OrIncrement(name, elements) + + CLOSE); break; default: - throw new ArgumentException("unknown node type " + - child.Type); + // more or less ignore + // FIXME: is this a good thing? + l = new Level(string.Empty); + break; } current.Children.Add(l); } @@ -96,9 +124,9 @@ get { StringBuilder sb = new StringBuilder(); foreach (Level l in path) { - sb.AppendFormat("/{0}", l.Expression); + sb.AppendFormat(SEP + "{0}", l.Expression); } - return sb.Replace("//", "/").ToString(); + return sb.Replace(SEP + SEP, SEP).ToString(); } } @@ -111,6 +139,19 @@ return (p == null ? "" : p + ":") + name.Name; } + /// <summary> + /// Increments the value name maps to or adds 1 as value if name + /// isn't present inside the map. + /// </summary> + /// <returns>the new mapping for name</returns> + private static int Add1OrIncrement(string name, + IDictionary<string, int> map) { + int index = 0; + map.TryGetValue(name, out index); + map[name] = ++index; + return index; + } + internal class Level { internal readonly string Expression; internal readonly IList<Level> Children = new List<Level>(); Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/XPathContextTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/XPathContextTest.java 2010-08-23 08:42:44 UTC (rev 435) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/XPathContextTest.java 2010-08-26 14:46:54 UTC (rev 436) @@ -14,9 +14,9 @@ package net.sf.xmlunit.diff; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import javax.xml.namespace.QName; +import net.sf.xmlunit.util.Linqy; import org.junit.Test; import org.w3c.dom.Node; @@ -34,7 +34,7 @@ l.add(new Element("bar")); l.add(new Element("foo")); XPathContext ctx = new XPathContext(); - ctx.registerChildren(l); + ctx.setChildren(l); ctx.navigateToChild(0); assertEquals("/foo[1]", ctx.getXPath()); ctx.navigateToParent(); @@ -48,6 +48,29 @@ assertEquals("/foo[3]", ctx.getXPath()); } + @Test public void appendChildren() { + ArrayList<Element> l = new ArrayList<Element>(); + l.add(new Element("foo")); + l.add(new Element("foo")); + XPathContext ctx = new XPathContext(); + ctx.setChildren(l); + l = new ArrayList<Element>(); + l.add(new Element("bar")); + l.add(new Element("foo")); + ctx.appendChildren(l); + ctx.navigateToChild(0); + assertEquals("/foo[1]", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToChild(1); + assertEquals("/foo[2]", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToChild(2); + assertEquals("/bar[1]", ctx.getXPath()); + ctx.navigateToParent(); + ctx.navigateToChild(3); + assertEquals("/foo[3]", ctx.getXPath()); + } + @Test public void twoLevelsOfElements() { ArrayList<Element> l = new ArrayList<Element>(); l.add(new Element("foo")); @@ -55,10 +78,10 @@ l.add(new Element("bar")); l.add(new Element("foo")); XPathContext ctx = new XPathContext(); - ctx.registerChildren(l); + ctx.setChildren(l); ctx.navigateToChild(0); assertEquals("/foo[1]", ctx.getXPath()); - ctx.registerChildren(l); + ctx.setChildren(l); ctx.navigateToChild(3); assertEquals("/foo[1]/foo[3]", ctx.getXPath()); ctx.navigateToParent(); @@ -70,11 +93,11 @@ @Test public void attributes() { XPathContext ctx = new XPathContext(); - ctx.registerChildren(Collections.singletonList(new Element("foo"))); + ctx.setChildren(Linqy.singleton(new Element("foo"))); ctx.navigateToChild(0); ArrayList<QName> l = new ArrayList<QName>(); l.add(new QName("bar")); - ctx.registerAttributes(l); + ctx.addAttributes(l); ctx.navigateToAttribute(new QName("bar")); assertEquals("/foo[1]/@bar", ctx.getXPath()); } @@ -90,7 +113,7 @@ l.add(new PI()); l.add(new Text()); XPathContext ctx = new XPathContext(); - ctx.registerChildren(l); + ctx.setChildren(l); ctx.navigateToChild(0); assertEquals("/text()[1]", ctx.getXPath()); ctx.navigateToParent(); @@ -124,7 +147,7 @@ HashMap<String, String> m = new HashMap<String, String>(); m.put("urn:foo:bar", "bar"); XPathContext ctx = new XPathContext(m); - ctx.registerChildren(l); + ctx.setChildren(l); ctx.navigateToChild(0); assertEquals("/foo[1]", ctx.getXPath()); ctx.navigateToParent(); @@ -139,14 +162,12 @@ HashMap<String, String> m = new HashMap<String, String>(); m.put("urn:foo:bar", "bar"); XPathContext ctx = new XPathContext(m); - ctx.registerChildren(Collections.singletonList(new Element("foo", - "urn:foo:bar")) - ); + ctx.setChildren(Linqy.singleton(new Element("foo", "urn:foo:bar"))); ctx.navigateToChild(0); ArrayList<QName> l = new ArrayList<QName>(); l.add(new QName("baz")); l.add(new QName("urn:foo:bar", "baz")); - ctx.registerAttributes(l); + ctx.addAttributes(l); ctx.navigateToAttribute(new QName("baz")); assertEquals("/bar:foo[1]/@baz", ctx.getXPath()); ctx.navigateToParent(); Modified: trunk/xmlunit/src/tests/net-core/diff/XPathContextTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/XPathContextTest.cs 2010-08-23 08:42:44 UTC (rev 435) +++ trunk/xmlunit/src/tests/net-core/diff/XPathContextTest.cs 2010-08-26 14:46:54 UTC (rev 436) @@ -27,6 +27,30 @@ } [Test] + public void AppendChildren() { + List<Element> l = new List<Element>(); + l.Add(new Element("foo")); + l.Add(new Element("foo")); + XPathContext ctx = new XPathContext(); + ctx.SetChildren(l); + l = new List<Element>(); + l.Add(new Element("bar")); + l.Add(new Element("foo")); + ctx.AppendChildren(l); + ctx.NavigateToChild(0); + Assert.AreEqual("/foo[1]", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToChild(1); + Assert.AreEqual("/foo[2]", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToChild(2); + Assert.AreEqual("/bar[1]", ctx.XPath); + ctx.NavigateToParent(); + ctx.NavigateToChild(3); + Assert.AreEqual("/foo[3]", ctx.XPath); + } + + [Test] public void OneLevelOfElements() { List<Element> l = new List<Element>(); l.Add(new Element("foo")); @@ -34,7 +58,7 @@ l.Add(new Element("bar")); l.Add(new Element("foo")); XPathContext ctx = new XPathContext(); - ctx.RegisterChildren(l); + ctx.SetChildren(l); ctx.NavigateToChild(0); Assert.AreEqual("/foo[1]", ctx.XPath); ctx.NavigateToParent(); @@ -56,10 +80,10 @@ l.Add(new Element("bar")); l.Add(new Element("foo")); XPathContext ctx = new XPathContext(); - ctx.RegisterChildren(l); + ctx.SetChildren(l); ctx.NavigateToChild(0); Assert.AreEqual("/foo[1]", ctx.XPath); - ctx.RegisterChildren(l); + ctx.SetChildren(l); ctx.NavigateToChild(3); Assert.AreEqual("/foo[1]/foo[3]", ctx.XPath); ctx.NavigateToParent(); @@ -72,11 +96,11 @@ [Test] public void Attributes() { XPathContext ctx = new XPathContext(); - ctx.RegisterChildren(Linqy.Singleton(new Element("foo"))); + ctx.SetChildren(Linqy.Singleton(new Element("foo"))); ctx.NavigateToChild(0); List<XmlQualifiedName> l = new List<XmlQualifiedName>(); l.Add(new XmlQualifiedName("bar")); - ctx.RegisterAttributes(l); + ctx.AddAttributes(l); ctx.NavigateToAttribute(new XmlQualifiedName("bar")); Assert.AreEqual("/foo[1]/@bar", ctx.XPath); } @@ -93,7 +117,7 @@ l.Add(new PI()); l.Add(new Text()); XPathContext ctx = new XPathContext(); - ctx.RegisterChildren(l); + ctx.SetChildren(l); ctx.NavigateToChild(0); Assert.AreEqual("/text()[1]", ctx.XPath); ctx.NavigateToParent(); @@ -128,7 +152,7 @@ Dictionary<string, string> m = new Dictionary<string, string>(); m["urn:foo:bar"] = "bar"; XPathContext ctx = new XPathContext(m); - ctx.RegisterChildren(l); + ctx.SetChildren(l); ctx.NavigateToChild(0); Assert.AreEqual("/foo[1]", ctx.XPath); ctx.NavigateToParent(); @@ -144,13 +168,13 @@ Dictionary<string, string> m = new Dictionary<string, string>(); m["urn:foo:bar"] = "bar"; XPathContext ctx = new XPathContext(m); - ctx.RegisterChildren(Linqy.Singleton(new Element("foo", + ctx.SetChildren(Linqy.Singleton(new Element("foo", "urn:foo:bar"))); ctx.NavigateToChild(0); List<XmlQualifiedName> l = new List<XmlQualifiedName>(); l.Add(new XmlQualifiedName("baz")); l.Add(new XmlQualifiedName("baz", "urn:foo:bar")); - ctx.RegisterAttributes(l); + ctx.AddAttributes(l); ctx.NavigateToAttribute(new XmlQualifiedName("baz")); Assert.AreEqual("/bar:foo[1]/@baz", ctx.XPath); ctx.NavigateToParent(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-08-31 08:36:58
|
Revision: 441 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=441&view=rev Author: bodewig Date: 2010-08-31 08:36:50 +0000 (Tue, 31 Aug 2010) Log Message: ----------- a first-wins combiner for DifferenceEvaluators Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs Added Paths: ----------- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DifferenceEvaluatorsTest.java trunk/xmlunit/src/tests/net-core/diff/DifferenceEvaluatorsTest.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java 2010-08-30 07:57:04 UTC (rev 440) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java 2010-08-31 08:36:50 UTC (rev 441) @@ -101,4 +101,24 @@ } }; } + + /** + * Combines multiple DifferenceEvaluators so that the first one + * that changes the outcome wins. + */ + public static DifferenceEvaluator + first(final DifferenceEvaluator... evaluators) { + return new DifferenceEvaluator() { + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult orig) { + for (DifferenceEvaluator ev : evaluators) { + ComparisonResult evaluated = ev.evaluate(comparison, orig); + if (evaluated != orig) { + return evaluated; + } + } + return orig; + } + }; + } } Modified: trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs 2010-08-30 07:57:04 UTC (rev 440) +++ trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs 2010-08-31 08:36:50 UTC (rev 441) @@ -96,5 +96,22 @@ ? ComparisonResult.CRITICAL : r; }; } + + /// <summary> + /// Combines multiple DifferenceEvaluators so that the first + /// one that changes the outcome wins. + /// </summary> + public static DifferenceEvaluator + First(params DifferenceEvaluator[] evaluators) { + return delegate(Comparison comparison, ComparisonResult orig) { + foreach (DifferenceEvaluator ev in evaluators) { + ComparisonResult evaluated = ev(comparison, orig); + if (evaluated != orig) { + return evaluated; + } + } + return orig; + }; + } } } \ No newline at end of file Added: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DifferenceEvaluatorsTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DifferenceEvaluatorsTest.java (rev 0) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DifferenceEvaluatorsTest.java 2010-08-31 08:36:50 UTC (rev 441) @@ -0,0 +1,56 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package net.sf.xmlunit.diff; + +import org.junit.Test; + +import static org.junit.Assert.*; + +public class DifferenceEvaluatorsTest { + + private static class Evaluator implements DifferenceEvaluator { + private boolean called = false; + private final ComparisonResult ret; + private Evaluator(ComparisonResult ret) { + this.ret = ret; + } + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult orig) { + called = true; + return ret; + } + } + + @Test public void emptyFirstJustWorks() { + DifferenceEvaluator d = DifferenceEvaluators.first(); + assertEquals(ComparisonResult.CRITICAL, + d.evaluate(null, ComparisonResult.CRITICAL)); + } + + @Test public void firstChangeWinsInFirst() { + Evaluator e1 = new Evaluator(ComparisonResult.CRITICAL); + Evaluator e2 = new Evaluator(ComparisonResult.EQUAL); + DifferenceEvaluator d = DifferenceEvaluators.first(e1, e2); + assertEquals(ComparisonResult.CRITICAL, + d.evaluate(null, ComparisonResult.DIFFERENT)); + assertTrue(e1.called); + assertFalse(e2.called); + e1.called = false; + assertEquals(ComparisonResult.EQUAL, + d.evaluate(null, ComparisonResult.CRITICAL)); + assertTrue(e1.called); + assertTrue(e2.called); + } + +} Property changes on: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DifferenceEvaluatorsTest.java ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/tests/net-core/diff/DifferenceEvaluatorsTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/DifferenceEvaluatorsTest.cs (rev 0) +++ trunk/xmlunit/src/tests/net-core/diff/DifferenceEvaluatorsTest.cs 2010-08-31 08:36:50 UTC (rev 441) @@ -0,0 +1,59 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +using NUnit.Framework; + +namespace net.sf.xmlunit.diff { + + [TestFixture] + public class DifferenceEvaluatorsTest { + + internal class Evaluator { + internal bool Called = false; + private readonly ComparisonResult ret; + internal Evaluator(ComparisonResult ret) { + this.ret = ret; + } + public ComparisonResult Evaluate(Comparison comparison, + ComparisonResult orig) { + Called = true; + return ret; + } + } + + [Test] + public void EmptyFirstJustWorks() { + DifferenceEvaluator d = DifferenceEvaluators.First(); + Assert.AreEqual(ComparisonResult.CRITICAL, + d(null, ComparisonResult.CRITICAL)); + } + + [Test] + public void FirstChangeWinsInFirst() { + Evaluator e1 = new Evaluator(ComparisonResult.CRITICAL); + Evaluator e2 = new Evaluator(ComparisonResult.EQUAL); + DifferenceEvaluator d = DifferenceEvaluators.First(e1.Evaluate, + e2.Evaluate); + Assert.AreEqual(ComparisonResult.CRITICAL, + d(null, ComparisonResult.DIFFERENT)); + Assert.IsTrue(e1.Called); + Assert.IsFalse(e2.Called); + e1.Called = false; + Assert.AreEqual(ComparisonResult.EQUAL, + d(null, ComparisonResult.CRITICAL)); + Assert.IsTrue(e1.Called); + Assert.IsTrue(e2.Called); + } + } +} Property changes on: trunk/xmlunit/src/tests/net-core/diff/DifferenceEvaluatorsTest.cs ___________________________________________________________________ Added: 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...> - 2010-08-31 09:18:36
|
Revision: 442 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=442&view=rev Author: bodewig Date: 2010-08-31 09:18:25 +0000 (Tue, 31 Aug 2010) Log Message: ----------- ELEMENT_TAG_NAME differences must not use prefix Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-08-31 08:36:50 UTC (rev 441) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-08-31 09:18:25 UTC (rev 442) @@ -210,7 +210,9 @@ XPathContext testContext) { ]]></literal> <lastResultDef/> - <compare type="ELEMENT_TAG_NAME" property="getTagName()"/> + <compareExpr type="ELEMENT_TAG_NAME" + controlExpr="Nodes.getQName(control).getLocalPart()" + testExpr="Nodes.getQName(test).getLocalPart()"/> <literal><![CDATA[ Attributes controlAttributes = splitAttributes(control.getAttributes()); controlContext Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-08-31 08:36:50 UTC (rev 441) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-08-31 09:18:25 UTC (rev 442) @@ -701,4 +701,30 @@ e2, new XPathContext())); assertEquals(1, ex.invoked); } + + @Test public void compareElementsNS() { + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.ELEMENT_TAG_NAME); + d.addDifferenceListener(ex); + DifferenceEvaluator ev = new DifferenceEvaluator() { + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult outcome) { + if (comparison.getType() == ComparisonType.NAMESPACE_PREFIX) { + return ComparisonResult.EQUAL; + } + return DifferenceEvaluators.DefaultStopWhenDifferent + .evaluate(comparison, outcome); + } + }; + d.setDifferenceEvaluator(ev); + Element e1 = doc.createElementNS("urn:xmlunit:test", "foo"); + e1.setPrefix("p1"); + Element e2 = doc.createElementNS("urn:xmlunit:test", "foo"); + e2.setPrefix("p2"); + assertEquals(ComparisonResult.EQUAL, + d.compareNodes(e1, new XPathContext(), + e2, new XPathContext())); + assertEquals(0, ex.invoked); + } + } Modified: trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-31 08:36:50 UTC (rev 441) +++ trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-31 09:18:25 UTC (rev 442) @@ -694,5 +694,28 @@ e2, new XPathContext())); Assert.AreEqual(1, ex.invoked); } + + [Test] + public void CompareElementsNS() { + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.ELEMENT_TAG_NAME); + d.DifferenceListener += ex.ComparisonPerformed; + DifferenceEvaluator ev = delegate(Comparison comparison, + ComparisonResult outcome) { + if (comparison.Type == ComparisonType.NAMESPACE_PREFIX) { + return ComparisonResult.EQUAL; + } + return DifferenceEvaluators.DefaultStopWhenDifferent(comparison, + outcome); + }; + d.DifferenceEvaluator = ev; + + XmlElement e1 = doc.CreateElement("p1", "foo", "urn:xmlunit:test"); + XmlElement e2 = doc.CreateElement("p1", "foo", "urn:xmlunit:test"); + Assert.AreEqual(ComparisonResult.EQUAL, + d.CompareNodes(e1, new XPathContext(), + e2, new XPathContext())); + Assert.AreEqual(0, ex.invoked); + } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-08-31 10:15:07
|
Revision: 443 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=443&view=rev Author: bodewig Date: 2010-08-31 10:15:01 +0000 (Tue, 31 Aug 2010) Log Message: ----------- a source that is obtained by stripping comments from a different source Added Paths: ----------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/input/ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/input/CommentLessSource.java trunk/xmlunit/src/main/net-core/input/CommentLessSource.cs trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/input/ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/input/CommentLessSourceTest.java trunk/xmlunit/src/tests/net-core/input/ trunk/xmlunit/src/tests/net-core/input/CommentLessSourceTest.cs Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/input/CommentLessSource.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/input/CommentLessSource.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/input/CommentLessSource.java 2010-08-31 10:15:01 UTC (rev 443) @@ -0,0 +1,48 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package net.sf.xmlunit.input; + +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamSource; + +import net.sf.xmlunit.transform.Transformation; + +/** + * A source that is obtained from a different source by stripping all + * comments. + */ +public final class CommentLessSource extends DOMSource { + + public CommentLessSource(Source originalSource) { + super(); + if (originalSource == null) { + throw new IllegalArgumentException("source must not be null"); + } + Transformation t = new Transformation(originalSource); + t.setStylesheet(getStylesheet()); + setNode(t.transformToDocument()); + } + + private static final String STYLE = + "<stylesheet xmlns=\"http://www.w3.org/1999/XSL/Transform\">" + + "<template match=\"node()[not(self::comment())]|@*\"><copy>" + + "<apply-templates select=\"node()[not(self::comment())]|@*\"/>" + + "</copy></template>" + + "</stylesheet>"; + + private static Source getStylesheet() { + return new StreamSource(new java.io.StringReader(STYLE)); + } +} Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/input/CommentLessSource.java ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/net-core/input/CommentLessSource.cs =================================================================== --- trunk/xmlunit/src/main/net-core/input/CommentLessSource.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/input/CommentLessSource.cs 2010-08-31 10:15:01 UTC (rev 443) @@ -0,0 +1,67 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +using System; +using System.Xml; +using net.sf.xmlunit.transform; + +namespace net.sf.xmlunit.input { + + /// <summary> + /// ISource implementation that is obtained from a different + /// source by stripping all comments. + /// </summary> + public sealed class CommentLessSource : ISource { + private readonly XmlReader reader; + private string systemId; + + public CommentLessSource(ISource originalSource) { + if (originalSource == null) { + throw new ArgumentNullException(); + } + systemId = originalSource.SystemId; + + Transformation t = new Transformation(originalSource); + t.Stylesheet = Stylesheet; + reader = new XmlNodeReader(t.TransformToDocument()); + } + + public XmlReader Reader { + get { + return reader; + } + } + public string SystemId { + get { + return systemId; + } + set { + systemId = value; + } + } + + private const string STYLE = + "<stylesheet xmlns=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" + + "<template match=\"node()[not(self::comment())]|@*\"><copy>" + + "<apply-templates select=\"node()[not(self::comment())]|@*\"/>" + + "</copy></template>" + + "</stylesheet>"; + + private static ISource Stylesheet { + get { + return new StreamSource(new System.IO.StringReader(STYLE)); + } + } + } +} Property changes on: trunk/xmlunit/src/main/net-core/input/CommentLessSource.cs ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/input/CommentLessSourceTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/input/CommentLessSourceTest.java (rev 0) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/input/CommentLessSourceTest.java 2010-08-31 10:15:01 UTC (rev 443) @@ -0,0 +1,41 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package net.sf.xmlunit.input; + +import java.io.StringReader; +import javax.xml.transform.stream.StreamSource; +import net.sf.xmlunit.util.Convert; +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import static org.junit.Assert.*; + +public class CommentLessSourceTest { + + @Test public void stripCommentsAtDifferentLevels() { + StreamSource s = + new StreamSource(new StringReader("<?xml version='1.0'?>" + + "<!-- comment 1 -->" + + "<foo>" + + "<!-- comment 2 -->" + + "</foo>")); + CommentLessSource cls = new CommentLessSource(s); + Document d = Convert.toDocument(cls); + assertEquals(1, d.getChildNodes().getLength()); + assertTrue(d.getChildNodes().item(0) instanceof Element); + assertEquals(0, d.getChildNodes().item(0).getChildNodes().getLength()); + } + +} Property changes on: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/input/CommentLessSourceTest.java ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/tests/net-core/input/CommentLessSourceTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/input/CommentLessSourceTest.cs (rev 0) +++ trunk/xmlunit/src/tests/net-core/input/CommentLessSourceTest.cs 2010-08-31 10:15:01 UTC (rev 443) @@ -0,0 +1,40 @@ +/* + This file is licensed to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +using NUnit.Framework; +using System.IO; +using System.Xml; + +namespace net.sf.xmlunit.input { + [TestFixture] + public class CommentLessSourceTest { + + [Test] + public void StripCommentsAtDifferentLevels() { + StreamSource s = + new StreamSource(new StringReader("<?xml version='1.0'?>" + + "<!-- comment 1 -->" + + "<foo>" + + "<!-- comment 2 -->" + + "</foo>")); + CommentLessSource cls = new CommentLessSource(s); + XmlDocument d = net.sf.xmlunit.util.Convert.ToDocument(cls); + Assert.AreEqual(2, d.ChildNodes.Count); + Assert.IsTrue(d.ChildNodes[0] is XmlDeclaration); + Assert.IsTrue(d.ChildNodes[1] is XmlElement); + Assert.AreEqual(0, d.ChildNodes[1].ChildNodes.Count); + } + } +} + Property changes on: trunk/xmlunit/src/tests/net-core/input/CommentLessSourceTest.cs ___________________________________________________________________ Added: 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...> - 2010-08-31 14:18:02
|
Revision: 444 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=444&view=rev Author: bodewig Date: 2010-08-31 14:17:56 +0000 (Tue, 31 Aug 2010) Log Message: ----------- add forgotten child_nodelist_sequence comparison Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-08-31 10:15:01 UTC (rev 443) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DOMDifferenceEngine.java.xml 2010-08-31 14:17:56 UTC (rev 444) @@ -326,12 +326,16 @@ ]]></literal> testContext.navigateToChild(testMatch.index); try { + Integer testIndex = Integer.valueOf(testMatch.index); + <compareExpr type="CHILD_NODELIST_SEQUENCE" + controlExpr="Integer.valueOf(i)" + testExpr="testIndex" + /> <compareMethodExpr method="compareNodes" controlExpr="controlList.get(i)" testExpr="testMatch.node"/> <literal><![CDATA[ - unmatchedTestIndexes - .remove(Integer.valueOf(testMatch.index)); + unmatchedTestIndexes.remove(testIndex); lastMatch = testMatch; } finally { testContext.navigateToParent(); Modified: trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-31 10:15:01 UTC (rev 443) +++ trunk/xmlunit/src/main/net-core/diff/DOMDifferenceEngine.xml 2010-08-31 14:17:56 UTC (rev 444) @@ -365,6 +365,10 @@ testContext.NavigateToChild(testMatch.Index); try { ]]></literal> + <compareExpr type="CHILD_NODELIST_SEQUENCE" + controlExpr="i" + testExpr="testMatch.Index" + /> <compareMethodExpr method="CompareNodes" controlExpr="controlList[i]" testExpr="testMatch.Node"/> Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-08-31 10:15:01 UTC (rev 443) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/DOMDifferenceEngineTest.java 2010-08-31 14:17:56 UTC (rev 444) @@ -727,4 +727,41 @@ assertEquals(0, ex.invoked); } + @Test public void childNodeListSequence() { + Element e1 = doc.createElement("foo"); + Element e3 = doc.createElement("bar"); + Element e4 = doc.createElement("baz"); + e1.appendChild(e3); + e1.appendChild(e4); + + Element e2 = doc.createElement("foo"); + Element e5 = doc.createElement("bar"); + Element e6 = doc.createElement("baz"); + e2.appendChild(e6); + e2.appendChild(e5); + + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.CHILD_NODELIST_SEQUENCE, + "/bar[1]", "/bar[1]"); + d.addDifferenceListener(ex); + DifferenceEvaluator ev = new DifferenceEvaluator() { + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult outcome) { + if (outcome != ComparisonResult.EQUAL + && comparison.getType() == ComparisonType.CHILD_NODELIST_SEQUENCE) { + return ComparisonResult.CRITICAL; + } + return DifferenceEvaluators.DefaultStopWhenDifferent + .evaluate(comparison, outcome); + } + }; + d.setDifferenceEvaluator(ev); + d.setElementSelector(ElementSelectors.byName); + + assertEquals(ComparisonResult.CRITICAL, + d.compareNodes(e1, new XPathContext(), + e2, new XPathContext())); + assertEquals(1, ex.invoked); + } + } Modified: trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-31 10:15:01 UTC (rev 443) +++ trunk/xmlunit/src/tests/net-core/diff/DOMDifferenceEngineTest.cs 2010-08-31 14:17:56 UTC (rev 444) @@ -717,5 +717,41 @@ e2, new XPathContext())); Assert.AreEqual(0, ex.invoked); } + + [Test] + public void ChildNodeListSequence() { + XmlElement e1 = doc.CreateElement("foo"); + XmlElement e3 = doc.CreateElement("bar"); + XmlElement e4 = doc.CreateElement("baz"); + e1.AppendChild(e3); + e1.AppendChild(e4); + + XmlElement e2 = doc.CreateElement("foo"); + XmlElement e5 = doc.CreateElement("bar"); + XmlElement e6 = doc.CreateElement("baz"); + e2.AppendChild(e6); + e2.AppendChild(e5); + + DOMDifferenceEngine d = new DOMDifferenceEngine(); + DiffExpecter ex = new DiffExpecter(ComparisonType.CHILD_NODELIST_SEQUENCE, + "/bar[1]", "/bar[1]"); + d.DifferenceListener += ex.ComparisonPerformed; + DifferenceEvaluator ev = delegate(Comparison comparison, + ComparisonResult outcome) { + if (outcome != ComparisonResult.EQUAL + && comparison.Type == ComparisonType.CHILD_NODELIST_SEQUENCE) { + return ComparisonResult.CRITICAL; + } + return DifferenceEvaluators.DefaultStopWhenDifferent(comparison, + outcome); + }; + d.DifferenceEvaluator = ev; + d.ElementSelector = ElementSelectors.ByName; + + Assert.AreEqual(ComparisonResult.CRITICAL, + d.CompareNodes(e1, new XPathContext(), + e2, new XPathContext())); + Assert.AreEqual(1, ex.invoked); + } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-08-31 16:08:36
|
Revision: 445 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=445&view=rev Author: bodewig Date: 2010-08-31 15:08:26 +0000 (Tue, 31 Aug 2010) Log Message: ----------- Create a legacy DifferenceEngine lookalike that is based on the new core code Added Paths: ----------- trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/NewDifferenceEngine.java trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_NewDifferenceEngine.java Copied: trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/NewDifferenceEngine.java (from rev 438, trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/DifferenceEngine.java) =================================================================== --- trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/NewDifferenceEngine.java (rev 0) +++ trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/NewDifferenceEngine.java 2010-08-31 15:08:26 UTC (rev 445) @@ -0,0 +1,355 @@ +/* +****************************************************************** +Copyright (c) 2001-2010, 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 javax.xml.transform.Source; + +import net.sf.xmlunit.builder.Input; +import net.sf.xmlunit.diff.Comparison; +import net.sf.xmlunit.diff.ComparisonListener; +import net.sf.xmlunit.diff.ComparisonResult; +import net.sf.xmlunit.diff.DOMDifferenceEngine; +import net.sf.xmlunit.diff.DifferenceEvaluator; +import net.sf.xmlunit.diff.DifferenceEvaluators; +import net.sf.xmlunit.diff.ElementSelector; +import net.sf.xmlunit.input.CommentLessSource; + +import org.w3c.dom.CDATASection; +import org.w3c.dom.Comment; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * Class that has responsibility for comparing Nodes and notifying a + * DifferenceListener of any differences or dissimilarities that are found. + * Knows how to compare namespaces and nested child nodes, but currently + * only compares nodes of type ELEMENT_NODE, CDATA_SECTION_NODE, + * COMMENT_NODE, DOCUMENT_TYPE_NODE, PROCESSING_INSTRUCTION_NODE and TEXT_NODE. + * Nodes of other types (eg ENTITY_NODE) will be skipped. + * <br />Examples and more at <a href="http://xmlunit.sourceforge.net"/>xmlunit. + * sourceforge.net</a> + * @see DifferenceListener#differenceFound(Difference) + */ +public class NewDifferenceEngine implements DifferenceConstants { + private static final Integer ZERO = Integer.valueOf(0); + + private final ComparisonController controller; + private MatchTracker matchTracker; + + /** + * Simple constructor that uses no MatchTracker at all. + * @param controller the instance used to determine whether a Difference + * detected by this class should halt further comparison or not + * @see ComparisonController#haltComparison(Difference) + */ + public NewDifferenceEngine(ComparisonController controller) { + this(controller, null); + } + + /** + * Simple constructor + * @param controller the instance used to determine whether a Difference + * detected by this class should halt further comparison or not + * @param matchTracker the instance that is notified on each + * successful match. May be null. + * @see ComparisonController#haltComparison(Difference) + * @see MatchTracker#matchFound(Difference) + */ + public NewDifferenceEngine(ComparisonController controller, + MatchTracker matchTracker) { + this.controller = controller; + this.matchTracker = matchTracker; + } + + /** + * @param matchTracker the instance that is notified on each + * successful match. May be null. + */ + public void setMatchTracker(MatchTracker matchTracker) { + this.matchTracker = matchTracker; + } + + /** + * Entry point for Node comparison testing. + * @param control Control XML to compare + * @param test Test XML to compare + * @param listener Notified of any {@link Difference differences} detected + * during node comparison testing + * @param elementQualifier Used to determine which elements qualify for + * comparison e.g. when a node has repeated child elements that may occur + * in any sequence and that sequence is not considered important. + */ + public void compare(Node control, Node test, DifferenceListener listener, + ElementQualifier elementQualifier) { + DOMDifferenceEngine engine = new DOMDifferenceEngine(); + if (matchTracker != null) { + engine + .addMatchListener(new MatchTracker2ComparisonListener(matchTracker)); + } + + DifferenceEvaluator controllerAsEvaluator = + new ComparisonController2DifferenceEvaluator(controller); + if (listener != null) { + DifferenceEvaluator l = + new DifferenceListener2DifferenceEvaluator(listener); + engine + .setDifferenceEvaluator(DifferenceEvaluators.first(l, + controllerAsEvaluator)); + } else { + engine + .setDifferenceEvaluator(controllerAsEvaluator); + } + if (elementQualifier != null) { + engine + .setElementSelector(new ElementQualifier2ElementSelector(elementQualifier)); + } + + Input.Builder ctrlBuilder = Input.fromNode(control); + Input.Builder tstBuilder = Input.fromNode(test); + + Source ctrlSource = ctrlBuilder.build(); + Source tstSource = tstBuilder.build(); + if (XMLUnit.getIgnoreComments()) { + ctrlSource = new CommentLessSource(ctrlSource); + tstSource = new CommentLessSource(tstSource); + } + + engine.compare(ctrlSource, tstSource); + } + + public static Difference toDifference(Comparison comp) { + Difference proto = null; + switch (comp.getType()) { + case ATTR_VALUE_EXPLICITLY_SPECIFIED: + proto = ATTR_VALUE_EXPLICITLY_SPECIFIED; + break; + case HAS_DOCTYPE_DECLARATION: + proto = HAS_DOCTYPE_DECLARATION; + break; + case DOCTYPE_NAME: + proto = DOCTYPE_NAME; + break; + case DOCTYPE_PUBLIC_ID: + proto = DOCTYPE_PUBLIC_ID; + break; + case DOCTYPE_SYSTEM_ID: + proto = DOCTYPE_SYSTEM_ID; + break; + case SCHEMA_LOCATION: + proto = SCHEMA_LOCATION; + break; + case NO_NAMESPACE_SCHEMA_LOCATION: + proto = NO_NAMESPACE_SCHEMA_LOCATION; + break; + case NODE_TYPE: + proto = NODE_TYPE; + break; + case NAMESPACE_PREFIX: + proto = NAMESPACE_PREFIX; + break; + case NAMESPACE_URI: + proto = NAMESPACE_URI; + break; + case TEXT_VALUE: + if (comp.getControlDetails().getTarget() instanceof CDATASection) { + proto = CDATA_VALUE; + } else if (comp.getControlDetails().getTarget() + instanceof Comment) { + proto = COMMENT_VALUE; + } + proto = TEXT_VALUE; + break; + case PROCESSING_INSTRUCTION_TARGET: + proto = PROCESSING_INSTRUCTION_TARGET; + break; + case PROCESSING_INSTRUCTION_DATA: + proto = PROCESSING_INSTRUCTION_DATA; + break; + case ELEMENT_TAG_NAME: + proto = ELEMENT_TAG_NAME; + break; + case ELEMENT_NUM_ATTRIBUTES: + proto = ELEMENT_NUM_ATTRIBUTES; + break; + case ATTR_VALUE: + proto = ATTR_VALUE; + break; + case CHILD_NODELIST_LENGTH: + Comparison.Detail cd = comp.getControlDetails(); + Comparison.Detail td = comp.getTestDetails(); + if (ZERO.equals(cd.getValue()) + || ZERO.equals(td.getValue())) { + return new Difference(HAS_CHILD_NODES, + new NodeDetail(String + .valueOf(!ZERO + .equals(cd + .getValue())), + (Node) cd.getTarget(), + cd.getXPath()), + new NodeDetail(String + .valueOf(!ZERO + .equals(td + .getValue())), + (Node) td.getTarget(), + td.getXPath())); + } + proto = CHILD_NODELIST_LENGTH; + break; + case CHILD_NODELIST_SEQUENCE: + proto = CHILD_NODELIST_SEQUENCE; + break; + case CHILD_LOOKUP: + proto = CHILD_NODE_NOT_FOUND; + break; + case ATTR_NAME_LOOKUP: + proto = ATTR_NAME_NOT_FOUND; + break; + default: + /* comparison doesn't match one of legacy's built-in differences */ + break; + } + if (proto != null) { + return new Difference(proto, toNodeDetail(comp.getControlDetails()), + toNodeDetail(comp.getTestDetails())); + } + return null; + } + + public static NodeDetail toNodeDetail(Comparison.Detail detail) { + return new NodeDetail(String.valueOf(detail.getValue()), + (Node) detail.getTarget(), + detail.getXPath()); + } + + public static class MatchTracker2ComparisonListener + implements ComparisonListener { + private final MatchTracker mt; + + public MatchTracker2ComparisonListener(MatchTracker m) { + mt = m; + } + + public void comparisonPerformed(Comparison comparison, + ComparisonResult outcome) { + Difference diff = toDifference(comparison); + if (diff != null) { + mt.matchFound(diff); + } + } + } + + public static class DifferenceListener2ComparisonListener + implements ComparisonListener { + private final DifferenceListener dl; + + public DifferenceListener2ComparisonListener(DifferenceListener dl) { + this.dl = dl; + } + + public void comparisonPerformed(Comparison comparison, + ComparisonResult outcome) { + Difference diff = toDifference(comparison); + if (diff != null) { + dl.differenceFound(diff); + } + } + } + + public static class ComparisonController2DifferenceEvaluator + implements DifferenceEvaluator { + private final ComparisonController cc; + public ComparisonController2DifferenceEvaluator(ComparisonController c) { + cc = c; + } + + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult outcome) { + if (outcome != ComparisonResult.EQUAL) { + Difference diff = toDifference(comparison); + if (diff != null && cc.haltComparison(diff)) { + return ComparisonResult.CRITICAL; + } + } + return outcome; + } + } + + public static class ElementQualifier2ElementSelector + implements ElementSelector { + private final ElementQualifier eq; + + public ElementQualifier2ElementSelector(ElementQualifier eq) { + this.eq = eq; + } + + public boolean canBeCompared(Element controlElement, + Element testElement) { + return eq.qualifyForComparison(controlElement, testElement); + } + + } + + public static class DifferenceListener2DifferenceEvaluator + implements DifferenceEvaluator { + private final DifferenceListener dl; + + public DifferenceListener2DifferenceEvaluator(DifferenceListener dl) { + this.dl = dl; + } + + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult outcome) { + if (outcome != ComparisonResult.EQUAL) { + Difference diff = toDifference(comparison); + if (diff != null) { + switch (dl.differenceFound(diff)) { + case DifferenceListener + .RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL: + return ComparisonResult.EQUAL; + case DifferenceListener + .RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR: + return ComparisonResult.SIMILAR; + case DifferenceListener + .RETURN_UPGRADE_DIFFERENCE_NODES_DIFFERENT: + return ComparisonResult.DIFFERENT; + } + } + } + return outcome; + } + } +} Copied: trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_NewDifferenceEngine.java (from rev 438, trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_DifferenceEngine.java) =================================================================== --- trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_NewDifferenceEngine.java (rev 0) +++ trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_NewDifferenceEngine.java 2010-08-31 15:08:26 UTC (rev 445) @@ -0,0 +1,591 @@ +/* +****************************************************************** +Copyright (c) 2001-2008,2010 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.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; + +import javax.xml.parsers.DocumentBuilder; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.w3c.dom.Attr; +import org.w3c.dom.CDATASection; +import org.w3c.dom.Comment; +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; +import org.xml.sax.SAXException; + +/** + * JUnit test for NewDifferenceEngine + */ +public class test_NewDifferenceEngine extends TestCase implements DifferenceConstants { + private CollectingDifferenceListener listener; + private NewDifferenceEngine engine; + private Document document; + + private final ComparisonController PSEUDO_DIFF = new SimpleComparisonController(); + private final ComparisonController PSEUDO_DETAILED_DIFF = new NeverHaltingComparisonController(); + + private final static ElementQualifier + DEFAULT_ELEMENT_QUALIFIER = new ElementNameQualifier(); + private final static ElementQualifier SEQUENCE_ELEMENT_QUALIFIER = null; + private final static String TEXT_A = "the pack on my back is aching"; + private final static String TEXT_B = "the straps seem to cut me like a knife"; + private final static String COMMENT_A = "Im no clown I wont back down"; + private final static String COMMENT_B = "dont need you to tell me whats going down"; + private final static String[] PROC_A = {"down", "down down"}; + private final static String[] PROC_B = {"dadada", "down"}; + private final static String CDATA_A = "I'm standing alone, you're weighing the gold"; + private final static String CDATA_B = "I'm watching you sinking... Fools Gold"; + private final static String ATTR_A = "These boots were made for walking"; + private final static String ATTR_B = "The marquis de sade never wore no boots like these"; + + public void testCompareNode() throws Exception { + Document controlDocument = XMLUnit.buildControlDocument("<root>" + + "<!-- " + COMMENT_A + " -->" + + "<?" + PROC_A[0] + " "+ PROC_A[1] + " ?>" + + "<elem attr=\"" + ATTR_A + "\">" + TEXT_A + "</elem></root>"); + Document testDocument = XMLUnit.buildTestDocument("<root>" + + "<!-- " + COMMENT_B + " -->" + + "<?" + PROC_B[0] + " "+ PROC_B[1] + " ?>" + + "<elem attr=\"" + ATTR_B + "\">" + TEXT_B + "</elem></root>"); + + engine.compare(controlDocument, testDocument, listener, null); + + Node control = controlDocument.getDocumentElement().getFirstChild(); + Node test = testDocument.getDocumentElement().getFirstChild(); + + do { + resetListener(); + engine.compare(control, test, listener, null); + assertEquals(true, -1 != listener.comparingWhat); + assertEquals(false, listener.nodesSkipped); + + resetListener(); + engine.compare(control, control, listener, null); + assertEquals(-1, listener.comparingWhat); + + control = control.getNextSibling(); + test = test.getNextSibling(); + } while (control != null); + } + + public void testXpathLocation1() throws Exception { + String control = "<dvorak><keyboard/><composer/></dvorak>"; + String test = "<qwerty><keyboard/></qwerty>"; + listenToDifferences(control, test, SEQUENCE_ELEMENT_QUALIFIER); + assertEquals("1st control xpath", "/dvorak[1]", listener.controlXpath); + assertEquals("1st test xpath", "/qwerty[1]", listener.testXpath); + } + + public void testXpathLocation2() throws Exception { + String control = "<dvorak><keyboard/><composer/></dvorak>"; + String test = "<qwerty><keyboard/></qwerty>"; + String start = "<a>", end = "</a>"; + listenToDifferences(start + control + end, start + test + end, + SEQUENCE_ELEMENT_QUALIFIER); + assertEquals("2nd control xpath", "/a[1]/dvorak[1]", listener.controlXpath); + assertEquals("2nd test xpath", "/a[1]/qwerty[1]", listener.testXpath); + } + + public void testXpathLocation3() throws Exception { + String control = "<stuff><wood type=\"rough\"/></stuff>"; + String test = "<stuff><wood type=\"smooth\"/></stuff>"; + listenToDifferences(control, test); + assertEquals("3rd control xpath", "/stuff[1]/wood[1]/@type", listener.controlXpath); + assertEquals("3rd test xpath", "/stuff[1]/wood[1]/@type", listener.testXpath); + } + + public void testXpathLocation4() throws Exception { + String control = "<stuff><glass colour=\"clear\"/><glass colour=\"green\"/></stuff>"; + String test = "<stuff><glass colour=\"clear\"/><glass colour=\"blue\"/></stuff>";; + listenToDifferences(control, test); + assertEquals("4th control xpath", "/stuff[1]/glass[2]/@colour", listener.controlXpath); + assertEquals("4th test xpath", "/stuff[1]/glass[2]/@colour", listener.testXpath); + } + + public void testXpathLocation5() throws Exception { + String control = "<stuff><wood>maple</wood><wood>oak</wood></stuff>"; + String test = "<stuff><wood>maple</wood><wood>ash</wood></stuff>"; + listenToDifferences(control, test); + assertEquals("5th control xpath", "/stuff[1]/wood[2]/text()[1]", listener.controlXpath); + assertEquals("5th test xpath", "/stuff[1]/wood[2]/text()[1]", listener.testXpath); + } + + public void testXpathLocation6() throws Exception { + String control = "<stuff><list><wood/><glass/></list><item/></stuff>"; + String test = "<stuff><list><wood/><glass/></list><item>description</item></stuff>"; + listenToDifferences(control, test); + assertEquals("6th control xpath", "/stuff[1]/item[1]", listener.controlXpath); + assertEquals("6th test xpath", "/stuff[1]/item[1]", listener.testXpath); + } + + public void testXpathLocation7() throws Exception { + String control = "<stuff><list><wood/></list></stuff>"; + String test = "<stuff><list><glass/></list></stuff>"; + listenToDifferences(control, test, SEQUENCE_ELEMENT_QUALIFIER); + assertEquals("7th control xpath", "/stuff[1]/list[1]/wood[1]", listener.controlXpath); + assertEquals("7th test xpath", "/stuff[1]/list[1]/glass[1]", listener.testXpath); + } + + public void testXpathLocation8() throws Exception { + String control = "<stuff><list><!--wood--></list></stuff>"; + String test = "<stuff><list><!--glass--></list></stuff>"; + listenToDifferences(control, test); + assertEquals("8th control xpath", "/stuff[1]/list[1]/comment()[1]", listener.controlXpath); + assertEquals("8th test xpath", "/stuff[1]/list[1]/comment()[1]", listener.testXpath); + } + + public void testXpathLocation9() throws Exception { + String control = "<stuff><list/><?wood rough?><list/></stuff>"; + String test = "<stuff><list/><?glass clear?><list/></stuff>"; + listenToDifferences(control, test); + assertEquals("9th control xpath", "/stuff[1]/processing-instruction()[1]", + listener.controlXpath); + assertEquals("9th test xpath", "/stuff[1]/processing-instruction()[1]", + listener.testXpath); + } + + public void testXpathLocation10() throws Exception { + String control = "<stuff><list/>list<![CDATA[wood]]></stuff>"; + String test = "<stuff><list/>list<![CDATA[glass]]></stuff>"; + listenToDifferences(control, test); + assertEquals("10th control xpath", "/stuff[1]/text()[2]", + listener.controlXpath); + assertEquals("10th test xpath", "/stuff[1]/text()[2]", + listener.testXpath); + } + + public void testXpathLocation11() throws Exception { + String control = "<stuff><list><item/></list></stuff>"; + String test = "<stuff><list>item text</list></stuff>"; + listenToDifferences(control, test); + assertEquals("11th control xpath", "/stuff[1]/list[1]/item[1]", + listener.controlXpath); + // this is different from DifferenceEngine - the test node is null + // if there is no match + assertNull("11th test xpath", listener.testXpath); + } + + public void testXpathLocation12() throws Exception { + engine = new NewDifferenceEngine(PSEUDO_DETAILED_DIFF); + String control = "<stuff><item id=\"1\"/><item id=\"2\"/></stuff>"; + String test = "<stuff><item id=\"1\"/></stuff>"; + listenToDifferences(control, test); + assertEquals("12th control xpath", "/stuff[1]/item[2]", + listener.controlXpath); + // this is different from DifferenceEngine - the test node is null + // if there is no match + assertNull("12th test xpath", listener.testXpath); + } + + public void testXpathLocation13() throws Exception { + engine = new NewDifferenceEngine(PSEUDO_DETAILED_DIFF); + String control = "<stuff><item id=\"1\"/><item id=\"2\"/></stuff>"; + String test = "<stuff><?item data?></stuff>"; + listenToDifferences(control, test); + // 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); + assertNull("13th test xpath", listener.testXpath); + } + + public void testXpathLocation14() throws Exception { + engine = new NewDifferenceEngine(PSEUDO_DETAILED_DIFF); + String control = "<stuff><thing id=\"1\"/><item id=\"2\"/></stuff>"; + String test = "<stuff><item id=\"2\"/><item id=\"1\"/></stuff>"; + listenToDifferences(control, test); + // DifferenceEngine matches test node //item[2] with control + // node //item[1] and then generates a difference of attribute + // vales by default. + // NewDifferenceEngine has a "no match" for test node + // //item[2] as last comparison + assertNull("14th control xpath", listener.controlXpath); + assertEquals("14th test xpath", "/stuff[1]/item[2]", + listener.testXpath); + } + + public void testIssue1027863() throws Exception { + engine = new NewDifferenceEngine(PSEUDO_DIFF); + String control = "<stuff><item id=\"1\"><thing/></item></stuff>"; + String test = "<stuff><item id=\"2\"/></stuff>"; + listenToDifferences(control, test); + assertEquals("15th difference type", + NewDifferenceEngine.HAS_CHILD_NODES_ID, + listener.comparingWhat); + assertEquals("15th difference control value", "true", + listener.expected); + assertEquals("15th difference test value", "false", + listener.actual); + assertEquals("15th control xpath", "/stuff[1]/item[1]", + listener.controlXpath); + assertEquals("15th test xpath", "/stuff[1]/item[1]", + listener.testXpath); + } + + 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); + } + + 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); + } + + 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); + } + + public void testMatchTrackerSetViaConstructor() throws Exception { + Element control = document.createElement("foo"); + Element test = document.createElement("foo"); + final int[] count = new int[1]; + NewDifferenceEngine d = + new NewDifferenceEngine(new SimpleComparisonController(), + new MatchTracker() { + public void matchFound(Difference d) { + count[0]++; + } + }); + d.compare(control, test, listener, null); + // NODE_TYPE(Element), NAMESPACE_URI(none), + // NAMESPACE_PREFIX(none), HAS_CHILD_NODES(false), + // ELEMENT_TAG_NAME(foo), ELEMENT_NUM_ATTRIBUTE(none), + // SCHEMA_LOCATION(none), NO_NAMESPACE_SCHEMA_LOCATION(none) + assertEquals(8, count[0]); + } + + public void testMatchTrackerSetViaSetter() throws Exception { + Element control = document.createElement("foo"); + Element test = document.createElement("foo"); + final int[] count = new int[1]; + engine.setMatchTracker(new MatchTracker() { + public void matchFound(Difference d) { + count[0]++; + } + }); + engine.compare(control, test, listener, null); + // NODE_TYPE(Element), NAMESPACE_URI(none), + // NAMESPACE_PREFIX(none), HAS_CHILD_NODES(false), + // ELEMENT_TAG_NAME(foo), ELEMENT_NUM_ATTRIBUTE(none), + // SCHEMA_LOCATION(none), NO_NAMESPACE_SCHEMA_LOCATION(none) + assertEquals(8, count[0]); + } + + /** + * @see http://sourceforge.net/forum/forum.php?thread_id=3284504&forum_id=73274 + */ + public void testNamespaceAttributeDifferences() throws Exception { + String control = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" + + "<ns0:Message xmlns:ns0 = \"http://mynamespace\">" + + "<ns0:EventHeader>" + + "<ns0:EventID>9999</ns0:EventID>" + + "<ns0:MessageID>1243409665297</ns0:MessageID>" + + "<ns0:MessageVersionID>1.0</ns0:MessageVersionID>" + + "<ns0:EventName>TEST-EVENT</ns0:EventName>" + + "<ns0:BWDomain>TEST</ns0:BWDomain>" + + "<ns0:DateTimeStamp>2009-01-01T12:00:00</ns0:DateTimeStamp>" + + "<ns0:SchemaPayloadRef>anything</ns0:SchemaPayloadRef>" + + "<ns0:MessageURI>anything</ns0:MessageURI>" + + "<ns0:ResendFlag>F</ns0:ResendFlag>" + + "</ns0:EventHeader>" + + "<ns0:EventBody>" + + "<ns0:XMLContent>" + + "<xyz:root xmlns:xyz=\"http://test.com/xyz\">" + + "<xyz:test1>A</xyz:test1>" + + "<xyz:test2>B</xyz:test2>" + + "</xyz:root>" + + "</ns0:XMLContent>" + + "</ns0:EventBody>" + + "</ns0:Message>"; + String test = + "<abc:Message xmlns:abc=\"http://mynamespace\" xmlns:xyz=\"http://test.com/xyz\">" + + "<abc:EventHeader>" + + "<abc:EventID>9999</abc:EventID>" + + "<abc:MessageID>1243409665297</abc:MessageID>" + + "<abc:MessageVersionID>1.0</abc:MessageVersionID>" + + "<abc:EventName>TEST-EVENT</abc:EventName>" + + "<abc:BWDomain>TEST</abc:BWDomain>" + + "<abc:DateTimeStamp>2009-01-01T12:00:00</abc:DateTimeStamp>" + + "<abc:SchemaPayloadRef>anything</abc:SchemaPayloadRef>" + + "<abc:MessageURI>anything</abc:MessageURI>" + + "<abc:ResendFlag>F</abc:ResendFlag>" + + "</abc:EventHeader>" + + "<abc:EventBody>" + + "<abc:XMLContent>" + + "<xyz:root>" + + "<xyz:test1>A</xyz:test1>" + + "<xyz:test2>B</xyz:test2>" + + "</xyz:root>" + + "</abc:XMLContent>" + + "</abc:EventBody>" + + "</abc:Message>"; + listenToDifferences(control, test); + assertFalse(listener.different); + } + + private void listenToDifferences(String control, String test) + throws SAXException, IOException { + listenToDifferences(control, test, DEFAULT_ELEMENT_QUALIFIER); + } + + private void listenToDifferences(String control, String test, + ElementQualifier eq) + throws SAXException, IOException { + Document controlDoc = XMLUnit.buildControlDocument(control); + Document testDoc = XMLUnit.buildTestDocument(test); + engine.compare(controlDoc, testDoc, listener, eq); + } + + + private void resetListener() { + listener = new CollectingDifferenceListener(); + } + + public void setUp() throws Exception { + resetListener(); + engine = new NewDifferenceEngine(PSEUDO_DIFF); + DocumentBuilder documentBuilder = XMLUnit.newControlParser(); + document = documentBuilder.newDocument(); + } + + private class SimpleComparisonController implements ComparisonController { + public boolean haltComparison(Difference afterDifference) { + return !afterDifference.isRecoverable(); + } + } + + private class NeverHaltingComparisonController implements ComparisonController { + public boolean haltComparison(Difference afterDifference) { + return false; + } + } + + private class CollectingDifferenceListener implements DifferenceListener { + public String expected; + public String actual; + public Node control; + public Node test; + public int comparingWhat = -1; + public boolean different = false; + public boolean nodesSkipped = false; + public String controlXpath; + public String testXpath; + private boolean tracing = false; + public int differenceFound(Difference difference) { + if (tracing) { + System.out.println("df: " + difference.toString()); + } + assertNotNull("difference not null", difference); + assertNotNull("control node detail not null", difference.getControlNodeDetail()); + assertNotNull("test node detail not null", difference.getTestNodeDetail()); + this.expected = difference.getControlNodeDetail().getValue(); + this.actual = difference.getTestNodeDetail().getValue(); + this.control = difference.getControlNodeDetail().getNode(); + this.test = difference.getTestNodeDetail().getNode(); + this.comparingWhat = difference.getId(); + this.different = !difference.isRecoverable(); + this.controlXpath = difference.getControlNodeDetail().getXpathLocation(); + this.testXpath = difference.getTestNodeDetail().getXpathLocation(); + return RETURN_ACCEPT_DIFFERENCE; + } + public void skippedComparison(Node control, Node test) { + nodesSkipped = true; + } + public void setTrace(boolean active) { + 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...> - 2010-09-02 12:00:57
|
Revision: 453 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=453&view=rev Author: bodewig Date: 2010-09-02 12:00:51 +0000 (Thu, 02 Sep 2010) Log Message: ----------- change default value for legacy's ignoreAttributeOrder Modified Paths: -------------- trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/XMLUnit.java trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_DifferenceEngine.java Modified: trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/XMLUnit.java =================================================================== --- trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/XMLUnit.java 2010-09-02 10:59:43 UTC (rev 452) +++ trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/XMLUnit.java 2010-09-02 12:00:51 UTC (rev 453) @@ -79,7 +79,7 @@ private static boolean ignoreComments = false; private static boolean normalize = false; private static boolean normalizeWhitespace = false; - private static boolean ignoreAttributeOrder = false; + private static boolean ignoreAttributeOrder = true; private static String xsltVersion = "1.0"; private static String xpathFactoryName = null; private static boolean expandEntities = false; @@ -785,12 +785,11 @@ * 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 + * documents, still XMLUnit can 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> + * attributes. Set this option to true to compare the order.</p> * - * <p>The default value is false for backwards compatibility - * reasons.</p> + * <p>The default value is true</p> */ public static void setIgnoreAttributeOrder(boolean b) { ignoreAttributeOrder = b; @@ -800,12 +799,11 @@ * 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 + * documents, still XMLUnit can 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> + * attributes. Set this option to true to compare the order.</p> * - * <p>The default value is false for backwards compatibility - * reasons.</p> + * <p>The default value is true</p> */ public static boolean getIgnoreAttributeOrder() { return ignoreAttributeOrder; @@ -893,6 +891,14 @@ } /** + * Reset whether to compare unmatched control nodes to unmatched + * test nodes to its default setting. + */ + static void clearCompareUnmatched() { + compareUnmatched = null; + } + + /** * Whether unmatched control nodes should be compared to unmatched * test nodes. * Modified: trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_DifferenceEngine.java =================================================================== --- trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_DifferenceEngine.java 2010-09-02 10:59:43 UTC (rev 452) +++ trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_DifferenceEngine.java 2010-09-02 12:00:51 UTC (rev 453) @@ -667,14 +667,14 @@ } public void testAttributeSequence() throws Exception { - testAttributeSequence(ATTR_SEQUENCE_ID); - resetListener(); - XMLUnit.setIgnoreAttributeOrder(true); + XMLUnit.setIgnoreAttributeOrder(false); try { - testAttributeSequence(-1); + testAttributeSequence(ATTR_SEQUENCE_ID); } finally { - XMLUnit.setIgnoreAttributeOrder(false); + XMLUnit.setIgnoreAttributeOrder(true); } + resetListener(); + testAttributeSequence(-1); } private void testAttributeSequence(int expected) throws Exception { @@ -701,14 +701,14 @@ } public void testAttributeSequenceNS() throws Exception { - testAttributeSequenceNS(ATTR_SEQUENCE_ID); - resetListener(); - XMLUnit.setIgnoreAttributeOrder(true); + XMLUnit.setIgnoreAttributeOrder(false); try { - testAttributeSequenceNS(-1); + testAttributeSequenceNS(ATTR_SEQUENCE_ID); } finally { - XMLUnit.setIgnoreAttributeOrder(false); + XMLUnit.setIgnoreAttributeOrder(true); } + resetListener(); + testAttributeSequenceNS(-1); } private void testAttributeSequenceNS(int expected) throws Exception { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |