You can subscribe to this list here.
2007 |
Jan
|
Feb
(3) |
Mar
(18) |
Apr
(39) |
May
(15) |
Jun
(12) |
Jul
(3) |
Aug
(23) |
Sep
|
Oct
(1) |
Nov
(1) |
Dec
(3) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2008 |
Jan
(21) |
Feb
(23) |
Mar
(33) |
Apr
(8) |
May
(1) |
Jun
(22) |
Jul
|
Aug
(1) |
Sep
(1) |
Oct
(6) |
Nov
|
Dec
(11) |
2009 |
Jan
(5) |
Feb
|
Mar
(2) |
Apr
(24) |
May
(36) |
Jun
(18) |
Jul
(2) |
Aug
(3) |
Sep
(9) |
Oct
(3) |
Nov
(1) |
Dec
|
2010 |
Jan
(5) |
Feb
(3) |
Mar
|
Apr
(15) |
May
(24) |
Jun
(11) |
Jul
(8) |
Aug
(34) |
Sep
(42) |
Oct
|
Nov
|
Dec
|
2011 |
Jan
(13) |
Feb
(32) |
Mar
(35) |
Apr
(31) |
May
(33) |
Jun
(30) |
Jul
(32) |
Aug
(31) |
Sep
(30) |
Oct
(31) |
Nov
(32) |
Dec
(31) |
2012 |
Jan
(35) |
Feb
(31) |
Mar
(31) |
Apr
(30) |
May
(31) |
Jun
(34) |
Jul
(23) |
Aug
(30) |
Sep
(30) |
Oct
(29) |
Nov
(30) |
Dec
(32) |
2013 |
Jan
(25) |
Feb
(39) |
Mar
(1) |
Apr
(18) |
May
(1) |
Jun
|
Jul
(1) |
Aug
(20) |
Sep
(41) |
Oct
(32) |
Nov
(9) |
Dec
(31) |
2014 |
Jan
(31) |
Feb
(30) |
Mar
(34) |
Apr
(60) |
May
(31) |
Jun
(28) |
Jul
(32) |
Aug
(28) |
Sep
(26) |
Oct
(32) |
Nov
(43) |
Dec
(115) |
2015 |
Jan
(106) |
Feb
(101) |
Mar
(51) |
Apr
(32) |
May
(63) |
Jun
(18) |
Jul
|
Aug
(18) |
Sep
|
Oct
(1) |
Nov
(84) |
Dec
(63) |
2016 |
Jan
(26) |
Feb
(17) |
Mar
(104) |
Apr
(30) |
May
(6) |
Jun
(30) |
Jul
|
Aug
|
Sep
|
Oct
(3) |
Nov
(48) |
Dec
(22) |
2017 |
Jan
(15) |
Feb
(29) |
Mar
(43) |
Apr
(29) |
May
(25) |
Jun
(28) |
Jul
(62) |
Aug
(35) |
Sep
(35) |
Oct
(72) |
Nov
(10) |
Dec
(4) |
2018 |
Jan
(7) |
Feb
(4) |
Mar
|
Apr
(46) |
May
(20) |
Jun
(12) |
Jul
(9) |
Aug
(42) |
Sep
(4) |
Oct
(17) |
Nov
(32) |
Dec
(31) |
2019 |
Jan
(21) |
Feb
(14) |
Mar
|
Apr
(74) |
May
(25) |
Jun
(43) |
Jul
(2) |
Aug
(1) |
Sep
|
Oct
(2) |
Nov
|
Dec
(10) |
2020 |
Jan
(1) |
Feb
|
Mar
(26) |
Apr
(8) |
May
(62) |
Jun
(4) |
Jul
(25) |
Aug
|
Sep
(21) |
Oct
(24) |
Nov
(26) |
Dec
(9) |
2021 |
Jan
|
Feb
(4) |
Mar
|
Apr
|
May
|
Jun
|
Jul
(1) |
Aug
(1) |
Sep
(1) |
Oct
(11) |
Nov
(1) |
Dec
(12) |
2022 |
Jan
(47) |
Feb
|
Mar
(2) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(14) |
2023 |
Jan
(3) |
Feb
|
Mar
(60) |
Apr
(9) |
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
2024 |
Jan
(5) |
Feb
|
Mar
|
Apr
(10) |
May
(1) |
Jun
|
Jul
|
Aug
(17) |
Sep
(2) |
Oct
|
Nov
|
Dec
(1) |
2025 |
Jan
|
Feb
|
Mar
(88) |
Apr
(64) |
May
(47) |
Jun
(20) |
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <bo...@us...> - 2010-05-20 11:26:47
|
Revision: 397 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=397&view=rev Author: bodewig Date: 2010-05-20 11:26:40 +0000 (Thu, 20 May 2010) Log Message: ----------- more tests Modified Paths: -------------- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/ConvertTest.java trunk/xmlunit/src/tests/net-core/util/ConvertTest.cs Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/ConvertTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/ConvertTest.java 2010-05-20 11:20:38 UTC (rev 396) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/ConvertTest.java 2010-05-20 11:26:40 UTC (rev 397) @@ -28,6 +28,7 @@ import org.w3c.dom.Node; import org.xml.sax.InputSource; +import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.hamcrest.core.Is.is; @@ -84,6 +85,15 @@ convertToDocumentAndAssert(new SAXSource(s)); } + @Test public void domElementToDocument() throws Exception { + DocumentBuilder b = + DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document d = b.parse(new File(TestResources.ANIMAL_FILE)); + convertToDocumentAndAssert(new DOMSource(d.getDocumentElement())); + assertNotSame(d, + Convert.toDocument(new DOMSource(d.getDocumentElement()))); + } + private static void convertToNodeAndAssert(Source s) { Node n = Convert.toNode(s); Document d = n instanceof Document ? (Document) n : n.getOwnerDocument(); @@ -107,4 +117,13 @@ convertToNodeAndAssert(new SAXSource(s)); } + @Test public void domElementToNode() throws Exception { + DocumentBuilder b = + DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document d = b.parse(new File(TestResources.ANIMAL_FILE)); + convertToNodeAndAssert(new DOMSource(d.getDocumentElement())); + assertSame(d.getDocumentElement(), + Convert.toNode(new DOMSource(d.getDocumentElement()))); + } + } Modified: trunk/xmlunit/src/tests/net-core/util/ConvertTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/util/ConvertTest.cs 2010-05-20 11:20:38 UTC (rev 396) +++ trunk/xmlunit/src/tests/net-core/util/ConvertTest.cs 2010-05-20 11:26:40 UTC (rev 397) @@ -41,6 +41,15 @@ Assert.AreSame(d, Convert.ToDocument(new DOMSource(d))); } + [Test] + public void DomElementToDocument() { + XmlDocument d = new XmlDocument(); + d.Load(TestResources.ANIMAL_FILE); + ConvertToDocumentAndAssert(new DOMSource(d.DocumentElement)); + Assert.AreNotSame(d, Convert + .ToDocument(new DOMSource(d.DocumentElement))); + } + private static void ConvertToNodeAndAssert(ISource s) { XmlNode n = Convert.ToNode(s); DocumentAsserts(n is XmlDocument @@ -59,5 +68,14 @@ ConvertToNodeAndAssert(new DOMSource(d)); Assert.AreSame(d, Convert.ToNode(new DOMSource(d))); } + + [Test] + public void DomElementToNode() { + XmlDocument d = new XmlDocument(); + d.Load(TestResources.ANIMAL_FILE); + ConvertToNodeAndAssert(new DOMSource(d.DocumentElement)); + Assert.AreSame(d.DocumentElement, + Convert.ToNode(new DOMSource(d.DocumentElement))); + } } } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-05-20 11:20:44
|
Revision: 396 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=396&view=rev Author: bodewig Date: 2010-05-20 11:20:38 +0000 (Thu, 20 May 2010) Log Message: ----------- convert a(n) (I)Source to a DOM Node Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Convert.java trunk/xmlunit/src/main/net-core/util/Convert.cs trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/ConvertTest.java trunk/xmlunit/src/tests/net-core/util/ConvertTest.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Convert.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Convert.java 2010-05-19 16:18:11 UTC (rev 395) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Convert.java 2010-05-20 11:20:38 UTC (rev 396) @@ -76,7 +76,7 @@ * * <p>If the source is a {@link DOMSource} holding a Document * Node, this one will be returned. Otherwise {@link - * toInputSource} and a namespace aware DocumentBuilder (created + * #toInputSource} and a namespace aware DocumentBuilder (created * by the default DocumentBuilderFactory) will be used to read the * source. This may involve an XSLT identity transform in * toInputSource.</p> @@ -92,7 +92,7 @@ * * <p>If the source is a {@link DOMSource} holding a Document * Node, this one will be returned. Otherwise {@link - * toInputSource} and a namespace aware DocumentBuilder (created + * #toInputSource} and a namespace aware DocumentBuilder (created * by given DocumentBuilderFactory) will be used to read the * source. This may involve an XSLT identity transform in * toInputSource.</p> @@ -132,13 +132,42 @@ } private static Document tryExtractDocFromDOMSource(Source s) { + Node n = tryExtractNodeFromDOMSource(s); + if (n != null && n instanceof Document) { + @SuppressWarnings("unchecked") Document d = (Document) n; + return d; + } + return null; + } + + /** + * Creates a DOM Node from a TraX Source. + * + * <p>If the source is a {@link DOMSource} its Node will be + * returned, otherwise this delegates to {@link #toDocument}.</p> + */ + public static Node toNode(Source s) { + Node n = tryExtractNodeFromDOMSource(s); + return n != null ? n + : toDocument(s, DocumentBuilderFactory.newInstance()); + } + + /** + * Creates a DOM Node from a TraX Source. + * + * <p>If the source is a {@link DOMSource} its Node will be + * returned, otherwise this delegates to {@link #toDocument}.</p> + */ + public static Node toNode(Source s, + DocumentBuilderFactory factory) { + Node n = tryExtractNodeFromDOMSource(s); + return n != null ? n : toDocument(s, factory); + } + + private static Node tryExtractNodeFromDOMSource(Source s) { if (s instanceof DOMSource) { @SuppressWarnings("unchecked") DOMSource ds = (DOMSource) s; - Node n = ds.getNode(); - if (n instanceof Document) { - @SuppressWarnings("unchecked") Document d = (Document) n; - return d; - } + return ds.getNode(); } return null; } Modified: trunk/xmlunit/src/main/net-core/util/Convert.cs =================================================================== --- trunk/xmlunit/src/main/net-core/util/Convert.cs 2010-05-19 16:18:11 UTC (rev 395) +++ trunk/xmlunit/src/main/net-core/util/Convert.cs 2010-05-20 11:20:38 UTC (rev 396) @@ -40,6 +40,18 @@ } /// <summary> + /// Creates a DOM Node from an ISource. + /// </summary> + /// <remarks> + /// Unless the source is a DOMSource this will return the same + /// result as ToDocument. + /// </remarks> + public static XmlNode ToNode(ISource s) { + DOMSource ds = s as DOMSource; + return ds != null ? ds.Node : ToDocument(s); + } + + /// <summary> /// Creates a namespace resolver from a Map prefix => /// Namespace URI. /// </summary> Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/ConvertTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/ConvertTest.java 2010-05-19 16:18:11 UTC (rev 395) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/ConvertTest.java 2010-05-20 11:20:38 UTC (rev 396) @@ -25,6 +25,7 @@ import org.hamcrest.core.IsNull; import org.junit.Test; import org.w3c.dom.Document; +import org.w3c.dom.Node; import org.xml.sax.InputSource; import static org.junit.Assert.assertSame; @@ -83,4 +84,27 @@ convertToDocumentAndAssert(new SAXSource(s)); } + private static void convertToNodeAndAssert(Source s) { + Node n = Convert.toNode(s); + Document d = n instanceof Document ? (Document) n : n.getOwnerDocument(); + documentAsserts(d); + } + + @Test public void streamSourceToNode() throws Exception { + convertToNodeAndAssert(new StreamSource(new File(TestResources.ANIMAL_FILE))); + } + + @Test public void domSourceToNode() throws Exception { + DocumentBuilder b = + DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document d = b.parse(new File(TestResources.ANIMAL_FILE)); + convertToNodeAndAssert(new DOMSource(d)); + assertSame(d, Convert.toNode(new DOMSource(d))); + } + + @Test public void saxSourceToNode() throws Exception { + InputSource s = new InputSource(new FileInputStream(TestResources.ANIMAL_FILE)); + convertToNodeAndAssert(new SAXSource(s)); + } + } Modified: trunk/xmlunit/src/tests/net-core/util/ConvertTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/util/ConvertTest.cs 2010-05-19 16:18:11 UTC (rev 395) +++ trunk/xmlunit/src/tests/net-core/util/ConvertTest.cs 2010-05-20 11:20:38 UTC (rev 396) @@ -20,7 +20,10 @@ [TestFixture] public class ConvertTest { private static void ConvertToDocumentAndAssert(ISource s) { - XmlDocument d = Convert.ToDocument(s); + DocumentAsserts(Convert.ToDocument(s)); + } + + private static void DocumentAsserts(XmlDocument d) { Assert.IsNotNull(d); Assert.AreEqual("animal", d.DocumentElement.Name); } @@ -37,5 +40,24 @@ ConvertToDocumentAndAssert(new DOMSource(d)); Assert.AreSame(d, Convert.ToDocument(new DOMSource(d))); } + + private static void ConvertToNodeAndAssert(ISource s) { + XmlNode n = Convert.ToNode(s); + DocumentAsserts(n is XmlDocument + ? n as XmlDocument : n.OwnerDocument); + } + + [Test] + public void StreamSourceToNode() { + ConvertToNodeAndAssert(new StreamSource(TestResources.ANIMAL_FILE)); + } + + [Test] + public void DomSourceToNode() { + XmlDocument d = new XmlDocument(); + d.Load(TestResources.ANIMAL_FILE); + ConvertToNodeAndAssert(new DOMSource(d)); + Assert.AreSame(d, Convert.ToNode(new DOMSource(d))); + } } } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-05-19 16:18:18
|
Revision: 395 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=395&view=rev Author: bodewig Date: 2010-05-19 16:18:11 +0000 (Wed, 19 May 2010) Log Message: ----------- convert from (I)Source to DOm Document Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Convert.java trunk/xmlunit/src/main/net-core/input/DOMSource.cs trunk/xmlunit/src/main/net-core/util/Convert.cs trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/ConvertTest.java Added Paths: ----------- trunk/xmlunit/src/tests/net-core/util/ConvertTest.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Convert.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Convert.java 2010-05-19 10:26:31 UTC (rev 394) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Convert.java 2010-05-19 16:18:11 UTC (rev 395) @@ -23,14 +23,19 @@ import java.util.Map; import javax.xml.XMLConstants; import javax.xml.namespace.NamespaceContext; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import net.sf.xmlunit.exceptions.ConfigurationException; import net.sf.xmlunit.exceptions.XMLUnitException; +import org.w3c.dom.Document; +import org.w3c.dom.Node; import org.xml.sax.InputSource; /** @@ -67,6 +72,78 @@ } /** + * Creates a DOM Document from a TraX Source. + * + * <p>If the source is a {@link DOMSource} holding a Document + * Node, this one will be returned. Otherwise {@link + * toInputSource} and a namespace aware DocumentBuilder (created + * by the default DocumentBuilderFactory) will be used to read the + * source. This may involve an XSLT identity transform in + * toInputSource.</p> + */ + public static Document toDocument(Source s) { + Document d = tryExtractDocFromDOMSource(s); + return d != null ? d + : toDocument(s, DocumentBuilderFactory.newInstance()); + } + + /** + * Creates a DOM Document from a TraX Source. + * + * <p>If the source is a {@link DOMSource} holding a Document + * Node, this one will be returned. Otherwise {@link + * toInputSource} and a namespace aware DocumentBuilder (created + * by given DocumentBuilderFactory) will be used to read the + * source. This may involve an XSLT identity transform in + * toInputSource.</p> + */ + public static Document toDocument(Source s, + DocumentBuilderFactory factory) { + Document d = tryExtractDocFromDOMSource(s); + if (d == null) { + InputSource is = toInputSource(s); + DocumentBuilder b = null; + + // yes, there is a race condition but it is so unlikely to + // happen that I currently don't care enough + boolean oldNsAware = factory.isNamespaceAware(); + try { + if (!oldNsAware) { + factory.setNamespaceAware(true); + } + b = factory.newDocumentBuilder(); + } catch (javax.xml.parsers.ParserConfigurationException e) { + throw new ConfigurationException(e); + } finally { + if (!oldNsAware) { + factory.setNamespaceAware(false); + } + } + + try { + d = b.parse(is); + } catch (org.xml.sax.SAXException e) { + throw new XMLUnitException(e); + } catch (java.io.IOException e) { + throw new XMLUnitException(e); + } + } + return d; + } + + private static Document tryExtractDocFromDOMSource(Source s) { + if (s instanceof DOMSource) { + @SuppressWarnings("unchecked") DOMSource ds = (DOMSource) s; + Node n = ds.getNode(); + if (n instanceof Document) { + @SuppressWarnings("unchecked") Document d = (Document) n; + return d; + } + } + return null; + } + + /** * Creates a JAXP NamespaceContext from a Map prefix => Namespace URI. */ public static NamespaceContext Modified: trunk/xmlunit/src/main/net-core/input/DOMSource.cs =================================================================== --- trunk/xmlunit/src/main/net-core/input/DOMSource.cs 2010-05-19 10:26:31 UTC (rev 394) +++ trunk/xmlunit/src/main/net-core/input/DOMSource.cs 2010-05-19 16:18:11 UTC (rev 395) @@ -18,8 +18,19 @@ /// ISource implementation encapsulating a DOM Node. /// </summary> public class DOMSource : AbstractSource { + private readonly XmlNode node; public DOMSource(XmlNode node) : base(new XmlNodeReader(node)) { + this.node = node; } + + /// <summary> + /// The node this source is wrapping + /// </summary> + public XmlNode Node { + get { + return node; + } + } } } Modified: trunk/xmlunit/src/main/net-core/util/Convert.cs =================================================================== --- trunk/xmlunit/src/main/net-core/util/Convert.cs 2010-05-19 10:26:31 UTC (rev 394) +++ trunk/xmlunit/src/main/net-core/util/Convert.cs 2010-05-19 16:18:11 UTC (rev 395) @@ -14,6 +14,7 @@ using System.Collections.Generic; using System.Xml; +using net.sf.xmlunit.input; namespace net.sf.xmlunit.util { /// <summary> @@ -23,6 +24,22 @@ private Convert() { } /// <summary> + /// Creates a DOM Document from an ISource. + /// </summary> + public static XmlDocument ToDocument(ISource s) { + DOMSource ds = s as DOMSource; + if (ds != null) { + XmlDocument doc = ds.Node as XmlDocument; + if (doc != null) { + return doc; + } + } + XmlDocument d = new XmlDocument(); + d.Load(s.Reader); + return d; + } + + /// <summary> /// Creates a namespace resolver from a Map prefix => /// Namespace URI. /// </summary> Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/ConvertTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/ConvertTest.java 2010-05-19 10:26:31 UTC (rev 394) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/ConvertTest.java 2010-05-19 16:18:11 UTC (rev 395) @@ -27,33 +27,60 @@ import org.w3c.dom.Document; import org.xml.sax.InputSource; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.hamcrest.core.Is.is; public class ConvertTest { - private static void convertAndAssert(Source s) throws Exception { + private static void convertToInputSourceAndAssert(Source s) + throws Exception { DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document d = b.parse(Convert.toInputSource(s)); + documentAsserts(d); + } + + private static void documentAsserts(Document d) { assertThat(d, IsNull.notNullValue()); assertThat(d.getDocumentElement().getTagName(), is("animal")); } @Test public void streamSourceToInputSource() throws Exception { - convertAndAssert(new StreamSource(new File(TestResources.ANIMAL_FILE))); + convertToInputSourceAndAssert(new StreamSource(new File(TestResources.ANIMAL_FILE))); } @Test public void domSourceToInputSource() throws Exception { DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document d = b.parse(new File(TestResources.ANIMAL_FILE)); - convertAndAssert(new DOMSource(d)); + convertToInputSourceAndAssert(new DOMSource(d)); } @Test public void saxSourceToInputSource() throws Exception { InputSource s = new InputSource(new FileInputStream(TestResources.ANIMAL_FILE)); - convertAndAssert(new SAXSource(s)); + convertToInputSourceAndAssert(new SAXSource(s)); } + private static void convertToDocumentAndAssert(Source s) { + documentAsserts(Convert.toDocument(s)); + } + + @Test public void streamSourceToDocument() throws Exception { + convertToDocumentAndAssert(new StreamSource(new File(TestResources.ANIMAL_FILE))); + } + + @Test public void domSourceToDocument() throws Exception { + DocumentBuilder b = + DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document d = b.parse(new File(TestResources.ANIMAL_FILE)); + convertToDocumentAndAssert(new DOMSource(d)); + assertSame(d, Convert.toDocument(new DOMSource(d))); + } + + @Test public void saxSourceToDocument() throws Exception { + InputSource s = new InputSource(new FileInputStream(TestResources.ANIMAL_FILE)); + convertToDocumentAndAssert(new SAXSource(s)); + } + } Added: trunk/xmlunit/src/tests/net-core/util/ConvertTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/util/ConvertTest.cs (rev 0) +++ trunk/xmlunit/src/tests/net-core/util/ConvertTest.cs 2010-05-19 16:18:11 UTC (rev 395) @@ -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. +*/ + +using System.Xml; +using NUnit.Framework; +using net.sf.xmlunit.input; + +namespace net.sf.xmlunit.util { + [TestFixture] + public class ConvertTest { + private static void ConvertToDocumentAndAssert(ISource s) { + XmlDocument d = Convert.ToDocument(s); + Assert.IsNotNull(d); + Assert.AreEqual("animal", d.DocumentElement.Name); + } + + [Test] + public void StreamSourceToDocument() { + ConvertToDocumentAndAssert(new StreamSource(TestResources.ANIMAL_FILE)); + } + + [Test] + public void DomSourceToDocument() { + XmlDocument d = new XmlDocument(); + d.Load(TestResources.ANIMAL_FILE); + ConvertToDocumentAndAssert(new DOMSource(d)); + Assert.AreSame(d, Convert.ToDocument(new DOMSource(d))); + } + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/tests/net-core/util/ConvertTest.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-05-19 10:26:38
|
Revision: 394 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=394&view=rev Author: bodewig Date: 2010-05-19 10:26:31 +0000 (Wed, 19 May 2010) Log Message: ----------- Add a fluent API for XSLT Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java trunk/xmlunit/src/main/net-core/builder/AbstractTransformationBuilder.cs trunk/xmlunit/src/main/net-core/builder/ITransformationBuilderBase.cs trunk/xmlunit/src/main/net-core/builder/Input.cs trunk/xmlunit/src/main/net-core/builder/Transform.cs Added Paths: ----------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/AbstractTransformationBuilder.java trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/ITransformationBuilderBase.java trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Transform.java trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/builder/TransformTest.java trunk/xmlunit/src/tests/net-core/builder/TransformTest.cs Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/AbstractTransformationBuilder.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/AbstractTransformationBuilder.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/AbstractTransformationBuilder.java 2010-05-19 10:26:31 UTC (rev 394) @@ -0,0 +1,66 @@ +/* + 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.builder; + +import javax.xml.transform.Source; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.URIResolver; +import net.sf.xmlunit.transform.Transformation; + +/** + * Base class providing the common logic of the XSLT related builders. + * + * <p>Not intended to be used outside of this package.</p> + * + * <p>I wish there was a way to say <code>implements B</code>.</p> + */ +abstract class + AbstractTransformationBuilder<B extends ITransformationBuilderBase<B>> + implements ITransformationBuilderBase<B> { + + private final Transformation helper; + + protected AbstractTransformationBuilder(Source s) { + helper = new Transformation(s); + } + public B withStylesheet(Source s) { + helper.setStylesheet(s); + return asB(); + } + public B withOutputProperty(String name, String value) { + helper.addOutputProperty(name, value); + return asB(); + } + public B withParameter(String name, Object value) { + helper.addParameter(name, value); + return asB(); + } + public B usingFactory(TransformerFactory f) { + helper.setFactory(f); + return asB(); + } + public B withURIResolver(URIResolver r) { + helper.setURIResolver(r); + return asB(); + } + + protected Transformation getHelper() { + return helper; + } + + @SuppressWarnings("unchecked") + private B asB() { + return (B) this; + } +} Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/AbstractTransformationBuilder.java ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/ITransformationBuilderBase.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/ITransformationBuilderBase.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/ITransformationBuilderBase.java 2010-05-19 10:26:31 UTC (rev 394) @@ -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.builder; + +import javax.xml.transform.Source; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.URIResolver; + +/** + * Holds the common builder methods for XSLT related builders. + * + * <p><code>B</code> is the derived builder interface.</p> + */ +public interface + ITransformationBuilderBase<B extends ITransformationBuilderBase<B>> { + /** + * sets the TraX factory to use. + */ + B usingFactory(TransformerFactory f); + /** + * Adds an output property. + */ + B withOutputProperty(String name, String value); + /** + * Adds a parameter. + */ + B withParameter(String name, Object value); + /** + * Sets the stylesheet to use. + */ + B withStylesheet(Source s); + /** + * Sets the resolver to use for the document() function and + * xsi:import/include. + */ + B withURIResolver(URIResolver r); +} Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/ITransformationBuilderBase.java ___________________________________________________________________ Added: svn:eol-style + native Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java 2010-05-19 08:05:05 UTC (rev 393) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java 2010-05-19 10:26:31 UTC (rev 394) @@ -195,54 +195,26 @@ } } - public static interface TransformationBuilder extends Builder { - TransformationBuilder usingFactory(TransformerFactory f); - TransformationBuilder withOutputProperty(String name, String value); - TransformationBuilder withParameter(String name, Object value); + public static interface TransformationBuilder + extends ITransformationBuilderBase<TransformationBuilder>, Builder { /** * Sets the stylesheet to use. */ TransformationBuilder withStylesheet(Builder b); - TransformationBuilder withStylesheet(Source s); - TransformationBuilder withURIResolver(URIResolver r); } - private static class Transformation implements TransformationBuilder { - private final net.sf.xmlunit.transform.Transformation helper; + private static class Transformation + extends AbstractTransformationBuilder<TransformationBuilder> + implements TransformationBuilder { private Transformation(Source s) { - helper = new net.sf.xmlunit.transform.Transformation(s); + super(s); } - public TransformationBuilder withStylesheet(Source s) { - helper.setStylesheet(s); - return this; - } public TransformationBuilder withStylesheet(Builder b) { return withStylesheet(b.build()); } - public TransformationBuilder withOutputProperty(String name, - String value) { - helper.addOutputProperty(name, value); - return this; - } - - public TransformationBuilder withParameter(String name, Object value) { - helper.addParameter(name, value); - return this; - } - - public TransformationBuilder usingFactory(TransformerFactory f) { - helper.setFactory(f); - return this; - } - - public TransformationBuilder withURIResolver(URIResolver r) { - helper.setURIResolver(r); - return this; - } - public Source build() { - return new DOMSource(helper.transformToDocument()); + return new DOMSource(getHelper().transformToDocument()); } } Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Transform.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Transform.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Transform.java 2010-05-19 10:26:31 UTC (rev 394) @@ -0,0 +1,73 @@ +/* + 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.builder; + +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import net.sf.xmlunit.transform.Transformation; +import org.w3c.dom.Document; + +/** + * Fluent API access to {@link Transformation}. + */ +public final class Transform { + + public interface Builder extends ITransformationBuilderBase<Builder> { + /** + * Create the result of the transformation. + */ + TransformationResult build(); + } + public interface TransformationResult { + /** + * Output the result to a TraX Result. + */ + void to(Result r); + /** + * Output the result to a String. + */ + String toString(); + /** + * Output the result to a DOM Document. + */ + Document toDocument(); + } + + private static class TransformationBuilder + extends AbstractTransformationBuilder<Builder> + implements Builder, TransformationResult { + private TransformationBuilder(Source s) { + super(s); + } + public TransformationResult build() { + return this; + } + @Override public String toString() { + return getHelper().transformToString(); + } + public Document toDocument() { + return getHelper().transformToDocument(); + } + public void to(Result r) { + getHelper().transformTo(r); + } + } + + /** + * Build a transformation for a source document. + */ + public static Builder source(Source s) { + return new TransformationBuilder(s); + } +} Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Transform.java ___________________________________________________________________ Added: svn:eol-style + native Modified: trunk/xmlunit/src/main/net-core/builder/AbstractTransformationBuilder.cs =================================================================== --- trunk/xmlunit/src/main/net-core/builder/AbstractTransformationBuilder.cs 2010-05-19 08:05:05 UTC (rev 393) +++ trunk/xmlunit/src/main/net-core/builder/AbstractTransformationBuilder.cs 2010-05-19 10:26:31 UTC (rev 394) @@ -17,50 +17,58 @@ namespace net.sf.xmlunit.builder { - internal abstract class AbstractTransformationBuilder<T> - : ITransformationBuilderBase<T> - where T : class, ITransformationBuilderBase<T> { + /// <summary> + /// Base class providing the common logic of the XSLT related builders. + /// </summary> + /// <remarks> + /// Not intended to be used outside of this package. + /// I wish there was a way to say <code>: B</code>. + /// </remarks> + internal abstract class AbstractTransformationBuilder<B> + : ITransformationBuilderBase<B> + where B : class, ITransformationBuilderBase<B> { + private readonly Transformation t; protected AbstractTransformationBuilder(ISource s) { t = new Transformation(s); } - public T WithStylesheet(ISource s) { + public B WithStylesheet(ISource s) { t.Stylesheet = s; - return this as T; + return AsB; } - public T WithExtensionObject(string namespaceUri, object extension) { + public B WithExtensionObject(string namespaceUri, object extension) { t.AddExtensionObject(namespaceUri, extension); - return this as T; + return AsB; } - public T WithParameter(string name, string namespaceUri, + public B WithParameter(string name, string namespaceUri, object parameter) { t.AddParameter(name, namespaceUri, parameter); - return this as T; + return AsB; } - public T WithXmlResolver(XmlResolver r) { + public B WithXmlResolver(XmlResolver r) { t.XmlResolver = r; - return this as T; + return AsB; } - public T WithScripting() { + public B WithScripting() { return WithScripting(true); } - public T WithoutScripting() { + public B WithoutScripting() { return WithScripting(false); } - private T WithScripting(bool b) { + private B WithScripting(bool b) { t.EnableScriptBlocks = b; - return this as T; + return AsB; } - public T WithDocumentFunction() { + public B WithDocumentFunction() { return WithDocumentFunction(true); } - public T WithoutDocumentFunction() { + public B WithoutDocumentFunction() { return WithDocumentFunction(false); } - private T WithDocumentFunction(bool b) { + private B WithDocumentFunction(bool b) { t.EnableDocumentFunction = b; - return this as T; + return AsB; } protected Transformation Helper { @@ -68,5 +76,11 @@ return t; } } + + private B AsB { + get { + return this as B; + } + } } } \ No newline at end of file Modified: trunk/xmlunit/src/main/net-core/builder/ITransformationBuilderBase.cs =================================================================== --- trunk/xmlunit/src/main/net-core/builder/ITransformationBuilderBase.cs 2010-05-19 08:05:05 UTC (rev 393) +++ trunk/xmlunit/src/main/net-core/builder/ITransformationBuilderBase.cs 2010-05-19 10:26:31 UTC (rev 394) @@ -16,15 +16,46 @@ namespace net.sf.xmlunit.builder { - public interface ITransformationBuilderBase<T> - where T : ITransformationBuilderBase<T> { - T WithDocumentFunction(); - T WithExtensionObject(string namespaceUri, object extension); - T WithParameter(string name, string namespaceUri, object parameter); - T WithScripting(); - T WithStylesheet(ISource s); - T WithXmlResolver(XmlResolver r); - T WithoutDocumentFunction(); - T WithoutScripting(); + /// <summary> + /// Holds the common builder methods for XSLT related builders. + /// </summary> + /// <remarks> + /// B is the derived builder interface. + /// </remarks> + public interface ITransformationBuilderBase<B> + where B : ITransformationBuilderBase<B> { + /// <summary> + /// Enables the document() function + /// </summary> + B WithDocumentFunction(); + /// <summary> + /// Adds an extension object. + /// </summary> + B WithExtensionObject(string namespaceUri, object extension); + /// <summary> + /// Adds a parameter. + /// </summary> + B WithParameter(string name, string namespaceUri, object parameter); + /// <summary> + /// Enables Script Blocks. + /// </summary> + B WithScripting(); + /// <summary> + /// Sets the stylesheet to use. + /// </summary> + B WithStylesheet(ISource s); + /// <summary> + /// Sets the resolver to use for the document() function and + /// xsi:import/include. + /// </summary> + B WithXmlResolver(XmlResolver r); + /// <summary> + /// Disables the document() function + /// </summary> + B WithoutDocumentFunction(); + /// <summary> + /// Disables Script Blocks. + /// </summary> + B WithoutScripting(); } } \ No newline at end of file Modified: trunk/xmlunit/src/main/net-core/builder/Input.cs =================================================================== --- trunk/xmlunit/src/main/net-core/builder/Input.cs 2010-05-19 08:05:05 UTC (rev 393) +++ trunk/xmlunit/src/main/net-core/builder/Input.cs 2010-05-19 10:26:31 UTC (rev 394) @@ -137,86 +137,25 @@ return new StreamBuilder(uri.AbsoluteUri); } - public interface ITransformationBuilder : IBuilder { - ITransformationBuilder WithDocumentFunction(); - ITransformationBuilder WithExtensionObject(string namespaceUri, - object extension); - ITransformationBuilder WithParameter(string name, - string namespaceUri, - object parameter); - ITransformationBuilder WithScripting(); - ITransformationBuilder WithStylesheet(ISource s); + public interface ITransformationBuilder + : ITransformationBuilderBase<ITransformationBuilder>, IBuilder { /// <summary> /// Sets the stylesheet to use. /// </summary> ITransformationBuilder WithStylesheet(IBuilder b); - ITransformationBuilder WithXmlResolver(XmlResolver r); - ITransformationBuilder WithoutDocumentFunction(); - ITransformationBuilder WithoutScripting(); } - internal class Transformation : ITransformationBuilder { - private readonly net.sf.xmlunit.transform.Transformation t; - internal Transformation(ISource s) { - t = new net.sf.xmlunit.transform.Transformation(s); + internal class Transformation + : AbstractTransformationBuilder<ITransformationBuilder>, + ITransformationBuilder { + + internal Transformation(ISource s) : base(s) { } - public ITransformationBuilder WithStylesheet(ISource s) { - t.Stylesheet = s; - return this; - } public ITransformationBuilder WithStylesheet(IBuilder b) { return WithStylesheet(b.Build()); } - - public ITransformationBuilder WithExtensionObject(string namespaceUri, - object extension) { - t.AddExtensionObject(namespaceUri, extension); - return this; - } - - public ITransformationBuilder WithParameter(string name, - string namespaceUri, - object parameter) { - t.AddParameter(name, namespaceUri, parameter); - return this; - } - - public ITransformationBuilder WithXmlResolver(XmlResolver r) { - t.XmlResolver = r; - return this; - } - - public ITransformationBuilder WithScripting() { - return WithScripting(true); - } - - public ITransformationBuilder WithoutScripting() { - return WithScripting(false); - } - - private ITransformationBuilder WithScripting(bool b) { - t.EnableScriptBlocks = b; - return this; - } - - public ITransformationBuilder WithDocumentFunction() { - return WithDocumentFunction(true); - } - - public ITransformationBuilder WithoutDocumentFunction() { - return WithDocumentFunction(false); - } - - private ITransformationBuilder WithDocumentFunction(bool b) { - t.EnableDocumentFunction = b; - return this; - } - public ISource Build() { - using (MemoryStream ms = new MemoryStream()) { - t.TransformTo(ms); - return FromMemory(ms.ToArray()).Build(); - } + return new DOMSource(Helper.TransformToDocument()); } } Modified: trunk/xmlunit/src/main/net-core/builder/Transform.cs =================================================================== --- trunk/xmlunit/src/main/net-core/builder/Transform.cs 2010-05-19 08:05:05 UTC (rev 393) +++ trunk/xmlunit/src/main/net-core/builder/Transform.cs 2010-05-19 10:26:31 UTC (rev 394) @@ -17,20 +17,40 @@ namespace net.sf.xmlunit.builder { + /// <summary> + /// Fluent API access to net.sf.xmlunit.transform.Transformation. + /// </summary> public sealed class Transform { public interface IBuilder : ITransformationBuilderBase<IBuilder> { + /// <summary> + /// Create the result of the transformation. + /// </summary> ITransformationResult Build(); } public interface ITransformationResult { + /// <summary> + /// Output the result to a stream. + /// </summary> void To(Stream s); + /// <summary> + /// Output the result to a writer. + /// </summary> void To(TextWriter t); + /// <summary> + /// Output the result to a writer. + /// </summary> void To(XmlWriter x); + /// <summary> + /// Output the result to a string. + /// </summary> string ToString(); + /// <summary> + /// Output the result to a DOM Document. + /// </summary> XmlDocument ToDocument(); } - internal class TransformationBuilder : AbstractTransformationBuilder<IBuilder>, IBuilder, ITransformationResult { @@ -57,6 +77,9 @@ } } + /// <summary> + /// Build a transformation for a source document. + /// </summary> public static IBuilder Source(ISource s) { return new TransformationBuilder(s); } Added: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/builder/TransformTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/builder/TransformTest.java (rev 0) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/builder/TransformTest.java 2010-05-19 10:26:31 UTC (rev 394) @@ -0,0 +1,60 @@ +/* + 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.builder; + +import javax.xml.transform.OutputKeys; +import net.sf.xmlunit.TestResources; +import net.sf.xmlunit.builder.Input; +import org.junit.Test; +import org.w3c.dom.Document; + +import static org.hamcrest.core.IsNot.*; +import static org.junit.Assert.*; + +public class TransformTest { + + @Test public void transformAnimalToString() { + assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><dog/>", + Transform + .source(Input.fromFile(TestResources.DOG_FILE) + .build()) + .withStylesheet(Input.fromFile(TestResources.ANIMAL_XSL) + .build()) + .build() + .toString()); + } + + @Test public void transformAnimalToDocument() { + Document doc = Transform + .source(Input.fromFile(TestResources.DOG_FILE).build()) + .withStylesheet(Input.fromFile(TestResources.ANIMAL_XSL) + .build()) + .build() + .toDocument(); + assertEquals("dog", doc.getDocumentElement().getTagName()); + } + + @Test public void transformAnimalToHtml() { + assertThat(Transform + .source(Input.fromFile(TestResources.DOG_FILE).build()) + .withStylesheet(Input.fromFile(TestResources.ANIMAL_XSL) + .build()) + .withOutputProperty(OutputKeys.METHOD, "html") + .build() + .toString(), + not("<?xml version=\"1.0\" encoding=\"UTF-8\"?><dog/>")); + } + +} + Property changes on: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/builder/TransformTest.java ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/tests/net-core/builder/TransformTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/builder/TransformTest.cs (rev 0) +++ trunk/xmlunit/src/tests/net-core/builder/TransformTest.cs 2010-05-19 10:26:31 UTC (rev 394) @@ -0,0 +1,43 @@ +/* + 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.Xml; +using NUnit.Framework; + +namespace net.sf.xmlunit.builder { + [TestFixture] + public class TransformTest { + [Test] public void TransformAnimalToString() { + Assert.AreEqual("<?xml version=\"1.0\" encoding=\"utf-16\"?><dog />", + Transform + .Source(Input.FromFile(TestResources.DOG_FILE) + .Build()) + .WithStylesheet(Input.FromFile(TestResources.ANIMAL_XSL) + .Build()) + .Build() + .ToString()); + } + + [Test] public void TransformAnimalToDocument() { + XmlDocument doc = Transform + .Source(Input.FromFile(TestResources.DOG_FILE).Build()) + .WithStylesheet(Input.FromFile(TestResources.ANIMAL_XSL) + .Build()) + .Build() + .ToDocument(); + Assert.AreEqual("dog", doc.DocumentElement.Name); + } + } +} + Property changes on: trunk/xmlunit/src/tests/net-core/builder/TransformTest.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-05-19 08:05:11
|
Revision: 393 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=393&view=rev Author: bodewig Date: 2010-05-19 08:05:05 +0000 (Wed, 19 May 2010) Log Message: ----------- documentation Modified Paths: -------------- trunk/xmlunit/src/main/net-core/input/AbstractSource.cs trunk/xmlunit/src/main/net-core/input/DOMSource.cs trunk/xmlunit/src/main/net-core/input/ReaderSource.cs trunk/xmlunit/src/main/net-core/input/StreamSource.cs Modified: trunk/xmlunit/src/main/net-core/input/AbstractSource.cs =================================================================== --- trunk/xmlunit/src/main/net-core/input/AbstractSource.cs 2010-05-19 08:04:25 UTC (rev 392) +++ trunk/xmlunit/src/main/net-core/input/AbstractSource.cs 2010-05-19 08:05:05 UTC (rev 393) @@ -14,6 +14,10 @@ using System.Xml; namespace net.sf.xmlunit.input { + /// <summary> + /// Provides a base implementation for the different concrete ISource + /// implementations. + /// </summary> public abstract class AbstractSource : ISource { private string systemId; private readonly XmlReader reader; Modified: trunk/xmlunit/src/main/net-core/input/DOMSource.cs =================================================================== --- trunk/xmlunit/src/main/net-core/input/DOMSource.cs 2010-05-19 08:04:25 UTC (rev 392) +++ trunk/xmlunit/src/main/net-core/input/DOMSource.cs 2010-05-19 08:05:05 UTC (rev 393) @@ -14,6 +14,9 @@ using System.Xml; namespace net.sf.xmlunit.input { + /// <summary> + /// ISource implementation encapsulating a DOM Node. + /// </summary> public class DOMSource : AbstractSource { public DOMSource(XmlNode node) : base(new XmlNodeReader(node)) { Modified: trunk/xmlunit/src/main/net-core/input/ReaderSource.cs =================================================================== --- trunk/xmlunit/src/main/net-core/input/ReaderSource.cs 2010-05-19 08:04:25 UTC (rev 392) +++ trunk/xmlunit/src/main/net-core/input/ReaderSource.cs 2010-05-19 08:05:05 UTC (rev 393) @@ -14,6 +14,9 @@ using System.Xml; namespace net.sf.xmlunit.input { + /// <summary> + /// ISource implementation encapsulating a plain XmlReader. + /// </summary> public class ReaderSource : AbstractSource { public ReaderSource(XmlReader rdr) : base(rdr) { Modified: trunk/xmlunit/src/main/net-core/input/StreamSource.cs =================================================================== --- trunk/xmlunit/src/main/net-core/input/StreamSource.cs 2010-05-19 08:04:25 UTC (rev 392) +++ trunk/xmlunit/src/main/net-core/input/StreamSource.cs 2010-05-19 08:05:05 UTC (rev 393) @@ -15,6 +15,10 @@ using System.Xml; namespace net.sf.xmlunit.input { + /// <summary> + /// ISource implementation encapsulating data read from a stream + /// or a reader. + /// </summary> public class StreamSource : AbstractSource { public StreamSource(TextReader rdr) : base(XmlReader.Create(rdr)) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-05-19 08:04:32
|
Revision: 392 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=392&view=rev Author: bodewig Date: 2010-05-19 08:04:25 +0000 (Wed, 19 May 2010) Log Message: ----------- documentation Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java trunk/xmlunit/src/main/net-core/ISource.cs trunk/xmlunit/src/main/net-core/builder/Input.cs Added Paths: ----------- trunk/xmlunit/src/main/net-core/builder/AbstractTransformationBuilder.cs trunk/xmlunit/src/main/net-core/builder/ITransformationBuilderBase.cs trunk/xmlunit/src/main/net-core/builder/Transform.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java 2010-05-19 06:57:47 UTC (rev 391) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java 2010-05-19 08:04:25 UTC (rev 392) @@ -32,9 +32,15 @@ import org.w3c.dom.Document; import org.w3c.dom.Node; +/** + * Fluent API to create Source instances. + */ public class Input { public static interface Builder { + /** + * build the actual Source instance. + */ Source build(); } @@ -49,10 +55,16 @@ } } + /** + * Build a Source from a DOM Document. + */ public static Builder fromDocument(Document d) { return new DOMBuilder(d); } + /** + * Build a Source from a DOM Node. + */ public static Builder fromNode(Node n) { return new DOMBuilder(n); } @@ -79,30 +91,51 @@ } } + /** + * Build a Source from a file. + */ public static Builder fromFile(File f) { return new StreamBuilder(f); } + /** + * Build a Source from a named file. + */ public static Builder fromFile(String name) { return new StreamBuilder(new File(name)); } + /** + * Build a Source from a stream. + */ public static Builder fromStream(InputStream s) { return new StreamBuilder(s); } + /** + * Build a Source from a reader. + */ public static Builder fromReader(Reader r) { return new StreamBuilder(r); } + /** + * Build a Source from a string. + */ public static Builder fromMemory(String s) { return fromReader(new StringReader(s)); } + /** + * Build a Source from an array of bytes. + */ public static Builder fromMemory(byte[] b) { return fromStream(new ByteArrayInputStream(b)); } + /** + * Build a Source from an URL. + */ public static Builder fromURL(URL url) { try { InputStream in = null; @@ -136,6 +169,10 @@ } } + /** + * Build a Source from an URI. + * @param uri must represent a valid URL + */ public static Builder fromURI(URI uri) { try { return fromURL(uri.toURL()); @@ -145,6 +182,10 @@ } } + /** + * Build a Source from an URI. + * @param uri must represent a valid URL + */ public static Builder fromURI(String uri) { try { return fromURI(new URI(uri)); @@ -158,6 +199,9 @@ TransformationBuilder usingFactory(TransformerFactory f); TransformationBuilder withOutputProperty(String name, String value); TransformationBuilder withParameter(String name, Object value); + /** + * Sets the stylesheet to use. + */ TransformationBuilder withStylesheet(Builder b); TransformationBuilder withStylesheet(Source s); TransformationBuilder withURIResolver(URIResolver r); @@ -202,10 +246,16 @@ } } + /** + * Build a Source by XSLT transforming a different Source. + */ public static TransformationBuilder byTransforming(Source s) { return new Transformation(s); } + /** + * Build a Source by XSLT transforming a different Source. + */ public static TransformationBuilder byTransforming(Builder b) { return byTransforming(b.build()); } Modified: trunk/xmlunit/src/main/net-core/ISource.cs =================================================================== --- trunk/xmlunit/src/main/net-core/ISource.cs 2010-05-19 06:57:47 UTC (rev 391) +++ trunk/xmlunit/src/main/net-core/ISource.cs 2010-05-19 08:04:25 UTC (rev 392) @@ -14,8 +14,18 @@ using System.Xml; namespace net.sf.xmlunit { + /// <summary> + /// Representation of the various ways to provide pieces of XML to + /// XMLUnit. + /// </summary> public interface ISource { + /// <summary> + /// Provides the content. + /// </summary> XmlReader Reader {get;} + /// <summary> + /// Some sort of Base-URI of this ISource. + /// </summary> string SystemId {get; set;} } } Added: trunk/xmlunit/src/main/net-core/builder/AbstractTransformationBuilder.cs =================================================================== --- trunk/xmlunit/src/main/net-core/builder/AbstractTransformationBuilder.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/builder/AbstractTransformationBuilder.cs 2010-05-19 08:04:25 UTC (rev 392) @@ -0,0 +1,72 @@ +/* + 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.Xml; +using net.sf.xmlunit.transform; + +namespace net.sf.xmlunit.builder { + + internal abstract class AbstractTransformationBuilder<T> + : ITransformationBuilderBase<T> + where T : class, ITransformationBuilderBase<T> { + private readonly Transformation t; + + protected AbstractTransformationBuilder(ISource s) { + t = new Transformation(s); + } + public T WithStylesheet(ISource s) { + t.Stylesheet = s; + return this as T; + } + public T WithExtensionObject(string namespaceUri, object extension) { + t.AddExtensionObject(namespaceUri, extension); + return this as T; + } + public T WithParameter(string name, string namespaceUri, + object parameter) { + t.AddParameter(name, namespaceUri, parameter); + return this as T; + } + public T WithXmlResolver(XmlResolver r) { + t.XmlResolver = r; + return this as T; + } + public T WithScripting() { + return WithScripting(true); + } + public T WithoutScripting() { + return WithScripting(false); + } + private T WithScripting(bool b) { + t.EnableScriptBlocks = b; + return this as T; + } + public T WithDocumentFunction() { + return WithDocumentFunction(true); + } + public T WithoutDocumentFunction() { + return WithDocumentFunction(false); + } + private T WithDocumentFunction(bool b) { + t.EnableDocumentFunction = b; + return this as T; + } + + protected Transformation Helper { + get { + return t; + } + } + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/main/net-core/builder/AbstractTransformationBuilder.cs ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/net-core/builder/ITransformationBuilderBase.cs =================================================================== --- trunk/xmlunit/src/main/net-core/builder/ITransformationBuilderBase.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/builder/ITransformationBuilderBase.cs 2010-05-19 08:04:25 UTC (rev 392) @@ -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. +*/ + +using System.Xml; + +namespace net.sf.xmlunit.builder { + + public interface ITransformationBuilderBase<T> + where T : ITransformationBuilderBase<T> { + T WithDocumentFunction(); + T WithExtensionObject(string namespaceUri, object extension); + T WithParameter(string name, string namespaceUri, object parameter); + T WithScripting(); + T WithStylesheet(ISource s); + T WithXmlResolver(XmlResolver r); + T WithoutDocumentFunction(); + T WithoutScripting(); + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/main/net-core/builder/ITransformationBuilderBase.cs ___________________________________________________________________ Added: svn:eol-style + native Modified: trunk/xmlunit/src/main/net-core/builder/Input.cs =================================================================== --- trunk/xmlunit/src/main/net-core/builder/Input.cs 2010-05-19 06:57:47 UTC (rev 391) +++ trunk/xmlunit/src/main/net-core/builder/Input.cs 2010-05-19 08:04:25 UTC (rev 392) @@ -18,8 +18,14 @@ using net.sf.xmlunit.input; namespace net.sf.xmlunit.builder { - public static class Input { + /// <summary> + /// Fluent API to create ISource instances. + /// </summary> + public sealed class Input { public interface IBuilder { + /// <summary> + /// build the actual ISource instance. + /// </summary> ISource Build(); } @@ -33,10 +39,16 @@ } } + /// <summary> + /// Build an ISource from a DOM Document. + /// </summary> public static IBuilder FromDocument(XmlDocument d) { return new DOMBuilder(d); } + /// <summary> + /// Build an ISource from a DOM Node. + /// </summary> public static IBuilder FromNode(XmlNode n) { return new DOMBuilder(n); } @@ -62,10 +74,16 @@ } } + /// <summary> + /// Build an ISource from a named file. + /// </summary> public static IBuilder FromFile(string name) { return new StreamBuilder(name); } + /// <summary> + /// Build an ISource from a stream. + /// </summary> public static IBuilder FromStream(Stream s) { StreamBuilder b = new StreamBuilder(s); if (s is FileStream) { @@ -75,6 +93,9 @@ return b; } + /// <summary> + /// Build an ISource from a reader. + /// </summary> public static IBuilder FromReader(TextReader r) { StreamBuilder b = new StreamBuilder(r); StreamReader s = r as StreamReader; @@ -86,18 +107,32 @@ return b; } + /// <summary> + /// Build an ISource from a string. + /// </summary> public static IBuilder FromMemory(string s) { return FromReader(new StringReader(s)); } + /// <summary> + /// Build an ISource from an array of bytes. + /// </summary> public static IBuilder FromMemory(byte[] b) { return FromStream(new MemoryStream(b)); } + /// <summary> + /// Build an ISource from an URI. + /// <param name="uri">must represent a valid URL</param> + /// </summary> public static IBuilder FromURI(string uri) { return new StreamBuilder(uri); } + /// <summary> + /// Build an ISource from an URI. + /// <param name="uri">must represent a valid URL</param> + /// </summary> public static IBuilder FromURI(System.Uri uri) { return new StreamBuilder(uri.AbsoluteUri); } @@ -111,6 +146,9 @@ object parameter); ITransformationBuilder WithScripting(); ITransformationBuilder WithStylesheet(ISource s); + /// <summary> + /// Sets the stylesheet to use. + /// </summary> ITransformationBuilder WithStylesheet(IBuilder b); ITransformationBuilder WithXmlResolver(XmlResolver r); ITransformationBuilder WithoutDocumentFunction(); @@ -182,9 +220,15 @@ } } + /// <summary> + /// Build an ISource by XSLT transforming a different ISource. + /// </summary> public static ITransformationBuilder ByTransforming(ISource s) { return new Transformation(s); } + /// <summary> + /// Build an ISource by XSLT transforming a different ISource. + /// </summary> public static ITransformationBuilder ByTransforming(IBuilder b) { return ByTransforming(b.Build()); } Added: trunk/xmlunit/src/main/net-core/builder/Transform.cs =================================================================== --- trunk/xmlunit/src/main/net-core/builder/Transform.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/builder/Transform.cs 2010-05-19 08:04:25 UTC (rev 392) @@ -0,0 +1,64 @@ +/* + 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.IO; +using System.Xml; + +namespace net.sf.xmlunit.builder { + + public sealed class Transform { + + public interface IBuilder : ITransformationBuilderBase<IBuilder> { + ITransformationResult Build(); + } + public interface ITransformationResult { + void To(Stream s); + void To(TextWriter t); + void To(XmlWriter x); + string ToString(); + XmlDocument ToDocument(); + } + + + internal class TransformationBuilder + : AbstractTransformationBuilder<IBuilder>, IBuilder, + ITransformationResult { + + internal TransformationBuilder(ISource s) : base(s) { + } + public ITransformationResult Build() { + return this; + } + public override string ToString() { + return Helper.TransformToString(); + } + public XmlDocument ToDocument() { + return Helper.TransformToDocument(); + } + public void To(Stream s) { + Helper.TransformTo(s); + } + public void To(TextWriter w) { + Helper.TransformTo(w); + } + public void To(XmlWriter w) { + Helper.TransformTo(w); + } + } + + public static IBuilder Source(ISource s) { + return new TransformationBuilder(s); + } + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/main/net-core/builder/Transform.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-05-19 06:57:55
|
Revision: 391 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=391&view=rev Author: bodewig Date: 2010-05-19 06:57:47 +0000 (Wed, 19 May 2010) Log Message: ----------- make legacy code-base use net.sf.xmlunit.transform Modified Paths: -------------- trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/Transform.java trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/exceptions/ConfigurationException.java trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_Transform.java Modified: trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/Transform.java =================================================================== --- trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/Transform.java 2010-05-19 06:56:49 UTC (rev 390) +++ trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/Transform.java 2010-05-19 06:57:47 UTC (rev 391) @@ -36,30 +36,28 @@ package org.custommonkey.xmlunit; -import org.custommonkey.xmlunit.exceptions.ConfigurationException; -import org.custommonkey.xmlunit.exceptions.XMLUnitRuntimeException; - import java.io.File; -import java.io.StringReader; -import java.io.StringWriter; import java.net.MalformedURLException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; import java.util.Properties; - import javax.xml.transform.ErrorListener; import javax.xml.transform.Result; import javax.xml.transform.Source; -import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.URIResolver; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.dom.DOMResult; import javax.xml.transform.sax.SAXSource; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; -import org.xml.sax.InputSource; +import net.sf.xmlunit.builder.Input; +import net.sf.xmlunit.exceptions.XMLUnitException; +import net.sf.xmlunit.exceptions.XMLUnitException; +import net.sf.xmlunit.transform.Transformation; +import org.custommonkey.xmlunit.exceptions.XMLUnitRuntimeException; +import org.custommonkey.xmlunit.exceptions.ConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Node; +import org.xml.sax.InputSource; /** * Handy wrapper for an XSLT transformation performed using JAXP/Trax. @@ -70,8 +68,9 @@ public class Transform { private static final File PWD = new File("."); - private final Source inputSource; - private final Transformer transformer; + private final Transformation transformation; + // only here in order to support the getParameter method + private final Map<String, Object> parameters = new HashMap<String, Object>(); /** * Create a transformation using String input XML and String stylesheet @@ -79,8 +78,8 @@ * @param stylesheet */ public Transform(String input, String stylesheet) { - this(new StreamSource(new StringReader(input)), - new StreamSource(new StringReader(stylesheet))); + this(input == null ? null : Input.fromMemory(input), + stylesheet == null ? null : Input.fromMemory(stylesheet)); } /** @@ -89,8 +88,8 @@ * @param stylesheet */ public Transform(String input, File stylesheet) { - this(new StreamSource(new StringReader(input)), - new StreamSource(stylesheet)); + this(input == null ? null : Input.fromMemory(input), + stylesheet == null ? null : Input.fromFile(stylesheet)); } /** @@ -110,7 +109,8 @@ * @param stylesheet */ public Transform(InputSource input, File stylesheet) { - this(new SAXSource(input), new StreamSource(stylesheet)); + this(new SAXSource(input), + stylesheet == null ? null : Input.fromFile(stylesheet).build()); } /** @@ -118,7 +118,7 @@ * @param source */ public Transform(Node sourceNode) { - this(sourceNode, (Source)null); + this(sourceNode, (String) null); } /** @@ -127,7 +127,8 @@ * @param stylesheet */ public Transform(Node sourceNode, String stylesheet) { - this(sourceNode, new StreamSource(new StringReader(stylesheet))); + this(sourceNode == null ? null : Input.fromNode(sourceNode), + stylesheet == null ? null : Input.fromMemory(stylesheet)); } /** @@ -136,16 +137,13 @@ * @param stylesheet */ public Transform(Node sourceNode, File stylesheet) { - this(sourceNode, new StreamSource(stylesheet)); + this(sourceNode == null ? null : Input.fromNode(sourceNode), + stylesheet == null ? null : Input.fromFile(stylesheet)); } - /** - * Create a transformation from an input Node and stylesheet in a Source - * @param sourceNode - * @param stylesheetSource - */ - private Transform(Node sourceNode, Source stylesheetSource) { - this(new DOMSource(sourceNode), stylesheetSource); + private Transform(Input.Builder input, Input.Builder stylesheet) { + this(input == null ? null : input.build(), + stylesheet == null ? null : stylesheet.build()); } /** @@ -154,11 +152,12 @@ * @param stylesheetReader */ public Transform(Source inputSource, Source stylesheetSource) { - this.inputSource = inputSource; + transformation = new Transformation(inputSource); + transformation.setStylesheet(stylesheetSource); + transformation.setFactory(XMLUnit.getTransformerFactory()); + provideSystemIdIfRequired(inputSource); - provideSystemIdIfRequired(stylesheetSource); - this.transformer = getTransformer(stylesheetSource); } /** @@ -184,31 +183,17 @@ } } /** - * Factory method - * @param stylesheetSource - * @throws ConfigurationException - * @return - */ - private Transformer getTransformer(Source stylesheetSource) - throws ConfigurationException { - try { - TransformerFactory factory = XMLUnit.getTransformerFactory(); - Transformer t = stylesheetSource == null - ? factory.newTransformer() - : factory.newTransformer(stylesheetSource); - return t; - } catch (javax.xml.transform.TransformerConfigurationException ex) { - throw new ConfigurationException(ex); - } - } - - /** * Perform the actual transformation * @param result * @throws TransformerException */ - protected void transformTo(Result result) throws TransformerException { - transformer.transform(inputSource, result); + protected void transformTo(final Result result) throws TransformerException { + withExceptionHandling(new Trans<Object>() { + public Object transform() { + transformation.transformTo(result); + return null; + } + }); } /** @@ -217,10 +202,11 @@ * @throws TransformerException */ public String getResultString() throws TransformerException { - StringWriter outputWriter = new StringWriter(); - transformTo(new StreamResult(outputWriter)); - - return outputWriter.toString(); + return withExceptionHandling(new Trans<String>() { + public String transform() { + return transformation.transformToString(); + } + }); } /** @@ -229,10 +215,11 @@ * @throws TransformerException */ public Document getResultDocument() throws TransformerException { - DOMResult result = new DOMResult(); - transformTo(result); - - return (Document) result.getNode(); + return withExceptionHandling(new Trans<Document>() { + public Document transform() { + return transformation.transformToDocument(); + } + }); } /** @@ -241,9 +228,7 @@ * @param value */ public void setOutputProperty(String name, String value) { - Properties properties = new Properties(); - properties.setProperty(name, value); - setOutputProperties(properties); + transformation.addOutputProperty(name, value); } /** @@ -252,9 +237,19 @@ * @see Transformer#setOutputProperties(java.util.Properties) */ public void setOutputProperties(Properties outputProperties) { - transformer.setOutputProperties(outputProperties); + for (Enumeration e = outputProperties.propertyNames(); + e.hasMoreElements(); ) { + Object key = e.nextElement(); + if (key != null) { + String name = key.toString(); + String value = outputProperties.getProperty(name); + if (value != null) { + setOutputProperty(name, value); + } + } + } } - + /** * Add a parameter for the transformation * @param name @@ -262,9 +257,10 @@ * @see Transformer#setParameter(java.lang.String, java.lang.Object) */ public void setParameter(String name, Object value) { - transformer.setParameter(name, value); + parameters.put(name, value); + transformation.addParameter(name, value); } - + /** * See a parameter used for the transformation * @param name @@ -272,30 +268,50 @@ * @see Transformer#getParameter(java.lang.String) */ public Object getParameter(String name) { - return transformer.getParameter(name); + return parameters.get(name); } - + /** * Clear parameters used for the transformation * @see Transformer#clearParameters() */ public void clearParameters() { - transformer.clearParameters(); + parameters.clear(); + transformation.clearParameters(); } - + /** * Set the URIResolver for the transformation * @see Transformer#setURIResolver(javax.xml.transform.URIResolver) */ public void setURIResolver(URIResolver uriResolver) { - transformer.setURIResolver(uriResolver); + transformation.setURIResolver(uriResolver); } - + /** * Set the ErrorListener for the transformation * @see Transformer#setErrorListener(javax.xml.transform.ErrorListener) */ public void setErrorListener(ErrorListener errorListener) { - transformer.setErrorListener(errorListener); + transformation.setErrorListener(errorListener); } + + private static <R> R withExceptionHandling(Trans<R> trans) + throws TransformerException { + try { + return trans.transform(); + } catch (net.sf.xmlunit.exceptions.ConfigurationException ex) { + throw new ConfigurationException(ex.getMessage(), ex.getCause()); + } catch (XMLUnitException ex) { + Throwable cause = ex.getCause(); + if (cause instanceof TransformerException) { + throw (TransformerException) cause; + } + throw new XMLUnitRuntimeException(ex.getMessage(), cause); + } + } + + private interface Trans<R> { + R transform(); + } } Modified: trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/exceptions/ConfigurationException.java =================================================================== --- trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/exceptions/ConfigurationException.java 2010-05-19 06:56:49 UTC (rev 390) +++ trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/exceptions/ConfigurationException.java 2010-05-19 06:57:47 UTC (rev 391) @@ -47,4 +47,7 @@ public ConfigurationException(String s) { super(s, null); } + public ConfigurationException(String s, Throwable t) { + super(s, t); + } } Modified: trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_Transform.java =================================================================== --- trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_Transform.java 2010-05-19 06:56:49 UTC (rev 390) +++ trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_Transform.java 2010-05-19 06:57:47 UTC (rev 391) @@ -134,6 +134,7 @@ + test_Constants.XSLT_END; try { Transform transform = new Transform(s, xsl); + transform.getResultString(); fail("should fail because of unknown include URI"); } catch (ConfigurationException tce) { // expected exception This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-05-19 06:56:55
|
Revision: 390 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=390&view=rev Author: bodewig Date: 2010-05-19 06:56:49 +0000 (Wed, 19 May 2010) Log Message: ----------- extract XSLT logic into something reusable Modified Paths: -------------- trunk/xmlunit/src/main/net-core/builder/Input.cs trunk/xmlunit/src/tests/net-core/TestResources.cs Added Paths: ----------- trunk/xmlunit/src/main/net-core/transform/ trunk/xmlunit/src/main/net-core/transform/Transformation.cs trunk/xmlunit/src/tests/net-core/transform/ trunk/xmlunit/src/tests/net-core/transform/TransformationTest.cs Modified: trunk/xmlunit/src/main/net-core/builder/Input.cs =================================================================== --- trunk/xmlunit/src/main/net-core/builder/Input.cs 2010-05-19 06:56:18 UTC (rev 389) +++ trunk/xmlunit/src/main/net-core/builder/Input.cs 2010-05-19 06:56:49 UTC (rev 390) @@ -14,7 +14,6 @@ using System; using System.IO; using System.Xml; -using System.Xml.Xsl; using net.sf.xmlunit.exceptions; using net.sf.xmlunit.input; @@ -119,16 +118,12 @@ } internal class Transformation : ITransformationBuilder { - private readonly ISource source; - private ISource styleSheet; - private XmlResolver xmlResolver = new XmlUrlResolver(); - private readonly XsltSettings settings = new XsltSettings(); - private readonly XsltArgumentList args = new XsltArgumentList(); + private readonly net.sf.xmlunit.transform.Transformation t; internal Transformation(ISource s) { - source = s; + t = new net.sf.xmlunit.transform.Transformation(s); } public ITransformationBuilder WithStylesheet(ISource s) { - this.styleSheet = s; + t.Stylesheet = s; return this; } public ITransformationBuilder WithStylesheet(IBuilder b) { @@ -137,19 +132,19 @@ public ITransformationBuilder WithExtensionObject(string namespaceUri, object extension) { - args.AddExtensionObject(namespaceUri, extension); + t.AddExtensionObject(namespaceUri, extension); return this; } public ITransformationBuilder WithParameter(string name, string namespaceUri, object parameter) { - args.AddParam(name, namespaceUri, parameter); + t.AddParameter(name, namespaceUri, parameter); return this; } public ITransformationBuilder WithXmlResolver(XmlResolver r) { - xmlResolver = r; + t.XmlResolver = r; return this; } @@ -162,7 +157,7 @@ } private ITransformationBuilder WithScripting(bool b) { - settings.EnableScript = b; + t.EnableScriptBlocks = b; return this; } @@ -175,25 +170,14 @@ } private ITransformationBuilder WithDocumentFunction(bool b) { - settings.EnableDocumentFunction = b; + t.EnableDocumentFunction = b; return this; } public ISource Build() { - try { - XslCompiledTransform t = new XslCompiledTransform(); - if (styleSheet != null) { - t.Load(styleSheet.Reader, settings, xmlResolver); - } - MemoryStream ms = new MemoryStream(); - using (ms) { - t.Transform(source.Reader, - args, - ms); - } + using (MemoryStream ms = new MemoryStream()) { + t.TransformTo(ms); return FromMemory(ms.ToArray()).Build(); - } catch (System.Exception ex) { - throw new XMLUnitException(ex); } } } Added: trunk/xmlunit/src/main/net-core/transform/Transformation.cs =================================================================== --- trunk/xmlunit/src/main/net-core/transform/Transformation.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/transform/Transformation.cs 2010-05-19 06:56:49 UTC (rev 390) @@ -0,0 +1,225 @@ +/* + 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.IO; +using System.Xml; +using System.Xml.Xsl; +using net.sf.xmlunit.exceptions; + +namespace net.sf.xmlunit.transform { + + /// <summary> + /// Provides a convenience layer over System.Xml.Xsl. + /// </summary> + /// <remarks> + /// Apart from ArgumentExceptions if you try to pass in null + /// values only the Transform methods will ever throw exceptions + /// and these will be XMLUnit's exceptions. + /// + /// Each invocation of a Transform method will use a fresh + /// XslCompiledTransform instance, the Transform methods are + /// thread-safe. + /// </remarks> + public sealed class Transformation { + private ISource source; + private ISource styleSheet; + private XmlResolver xmlResolver = null; + private readonly XsltSettings settings = new XsltSettings(); + private readonly XsltArgumentList args = new XsltArgumentList(); + + public Transformation() { + } + /// <param name="s">the source to transform - must not be null.</param> + public Transformation(ISource s) { + Source = s; + } + /// <summary> + /// Set the source document to transform - must not be null. + /// </summary> + public ISource Source { + set { + if (value == null) { + throw new ArgumentNullException(); + } + source = value; + } + } + /// <summary> + /// Set the stylesheet to use - may be null in which case an + /// identity transformation will be performed. + /// </summary> + /// <param name="s">the stylesheet to use</param> + public ISource Stylesheet { + set { + styleSheet = value; + } + } + /// <summary> + /// Add a named extension object. + /// </summary> + public void AddExtensionObject(string namespaceUri, object extension) { + if (namespaceUri == null) { + throw new ArgumentNullException("namespaceUri"); + } + args.AddExtensionObject(namespaceUri, extension); + } + /// <summary> + /// Clears all extension objects and parameters. + /// </summary> + public void Clear() { + args.Clear(); + } + /// <summary> + /// Add a named parameter. + /// </summary> + public void AddParameter(string name, string nsUri, object parameter) { + if (name == null) { + throw new ArgumentNullException("name"); + } + if (nsUri == null) { + throw new ArgumentNullException("nsUri"); + } + args.AddParam(name, nsUri, parameter); + } + /// <summary> + /// Set the resolver to use for document() and xsl:include/import + /// </summary> + /// <remarks>may be null in which case an empty XmlUrlResolver + /// will be used.</remarks> + public XmlResolver XmlResolver { + set { + xmlResolver = value; + } + } + /// <summary> + /// Whether the document() function will be allowed. + /// </summary> + public bool EnableDocumentFunction { + set { + settings.EnableDocumentFunction = value; + } + } + /// <summary> + /// Whether embedded script blocks will be allowed. + /// </summary> + public bool EnableScriptBlocks { + set { + settings.EnableScript = value; + } + } + + /// <summary> + /// Perform the transformation. + /// </summary> + public void TransformTo(Stream stream) { + if (stream == null) { + throw new ArgumentNullException("stream"); + } + Transform(TransformToStream(stream)); + } + + /// <summary> + /// Perform the transformation. + /// </summary> + public void TransformTo(TextWriter writer) { + if (writer == null) { + throw new ArgumentNullException("writer"); + } + Transform(TransformToTextWriter(writer)); + } + + /// <summary> + /// Perform the transformation. + /// </summary> + public void TransformTo(XmlWriter writer) { + if (writer == null) { + throw new ArgumentNullException("writer"); + } + Transform(TransformToXmlWriter(writer)); + } + + /// <summary> + /// Perform the transformation. + /// </summary> + private void Transform(Transformer transformer) { + if (source == null) { + throw new ArgumentNullException("source"); + } + try { + XslCompiledTransform t = new XslCompiledTransform(); + if (styleSheet != null) { + t.Load(styleSheet.Reader, settings, xmlResolver); + } + transformer(t, source.Reader, args); + } catch (System.Exception ex) { + throw new XMLUnitException(ex); + } + } + + /// <summary> + /// Convenience method that returns the result of the + /// transformation as a String. + /// </summary> + public string TransformToString() { + StringWriter sw = new StringWriter(); + TransformTo(sw); + return sw.ToString(); + } + + /// <summary> + /// Convenience method that returns the result of the + /// transformation as a Document. + /// </summary> + public XmlDocument TransformToDocument() { + using (MemoryStream ms = new MemoryStream()) { + TransformTo(ms); + ms.Flush(); + ms.Seek(0, SeekOrigin.Begin); + + XmlDocument doc = new XmlDocument(); + doc.Load(ms); + return doc; + } + } + + private delegate void Transformer(XslCompiledTransform t, + XmlReader r, + XsltArgumentList args); + + private static Transformer TransformToStream(Stream stream) { + return delegate(XslCompiledTransform t, XmlReader r, + XsltArgumentList args) { + t.Transform(r, args, stream); + }; + } + + private static Transformer TransformToTextWriter(TextWriter tw) { + return delegate(XslCompiledTransform t, XmlReader r, + XsltArgumentList args) { + t.Transform(r, args, tw); + }; + } + + private static Transformer TransformToXmlWriter(XmlWriter xw) { + return delegate(XslCompiledTransform t, XmlReader r, + XsltArgumentList args) { + t.Transform(r, args, xw); + }; + } + + } + +} + Property changes on: trunk/xmlunit/src/main/net-core/transform/Transformation.cs ___________________________________________________________________ Added: svn:eol-style + native Modified: trunk/xmlunit/src/tests/net-core/TestResources.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/TestResources.cs 2010-05-19 06:56:18 UTC (rev 389) +++ trunk/xmlunit/src/tests/net-core/TestResources.cs 2010-05-19 06:56:49 UTC (rev 390) @@ -17,6 +17,9 @@ public const string ANIMAL_FILE = "../../../src/tests/resources/test1.xml"; public const string BLAME_FILE = "../../../src/tests/resources/test.blame.html"; + public const string ANIMAL_XSL = "../../../src/tests/resources/animal.xsl"; + public const string DOG_FILE = "../../../src/tests/resources/testAnimal.xml"; + private TestResources() { } } } Added: trunk/xmlunit/src/tests/net-core/transform/TransformationTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/transform/TransformationTest.cs (rev 0) +++ trunk/xmlunit/src/tests/net-core/transform/TransformationTest.cs 2010-05-19 06:56:49 UTC (rev 390) @@ -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 System.Xml; +using net.sf.xmlunit.builder; +using NUnit.Framework; + +namespace net.sf.xmlunit.transform { + [TestFixture] + public class TransformationTest { + private Transformation t; + + [SetUp] public void CreateTransformation() { + t = new Transformation(Input.FromFile(TestResources.DOG_FILE) + .Build()); + t.Stylesheet = Input.FromFile(TestResources.ANIMAL_XSL).Build(); + } + + [Test] public void TransformAnimalToString() { + Assert.AreEqual("<?xml version=\"1.0\" encoding=\"utf-16\"?><dog />", + t.TransformToString()); + } + + [Test] public void TransformAnimalToDocument() { + XmlDocument doc = t.TransformToDocument(); + Assert.AreEqual("dog", doc.DocumentElement.Name); + } + } +} Property changes on: trunk/xmlunit/src/tests/net-core/transform/TransformationTest.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-05-19 06:56:24
|
Revision: 389 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=389&view=rev Author: bodewig Date: 2010-05-19 06:56:18 +0000 (Wed, 19 May 2010) Log Message: ----------- extract XSLT logic into something reusable Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/TestResources.java Added Paths: ----------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/transform/ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/transform/Transformation.java trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/transform/ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/transform/TransformationTest.java Removed Paths: ------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/TransformHelper.java Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java 2010-05-17 15:46:34 UTC (rev 388) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java 2010-05-19 06:56:18 UTC (rev 389) @@ -26,7 +26,6 @@ import javax.xml.transform.Source; import javax.xml.transform.TransformerFactory; import javax.xml.transform.URIResolver; -import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import net.sf.xmlunit.exceptions.XMLUnitException; @@ -161,14 +160,14 @@ TransformationBuilder withParameter(String name, Object value); TransformationBuilder withStylesheet(Builder b); TransformationBuilder withStylesheet(Source s); - TransformationBuilder withUriResolver(URIResolver r); + TransformationBuilder withURIResolver(URIResolver r); } private static class Transformation implements TransformationBuilder { - private final TransformHelper helper; + private final net.sf.xmlunit.transform.Transformation helper; private Transformation(Source s) { - helper = new TransformHelper(s); + helper = new net.sf.xmlunit.transform.Transformation(s); } public TransformationBuilder withStylesheet(Source s) { helper.setStylesheet(s); @@ -179,12 +178,12 @@ } public TransformationBuilder withOutputProperty(String name, String value) { - helper.setOutputProperty(name, value); + helper.addOutputProperty(name, value); return this; } public TransformationBuilder withParameter(String name, Object value) { - helper.setParameter(name, value); + helper.addParameter(name, value); return this; } @@ -193,15 +192,13 @@ return this; } - public TransformationBuilder withUriResolver(URIResolver r) { - helper.setUriResolver(r); + public TransformationBuilder withURIResolver(URIResolver r) { + helper.setURIResolver(r); return this; } public Source build() { - DOMResult r = new DOMResult(); - helper.transformTo(r); - return new DOMSource(r.getNode()); + return new DOMSource(helper.transformToDocument()); } } Deleted: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/TransformHelper.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/TransformHelper.java 2010-05-17 15:46:34 UTC (rev 388) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/TransformHelper.java 2010-05-19 06:56:18 UTC (rev 389) @@ -1,78 +0,0 @@ -/* - 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.builder; - -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import javax.xml.transform.Result; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.URIResolver; -import net.sf.xmlunit.exceptions.ConfigurationException; -import net.sf.xmlunit.exceptions.XMLUnitException; - -class TransformHelper { - private final Source source; - private Source styleSheet; - private TransformerFactory factory; - private URIResolver uriResolver; - private final Properties output = new Properties(); - private final Map<String, Object> params = new HashMap<String, Object>(); - TransformHelper(Source s) { - source = s; - } - void setStylesheet(Source s) { - styleSheet = s; - } - void setOutputProperty(String name, String value) { - output.setProperty(name, value); - } - void setParameter(String name, Object value) { - params.put(name, value); - } - void setFactory(TransformerFactory f) { - factory = f; - } - void setUriResolver(URIResolver r) { - uriResolver = r; - } - void transformTo(Result r) { - try { - TransformerFactory fac = factory; - if (fac == null) { - fac = TransformerFactory.newInstance(); - } - Transformer t = null; - if (styleSheet != null) { - t = fac.newTransformer(styleSheet); - } else { - t = fac.newTransformer(); - } - if (uriResolver != null) { - t.setURIResolver(uriResolver); - } - t.setOutputProperties(output); - for (Map.Entry<String, Object> ent : params.entrySet()) { - t.setParameter(ent.getKey(), ent.getValue()); - } - t.transform(source, r); - } catch (javax.xml.transform.TransformerConfigurationException e) { - throw new ConfigurationException(e); - } catch (javax.xml.transform.TransformerException e) { - throw new XMLUnitException(e); - } - } -} \ No newline at end of file Copied: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/transform/Transformation.java (from rev 388, trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/TransformHelper.java) =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/transform/Transformation.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/transform/Transformation.java 2010-05-19 06:56:18 UTC (rev 389) @@ -0,0 +1,222 @@ +/* + 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.transform; + +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import javax.xml.transform.ErrorListener; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.URIResolver; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.stream.StreamResult; +import net.sf.xmlunit.exceptions.ConfigurationException; +import net.sf.xmlunit.exceptions.XMLUnitException; +import org.w3c.dom.Document; + +/** + * Provides a convenience layer over TraX. + * + * <p>Apart from IllegalArgumentExceptions if you try to pass in null + * values only the transform methods will ever throw exceptions and + * these will be XMLUnit's runtime exceptions.</p> + * + * <p>Each invocation of a transform method will use a fresh + * Transformer instance, the transform methods are thread-safe.</p> + */ +public final class Transformation { + private Source source; + private Source styleSheet; + private TransformerFactory factory; + private URIResolver uriResolver; + private ErrorListener errorListener; + private final Properties output = new Properties(); + private final Map<String, Object> params = new HashMap<String, Object>(); + + public Transformation() { + } + /** + * @param s the source to transform - must not be null. + */ + public Transformation(Source s) { + setSource(s); + } + /** + * Set the source document to transform. + * @param s the source to transform - must not be null. + */ + public void setSource(Source s) { + if (s == null) { + throw new IllegalArgumentException("source must not be null"); + } + source = s; + } + /** + * Set the stylesheet to use. + * @param s the stylesheet to use - may be null in which case an + * identity transformation will be performed. + */ + public void setStylesheet(Source s) { + styleSheet = s; + } + /** + * Add a named output property. + * + * @param name name of the property - must not be null + * @param value value of the property - must not be null + */ + public void addOutputProperty(String name, String value) { + if (name == null) { + throw new IllegalArgumentException("name must not be null"); + } + if (value == null) { + throw new IllegalArgumentException("value must not be null"); + } + output.setProperty(name, value); + } + /** + * Clear all output properties. + */ + public void clearOutputProperties() { + output.clear(); + } + /** + * Add a named parameter. + * + * @param name name of the parameter - must not be null + * @param value value of the parameter - may be null + */ + public void addParameter(String name, Object value) { + if (name == null) { + throw new IllegalArgumentException("name must not be null"); + } + params.put(name, value); + } + /** + * Clear all output parameters. + */ + public void clearParameters() { + params.clear(); + } + /** + * Set the TraX factory to use. + * + * @param f the factory to use - may be null in which case the + * default factory will be used. + */ + public void setFactory(TransformerFactory f) { + factory = f; + } + /** + * Set the resolver to use for document() and xsl:include/import + * + * <p>The resolver will <b>not</b> be attached to the factory.</p> + * + * @param r the resolver - may be null in which case no explicit + * resolver will be used + */ + public void setURIResolver(URIResolver r) { + uriResolver = r; + } + /** + * Set the error listener for the transformation. + * + * <p>The listener will <b>not</b> be attached to the factory.</p> + * + * @param l the listener - may be null in which case no listener + * will be used + */ + public void setErrorListener(ErrorListener l) { + errorListener = l; + } + /** + * Perform the transformation. + * + * @param r where to send the transformation result - must not be null + * @exception IllegalArgumentException if source or result are null + * @exception ConfigurationException if the TraX system isn't + * configured properly + * @exception XMLUnitException if the transformation throws an + * exception + */ + public void transformTo(Result r) { + if (source == null) { + throw new IllegalArgumentException("source must not be null"); + } + if (r == null) { + throw new IllegalArgumentException("result must not be null"); + } + try { + TransformerFactory fac = factory; + if (fac == null) { + fac = TransformerFactory.newInstance(); + } + Transformer t = null; + if (styleSheet != null) { + t = fac.newTransformer(styleSheet); + } else { + t = fac.newTransformer(); + } + if (uriResolver != null) { + t.setURIResolver(uriResolver); + } + if (errorListener != null) { + t.setErrorListener(errorListener); + } + t.setOutputProperties(output); + for (Map.Entry<String, Object> ent : params.entrySet()) { + t.setParameter(ent.getKey(), ent.getValue()); + } + t.transform(source, r); + } catch (javax.xml.transform.TransformerConfigurationException e) { + throw new ConfigurationException(e); + } catch (javax.xml.transform.TransformerException e) { + throw new XMLUnitException(e); + } + } + /** + * Convenience method that returns the result of the + * transformation as a String. + * + * @exception IllegalArgumentException if source is null + * @exception ConfigurationException if the TraX system isn't + * configured properly + * @exception XMLUnitException if the transformation throws an + * exception + */ + public String transformToString() { + StringWriter sw = new StringWriter(); + transformTo(new StreamResult(sw)); + return sw.toString(); + } + /** + * Convenience method that returns the result of the + * transformation as a Document. + * + * @exception IllegalArgumentException if source is null + * @exception ConfigurationException if the TraX system isn't + * configured properly + * @exception XMLUnitException if the transformation throws an + * exception + */ + public Document transformToDocument() { + DOMResult r = new DOMResult(); + transformTo(r); + return (Document) r.getNode(); + } +} \ No newline at end of file Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/TestResources.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/TestResources.java 2010-05-17 15:46:34 UTC (rev 388) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/TestResources.java 2010-05-19 06:56:18 UTC (rev 389) @@ -16,6 +16,8 @@ public final class TestResources { public static final String ANIMAL_FILE = "src/tests/resources/test1.xml"; public static final String BLAME_FILE = "src/tests/resources/test.blame.html"; + public static final String ANIMAL_XSL = "src/tests/resources/animal.xsl"; + public static final String DOG_FILE = "src/tests/resources/testAnimal.xml"; private TestResources() { } Added: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/transform/TransformationTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/transform/TransformationTest.java (rev 0) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/transform/TransformationTest.java 2010-05-19 06:56:18 UTC (rev 389) @@ -0,0 +1,51 @@ +/* + 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.transform; + +import javax.xml.transform.OutputKeys; +import net.sf.xmlunit.TestResources; +import net.sf.xmlunit.builder.Input; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.Document; + +import static org.hamcrest.core.IsNot.*; +import static org.junit.Assert.*; + +public class TransformationTest { + private Transformation t; + + @Before public void createTransformation() { + t = new Transformation(Input.fromFile(TestResources.DOG_FILE) + .build()); + t.setStylesheet(Input.fromFile(TestResources.ANIMAL_XSL).build()); + } + + @Test public void transformAnimalToString() { + assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><dog/>", + t.transformToString()); + } + + @Test public void transformAnimalToDocument() { + Document doc = t.transformToDocument(); + assertEquals("dog", doc.getDocumentElement().getTagName()); + } + + @Test public void transformAnimalToHtml() { + t.addOutputProperty(OutputKeys.METHOD, "html"); + assertThat(t.transformToString(), + not("<?xml version=\"1.0\" encoding=\"UTF-8\"?><dog/>")); + } + +} Property changes on: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/transform/TransformationTest.java ___________________________________________________________________ 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-05-17 15:46:43
|
Revision: 388 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=388&view=rev Author: bodewig Date: 2010-05-17 15:46:34 +0000 (Mon, 17 May 2010) Log Message: ----------- extract reusable code from Input-by-XSLT Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java Added Paths: ----------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/TransformHelper.java Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java 2010-05-17 15:26:06 UTC (rev 387) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java 2010-05-17 15:46:34 UTC (rev 388) @@ -23,17 +23,12 @@ import java.net.URI; import java.net.URISyntaxException; import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; import javax.xml.transform.Source; -import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.URIResolver; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; -import net.sf.xmlunit.exceptions.ConfigurationException; import net.sf.xmlunit.exceptions.XMLUnitException; import org.w3c.dom.Document; import org.w3c.dom.Node; @@ -170,18 +165,13 @@ } private static class Transformation implements TransformationBuilder { - private final Source source; - private Source styleSheet; - private TransformerFactory factory; - private URIResolver uriResolver; - private final Properties output = new Properties(); - private final Map<String, Object> params = new HashMap<String, Object>(); + private final TransformHelper helper; private Transformation(Source s) { - source = s; + helper = new TransformHelper(s); } public TransformationBuilder withStylesheet(Source s) { - styleSheet = s; + helper.setStylesheet(s); return this; } public TransformationBuilder withStylesheet(Builder b) { @@ -189,52 +179,29 @@ } public TransformationBuilder withOutputProperty(String name, String value) { - output.setProperty(name, value); + helper.setOutputProperty(name, value); return this; } public TransformationBuilder withParameter(String name, Object value) { - params.put(name, value); + helper.setParameter(name, value); return this; } public TransformationBuilder usingFactory(TransformerFactory f) { - factory = f; + helper.setFactory(f); return this; } public TransformationBuilder withUriResolver(URIResolver r) { - uriResolver = r; + helper.setUriResolver(r); return this; } public Source build() { - try { - DOMResult r = new DOMResult(); - TransformerFactory fac = factory; - if (fac == null) { - fac = TransformerFactory.newInstance(); - } - Transformer t = null; - if (styleSheet != null) { - t = fac.newTransformer(styleSheet); - } else { - t = fac.newTransformer(); - } - if (uriResolver != null) { - t.setURIResolver(uriResolver); - } - t.setOutputProperties(output); - for (Map.Entry<String, Object> ent : params.entrySet()) { - t.setParameter(ent.getKey(), ent.getValue()); - } - t.transform(source, r); - return new DOMSource(r.getNode()); - } catch (javax.xml.transform.TransformerConfigurationException e) { - throw new ConfigurationException(e); - } catch (javax.xml.transform.TransformerException e) { - throw new XMLUnitException(e); - } + DOMResult r = new DOMResult(); + helper.transformTo(r); + return new DOMSource(r.getNode()); } } Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/TransformHelper.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/TransformHelper.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/TransformHelper.java 2010-05-17 15:46:34 UTC (rev 388) @@ -0,0 +1,78 @@ +/* + 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.builder; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.URIResolver; +import net.sf.xmlunit.exceptions.ConfigurationException; +import net.sf.xmlunit.exceptions.XMLUnitException; + +class TransformHelper { + private final Source source; + private Source styleSheet; + private TransformerFactory factory; + private URIResolver uriResolver; + private final Properties output = new Properties(); + private final Map<String, Object> params = new HashMap<String, Object>(); + TransformHelper(Source s) { + source = s; + } + void setStylesheet(Source s) { + styleSheet = s; + } + void setOutputProperty(String name, String value) { + output.setProperty(name, value); + } + void setParameter(String name, Object value) { + params.put(name, value); + } + void setFactory(TransformerFactory f) { + factory = f; + } + void setUriResolver(URIResolver r) { + uriResolver = r; + } + void transformTo(Result r) { + try { + TransformerFactory fac = factory; + if (fac == null) { + fac = TransformerFactory.newInstance(); + } + Transformer t = null; + if (styleSheet != null) { + t = fac.newTransformer(styleSheet); + } else { + t = fac.newTransformer(); + } + if (uriResolver != null) { + t.setURIResolver(uriResolver); + } + t.setOutputProperties(output); + for (Map.Entry<String, Object> ent : params.entrySet()) { + t.setParameter(ent.getKey(), ent.getValue()); + } + t.transform(source, r); + } catch (javax.xml.transform.TransformerConfigurationException e) { + throw new ConfigurationException(e); + } catch (javax.xml.transform.TransformerException e) { + throw new XMLUnitException(e); + } + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/TransformHelper.java ___________________________________________________________________ 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-05-17 15:26:13
|
Revision: 387 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=387&view=rev Author: bodewig Date: 2010-05-17 15:26:06 +0000 (Mon, 17 May 2010) Log Message: ----------- system ID stuff Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/builder/InputTest.java Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java 2010-05-17 13:38:46 UTC (rev 386) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java 2010-05-17 15:26:06 UTC (rev 387) @@ -21,6 +21,7 @@ import java.io.Reader; import java.io.StringReader; import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.util.HashMap; import java.util.Map; @@ -73,6 +74,11 @@ private StreamBuilder(Reader r) { source = new StreamSource(r); } + void setSystemId(String id) { + if (id != null) { + source.setSystemId(id); + } + } public Source build() { assert source != null; return source; @@ -116,7 +122,16 @@ baos.write(buf, 0, read); } } - return fromMemory(baos.toByteArray()); + StreamBuilder b = + (StreamBuilder) fromMemory(baos.toByteArray()); + try { + b.setSystemId(url.toURI().toString()); + } catch (URISyntaxException use) { + // impossible - shouldn't have been an URL in the + // first place + b.setSystemId(url.toString()); + } + return b; } finally { if (in != null) { in.close(); Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/builder/InputTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/builder/InputTest.java 2010-05-17 13:38:46 UTC (rev 386) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/builder/InputTest.java 2010-05-17 15:26:06 UTC (rev 387) @@ -47,11 +47,15 @@ } @Test public void shouldParseAnExistingFileByName() throws Exception { - allIsWellFor(Input.fromFile(TestResources.ANIMAL_FILE).build()); + Source s = Input.fromFile(TestResources.ANIMAL_FILE).build(); + allIsWellFor(s); + assertEquals(toFileUri(TestResources.ANIMAL_FILE), s.getSystemId()); } @Test public void shouldParseAnExistingFileByFile() throws Exception { - allIsWellFor(Input.fromFile(new File(TestResources.ANIMAL_FILE)).build()); + Source s = Input.fromFile(new File(TestResources.ANIMAL_FILE)).build(); + allIsWellFor(s); + assertEquals(toFileUri(TestResources.ANIMAL_FILE), s.getSystemId()); } @Test public void shouldParseAnExistingFileFromStream() throws Exception { @@ -92,11 +96,13 @@ } @Test public void shouldParseFileFromURI() throws Exception { - allIsWellFor(Input.fromURI(new URI("file:" + TestResources.ANIMAL_FILE)).build()); + allIsWellFor(Input.fromURI(new URI("file:" + TestResources.ANIMAL_FILE)) + .build()); } @Test public void shouldParseFileFromURL() throws Exception { - allIsWellFor(Input.fromURL(new URL("file:" + TestResources.ANIMAL_FILE)).build()); + allIsWellFor(Input.fromURL(new URL("file:" + TestResources.ANIMAL_FILE)) + .build()); } @Test public void shouldParseATransformationFromSource() throws Exception { @@ -141,4 +147,8 @@ is.close(); return bos.toByteArray(); } + + private static String toFileUri(String fileName) { + return new File(fileName).toURI().toString(); + } } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-05-17 13:38:53
|
Revision: 386 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=386&view=rev Author: bodewig Date: 2010-05-17 13:38:46 +0000 (Mon, 17 May 2010) Log Message: ----------- Add SystemId to ISource, enable file-URI tests Modified Paths: -------------- trunk/xmlunit/src/main/net-core/ISource.cs trunk/xmlunit/src/main/net-core/builder/Input.cs trunk/xmlunit/src/main/net-core/input/AbstractSource.cs trunk/xmlunit/src/tests/net-core/builder/InputTest.cs Modified: trunk/xmlunit/src/main/net-core/ISource.cs =================================================================== --- trunk/xmlunit/src/main/net-core/ISource.cs 2010-05-17 12:12:14 UTC (rev 385) +++ trunk/xmlunit/src/main/net-core/ISource.cs 2010-05-17 13:38:46 UTC (rev 386) @@ -16,5 +16,6 @@ namespace net.sf.xmlunit { public interface ISource { XmlReader Reader {get;} + string SystemId {get; set;} } } Modified: trunk/xmlunit/src/main/net-core/builder/Input.cs =================================================================== --- trunk/xmlunit/src/main/net-core/builder/Input.cs 2010-05-17 12:12:14 UTC (rev 385) +++ trunk/xmlunit/src/main/net-core/builder/Input.cs 2010-05-17 13:38:46 UTC (rev 386) @@ -11,6 +11,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +using System; using System.IO; using System.Xml; using System.Xml.Xsl; @@ -52,6 +53,11 @@ internal StreamBuilder(TextReader r) { source = new StreamSource(r); } + internal string SystemId { + set { + source.SystemId = value ?? string.Empty; + } + } public ISource Build() { return source; } @@ -62,11 +68,23 @@ } public static IBuilder FromStream(Stream s) { - return new StreamBuilder(s); + StreamBuilder b = new StreamBuilder(s); + if (s is FileStream) { + b.SystemId = new Uri(Path.GetFullPath((s as FileStream).Name)) + .ToString(); + } + return b; } public static IBuilder FromReader(TextReader r) { - return new StreamBuilder(r); + StreamBuilder b = new StreamBuilder(r); + StreamReader s = r as StreamReader; + if (s != null && s.BaseStream is FileStream) { + b.SystemId = + new Uri(Path.GetFullPath((s.BaseStream as FileStream).Name)) + .ToString(); + } + return b; } public static IBuilder FromMemory(string s) { Modified: trunk/xmlunit/src/main/net-core/input/AbstractSource.cs =================================================================== --- trunk/xmlunit/src/main/net-core/input/AbstractSource.cs 2010-05-17 12:12:14 UTC (rev 385) +++ trunk/xmlunit/src/main/net-core/input/AbstractSource.cs 2010-05-17 13:38:46 UTC (rev 386) @@ -15,14 +15,24 @@ namespace net.sf.xmlunit.input { public abstract class AbstractSource : ISource { + private string systemId; private readonly XmlReader reader; protected AbstractSource(XmlReader r) { reader = r; + systemId = r.BaseURI; } public XmlReader Reader { get { return reader; } } + public string SystemId { + get { + return systemId; + } + set { + systemId = value; + } + } } } Modified: trunk/xmlunit/src/tests/net-core/builder/InputTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/builder/InputTest.cs 2010-05-17 12:12:14 UTC (rev 385) +++ trunk/xmlunit/src/tests/net-core/builder/InputTest.cs 2010-05-17 13:38:46 UTC (rev 386) @@ -35,20 +35,28 @@ } [Test] public void ShouldParseAnExistingFileByName() { - AllIsWellFor(Input.FromFile(TestResources.ANIMAL_FILE).Build()); + ISource s = Input.FromFile(TestResources.ANIMAL_FILE).Build(); + AllIsWellFor(s); + Assert.AreEqual(ToFileUri(TestResources.ANIMAL_FILE), s.SystemId); } [Test] public void ShouldParseAnExistingFileFromStream() { using (FileStream fs = new FileStream(TestResources.ANIMAL_FILE, FileMode.Open, FileAccess.Read)) { - AllIsWellFor(Input.FromStream(fs).Build()); + ISource s = Input.FromStream(fs).Build(); + AllIsWellFor(s); + Assert.AreEqual(ToFileUri(TestResources.ANIMAL_FILE), + s.SystemId); } } [Test] public void ShouldParseAnExistingFileFromReader() { using (StreamReader r = new StreamReader(TestResources.ANIMAL_FILE)) { - AllIsWellFor(Input.FromReader(r).Build()); + ISource s = Input.FromReader(r).Build(); + AllIsWellFor(s); + Assert.AreEqual(ToFileUri(TestResources.ANIMAL_FILE), + s.SystemId); } } @@ -61,17 +69,20 @@ AllIsWellFor(Input.FromMemory(ReadTestFile()).Build()); } - [Ignore("looks as if file-URIs didn't work, revisit")] [Test] public void ShouldParseFileFromURIString() { - AllIsWellFor(Input.FromURI("file:" + TestResources.ANIMAL_FILE) - .Build()); + ISource s = Input.FromURI(ToFileUri(TestResources.ANIMAL_FILE)) + .Build(); + AllIsWellFor(s); + Assert.AreEqual(ToFileUri(TestResources.ANIMAL_FILE), + s.SystemId); } - [Ignore("looks as if file-URIs didn't work, revisit")] [Test] public void ShouldParseFileFromURI() { - AllIsWellFor(Input.FromURI(new Uri("file:" - + TestResources.ANIMAL_FILE)) - .Build()); + ISource s = Input.FromURI(new Uri(ToFileUri(TestResources.ANIMAL_FILE))) + .Build(); + AllIsWellFor(s); + Assert.AreEqual(ToFileUri(TestResources.ANIMAL_FILE), + s.SystemId); } [Test] public void ShouldParseATransformationFromSource() { @@ -116,5 +127,9 @@ return ms.ToArray(); } } + + private static string ToFileUri(string path) { + return new Uri(Path.GetFullPath(path)).ToString(); + } } } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-05-17 12:13:20
|
Revision: 385 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=385&view=rev Author: bodewig Date: 2010-05-17 12:12:14 +0000 (Mon, 17 May 2010) Log Message: ----------- a bunch of convenience methods Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java trunk/xmlunit/src/main/net-core/builder/Input.cs Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java 2010-05-07 16:14:55 UTC (rev 384) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/builder/Input.java 2010-05-17 12:12:14 UTC (rev 385) @@ -28,12 +28,14 @@ import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; +import javax.xml.transform.URIResolver; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import net.sf.xmlunit.exceptions.ConfigurationException; import net.sf.xmlunit.exceptions.XMLUnitException; import org.w3c.dom.Document; +import org.w3c.dom.Node; public class Input { @@ -43,7 +45,7 @@ private static class DOMBuilder implements Builder { private final Source source; - private DOMBuilder(Document d) { + private DOMBuilder(Node d) { source = new DOMSource(d); } public Source build() { @@ -56,6 +58,10 @@ return new DOMBuilder(d); } + public static Builder fromNode(Node n) { + return new DOMBuilder(n); + } + private static class StreamBuilder implements Builder { private final Source source; private StreamBuilder(File f) { @@ -140,15 +146,19 @@ } public static interface TransformationBuilder extends Builder { + TransformationBuilder usingFactory(TransformerFactory f); + TransformationBuilder withOutputProperty(String name, String value); + TransformationBuilder withParameter(String name, Object value); + TransformationBuilder withStylesheet(Builder b); TransformationBuilder withStylesheet(Source s); - TransformationBuilder withStylesheet(Builder b); - TransformationBuilder withParameter(String name, Object value); - TransformationBuilder withOutputProperty(String name, String value); + TransformationBuilder withUriResolver(URIResolver r); } private static class Transformation implements TransformationBuilder { private final Source source; private Source styleSheet; + private TransformerFactory factory; + private URIResolver uriResolver; private final Properties output = new Properties(); private final Map<String, Object> params = new HashMap<String, Object>(); @@ -173,16 +183,32 @@ return this; } + public TransformationBuilder usingFactory(TransformerFactory f) { + factory = f; + return this; + } + + public TransformationBuilder withUriResolver(URIResolver r) { + uriResolver = r; + return this; + } + public Source build() { try { DOMResult r = new DOMResult(); - TransformerFactory fac = TransformerFactory.newInstance(); + TransformerFactory fac = factory; + if (fac == null) { + fac = TransformerFactory.newInstance(); + } Transformer t = null; if (styleSheet != null) { t = fac.newTransformer(styleSheet); } else { t = fac.newTransformer(); } + if (uriResolver != null) { + t.setURIResolver(uriResolver); + } t.setOutputProperties(output); for (Map.Entry<String, Object> ent : params.entrySet()) { t.setParameter(ent.getKey(), ent.getValue()); Modified: trunk/xmlunit/src/main/net-core/builder/Input.cs =================================================================== --- trunk/xmlunit/src/main/net-core/builder/Input.cs 2010-05-07 16:14:55 UTC (rev 384) +++ trunk/xmlunit/src/main/net-core/builder/Input.cs 2010-05-17 12:12:14 UTC (rev 385) @@ -25,7 +25,7 @@ internal class DOMBuilder : IBuilder { private readonly ISource source; - internal DOMBuilder(XmlDocument d) { + internal DOMBuilder(XmlNode d) { source = new DOMSource(d); } public ISource Build() { @@ -37,6 +37,10 @@ return new DOMBuilder(d); } + public static IBuilder FromNode(XmlNode n) { + return new DOMBuilder(n); + } + internal class StreamBuilder : IBuilder { private readonly ISource source; internal StreamBuilder(string s) { @@ -82,18 +86,25 @@ } public interface ITransformationBuilder : IBuilder { - ITransformationBuilder WithStylesheet(ISource s); - ITransformationBuilder WithStylesheet(IBuilder b); + ITransformationBuilder WithDocumentFunction(); ITransformationBuilder WithExtensionObject(string namespaceUri, object extension); ITransformationBuilder WithParameter(string name, string namespaceUri, object parameter); + ITransformationBuilder WithScripting(); + ITransformationBuilder WithStylesheet(ISource s); + ITransformationBuilder WithStylesheet(IBuilder b); + ITransformationBuilder WithXmlResolver(XmlResolver r); + ITransformationBuilder WithoutDocumentFunction(); + ITransformationBuilder WithoutScripting(); } internal class Transformation : ITransformationBuilder { private readonly ISource source; private ISource styleSheet; + private XmlResolver xmlResolver = new XmlUrlResolver(); + private readonly XsltSettings settings = new XsltSettings(); private readonly XsltArgumentList args = new XsltArgumentList(); internal Transformation(ISource s) { source = s; @@ -119,11 +130,42 @@ return this; } + public ITransformationBuilder WithXmlResolver(XmlResolver r) { + xmlResolver = r; + return this; + } + + public ITransformationBuilder WithScripting() { + return WithScripting(true); + } + + public ITransformationBuilder WithoutScripting() { + return WithScripting(false); + } + + private ITransformationBuilder WithScripting(bool b) { + settings.EnableScript = b; + return this; + } + + public ITransformationBuilder WithDocumentFunction() { + return WithDocumentFunction(true); + } + + public ITransformationBuilder WithoutDocumentFunction() { + return WithDocumentFunction(false); + } + + private ITransformationBuilder WithDocumentFunction(bool b) { + settings.EnableDocumentFunction = b; + return this; + } + public ISource Build() { try { XslCompiledTransform t = new XslCompiledTransform(); if (styleSheet != null) { - t.Load(styleSheet.Reader); + t.Load(styleSheet.Reader, settings, xmlResolver); } MemoryStream ms = new MemoryStream(); using (ms) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-05-07 16:15:01
|
Revision: 384 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=384&view=rev Author: bodewig Date: 2010-05-07 16:14:55 +0000 (Fri, 07 May 2010) Log Message: ----------- listener management Added Paths: ----------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonListenerSupport.java trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/ComparisonListenerSupportTest.java Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonListenerSupport.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonListenerSupport.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonListenerSupport.java 2010-05-07 16:14:55 UTC (rev 384) @@ -0,0 +1,78 @@ +/* + 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.Iterator; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * Encapsulates support for DifferenceListeners so it can be reused by + * different implementations of IDifferenceEngine. + */ +public class ComparisonListenerSupport { + private final List<ComparisonListener> compListeners = + new CopyOnWriteArrayList<ComparisonListener>(); + private final List<ComparisonListener> matchListeners = + new CopyOnWriteArrayList<ComparisonListener>(); + private final List<ComparisonListener> diffListeners = + new CopyOnWriteArrayList<ComparisonListener>(); + + /** + * Registers a listener that is notified of each comparison. + */ + public void addComparisonListener(ComparisonListener l) { + compListeners.add(l); + } + + /** + * Registers a listener that is notified of each comparison with + * outcome {@link ComparisonResult#EQUAL}. + */ + public void addMatchListener(ComparisonListener l) { + matchListeners.add(l); + } + + /** + * Registers a listener that is notified of each comparison with + * outcome other than {@link ComparisonResult#EQUAL}. + */ + public void addDifferenceListener(ComparisonListener l) { + diffListeners.add(l); + } + + /** + * Propagates the result of a comparision to all registered + * listeners. + */ + public void fireComparisonPerformed(Comparison comparison, + ComparisonResult outcome) { + fire(comparison, outcome, compListeners); + if (outcome == ComparisonResult.EQUAL) { + fire(comparison, outcome, matchListeners); + } else { + fire(comparison, outcome, diffListeners); + } + } + + private static void fire(Comparison comparison, ComparisonResult outcome, + List<ComparisonListener> listeners) { + if (!listeners.isEmpty()) { + for (Iterator<ComparisonListener> it = listeners.iterator(); + it.hasNext(); ) { + it.next().comparisonPerformed(comparison, outcome); + } + } + } +} Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonListenerSupport.java ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/ComparisonListenerSupportTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/ComparisonListenerSupportTest.java (rev 0) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/ComparisonListenerSupportTest.java 2010-05-07 16:14:55 UTC (rev 384) @@ -0,0 +1,71 @@ +/* + 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.Arrays; +import java.util.HashSet; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class ComparisonListenerSupportTest { + + @Test public void dispatchesOnOutcome() { + ComparisonListenerSupport s = new ComparisonListenerSupport(); + Listener c, m, d; + s.addComparisonListener(c = new Listener(ComparisonResult.EQUAL, + ComparisonResult.SIMILAR, + ComparisonResult.DIFFERENT, + ComparisonResult.CRITICAL)); + s.addMatchListener(m = new Listener(ComparisonResult.EQUAL)); + s.addDifferenceListener(d = new Listener(ComparisonResult.SIMILAR, + ComparisonResult.DIFFERENT, + ComparisonResult.CRITICAL)); + for (ComparisonResult r : new ComparisonResult[] { + ComparisonResult.EQUAL, + ComparisonResult.SIMILAR, + ComparisonResult.DIFFERENT, + ComparisonResult.CRITICAL + }) { + s.fireComparisonPerformed(null, r); + } + + assertEquals(4, c.invocations); + assertEquals(1, m.invocations); + assertEquals(3, d.invocations); + } + + @Test public void noListenersDontCauseProblems() { + ComparisonListenerSupport s = new ComparisonListenerSupport(); + s.fireComparisonPerformed(null, ComparisonResult.EQUAL); + } + + private static class Listener implements ComparisonListener { + private final HashSet<ComparisonResult> acceptable = + new HashSet<ComparisonResult>(); + private int invocations = 0; + + private Listener(ComparisonResult... accept) { + acceptable.addAll(Arrays.asList(accept)); + } + + public void comparisonPerformed(Comparison comparison, + ComparisonResult outcome) { + invocations++; + if (!acceptable.contains(outcome)) { + fail("unexpected outcome: " + outcome); + } + } + } +} Property changes on: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/ComparisonListenerSupportTest.java ___________________________________________________________________ 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-05-07 11:45:57
|
Revision: 383 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=383&view=rev Author: bodewig Date: 2010-05-07 11:45:51 +0000 (Fri, 07 May 2010) Log Message: ----------- default difference evaluators Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonType.java trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs Added Paths: ----------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs 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-05-07 05:48:03 UTC (rev 382) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonType.java 2010-05-07 11:45:51 UTC (rev 383) @@ -29,12 +29,12 @@ * If the documents both have DOCTYPEs, compare the PUBLIC * identifiers. */ - DOCTYPE_PUBLIC, + DOCTYPE_PUBLIC_ID, /** * If the documents both have DOCTYPEs, compare the SYSTEM * identifiers. */ - DOCTYPE_SYSTEM, + DOCTYPE_SYSTEM_ID, /** * Check whether both documents provide the same values for Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java 2010-05-07 11:45:51 UTC (rev 383) @@ -0,0 +1,92 @@ +/* + 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.w3c.dom.Node; + +/** + * Evaluators used for the base cases. + */ +public final class DifferenceEvaluators { + private DifferenceEvaluators() { } + + private static final Short CDATA = Node.TEXT_NODE; + private static final Short TEXT = Node.CDATA_SECTION_NODE; + + /** + * The "standard" difference evaluator which decides which + * differences make two XML documents really different and which + * still leave them similar. + */ + public static final DifferenceEvaluator Default = + new DifferenceEvaluator() { + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult outcome) { + if (outcome == ComparisonResult.DIFFERENT) { + switch (comparison.getType()) { + case NODE_TYPE: + Short control = (Short) comparison + .getControlNodeDetails().getValue(); + Short test = (Short) comparison + .getTestNodeDetails().getValue(); + if ((control.equals(TEXT) && test.equals(CDATA)) + || + (control.equals(CDATA) && test.equals(TEXT))) { + outcome = ComparisonResult.SIMILAR; + } + break; + case HAS_DOCTYPE_DECLARATION: + case DOCTYPE_SYSTEM_ID: + case SCHEMA_LOCATION: + case NO_NAMESPACE_SCHEMA_LOCATION: + case NAMESPACE_PREFIX: + case ATTR_VALUE_EXPLICITLY_SPECIFIED: + case CHILD_NODELIST_SEQUENCE: + outcome = ComparisonResult.SIMILAR; + break; + } + } + return outcome; + } + }; + + /** + * Makes the comparison stop as soon as the first "real" + * difference is encountered, uses the {@link #Default default} + * evaluator to decide which differences leave the documents + * simlar. + */ + public static final DifferenceEvaluator defaultStopWhenDifferent + = stopWhenDifferent(Default); + + /** + * Makes the comparison stop as soon as the first "real" + * difference is encountered. + * @param nestedEvaluator provides the initial decision whether a + * difference is "real" or still leaves the documents in a similar + * state. + */ + public static DifferenceEvaluator + stopWhenDifferent(final DifferenceEvaluator nestedEvaluator) { + return new DifferenceEvaluator() { + public ComparisonResult evaluate(Comparison comparison, + ComparisonResult outcome) { + ComparisonResult r = nestedEvaluator.evaluate(comparison, + outcome); + return r == ComparisonResult.DIFFERENT + ? ComparisonResult.CRITICAL : r; + } + }; + } +} Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluators.java ___________________________________________________________________ Added: svn:eol-style + native Modified: trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs 2010-05-07 05:48:03 UTC (rev 382) +++ trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs 2010-05-07 11:45:51 UTC (rev 383) @@ -30,12 +30,12 @@ /// If the documents both have DOCTYPEs, compare the PUBLIC /// identifiers. /// </summary> - DOCTYPE_PUBLIC, + DOCTYPE_PUBLIC_ID, /// <summary> /// If the documents both have DOCTYPEs, compare the SYSTEM /// identifiers. /// </summary> - DOCTYPE_SYSTEM, + DOCTYPE_SYSTEM_ID, /// <summary> /// Check whether both documents provide the same values for Added: trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.cs 2010-05-07 11:45:51 UTC (rev 383) @@ -0,0 +1,91 @@ +/* + 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.Xml; + +namespace net.sf.xmlunit.diff { + + /// <summary> + /// Evaluators used for the base cases. + /// </summary> + public sealed class DifferenceEvaluators { + private DifferenceEvaluators() { } + + /// <summary> + /// The "standard" difference evaluator which decides which + /// differences make two XML documents really different and which + /// still leave them similar. + /// </summary> + public static ComparisonResult Default(Comparison comparison, + ComparisonResult outcome) { + if (outcome == ComparisonResult.DIFFERENT) { + switch (comparison.Type) { + case ComparisonType.NODE_TYPE: + XmlNodeType control = + (XmlNodeType) comparison.ControlNodeDetails.Value; + XmlNodeType test = + (XmlNodeType) comparison.TestNodeDetails.Value; + if ((control == XmlNodeType.Text && test == XmlNodeType.CDATA) + || + (control == XmlNodeType.CDATA && test == XmlNodeType.Text) + ) { + outcome = ComparisonResult.SIMILAR; + } + break; + case ComparisonType.HAS_DOCTYPE_DECLARATION: + case ComparisonType.DOCTYPE_SYSTEM_ID: + case ComparisonType.SCHEMA_LOCATION: + case ComparisonType.NO_NAMESPACE_SCHEMA_LOCATION: + case ComparisonType.NAMESPACE_PREFIX: + case ComparisonType.ATTR_VALUE_EXPLICITLY_SPECIFIED: + case ComparisonType.CHILD_NODELIST_SEQUENCE: + outcome = ComparisonResult.SIMILAR; + break; + } + } + return outcome; + } + + private static readonly DifferenceEvaluator defaultStopWhenDifferent + = StopWhenDifferent(Default); + + /// <summary> + /// Makes the comparison stop as soon as the first "real" + /// difference is encountered, uses the {@link #Default default} + /// evaluator to decide which differences leave the documents + /// simlar. + /// </summary> + public static DifferenceEvaluator DefaultStopWhenDifferent { + get { + return defaultStopWhenDifferent; + } + } + + /// <summary> + /// Makes the comparison stop as soon as the first "real" + /// difference is encountered. + /// </summary> + /// <param name="nestedEvaluator">provides the initial + /// decision whether a difference is "real" or still leaves + /// the documents in a similar state.</param> + public static DifferenceEvaluator + StopWhenDifferent(DifferenceEvaluator nestedEvaluator) { + return delegate(Comparison comparison, ComparisonResult outcome) { + ComparisonResult r = nestedEvaluator(comparison, outcome); + return r == ComparisonResult.DIFFERENT + ? ComparisonResult.CRITICAL : r; + }; + } + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluators.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-05-07 05:48:09
|
Revision: 382 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=382&view=rev Author: bodewig Date: 2010-05-07 05:48:03 +0000 (Fri, 07 May 2010) Log Message: ----------- port ElementSelectors to .NET Added Paths: ----------- trunk/xmlunit/src/main/net-core/diff/ElementSelectors.cs trunk/xmlunit/src/main/net-core/util/Nodes.cs trunk/xmlunit/src/tests/net-core/diff/ trunk/xmlunit/src/tests/net-core/diff/ElementSelectorsTest.cs trunk/xmlunit/src/tests/net-core/util/ trunk/xmlunit/src/tests/net-core/util/NodesTest.cs Added: trunk/xmlunit/src/main/net-core/diff/ElementSelectors.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/ElementSelectors.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/diff/ElementSelectors.cs 2010-05-07 05:48:03 UTC (rev 382) @@ -0,0 +1,262 @@ +/* + 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 net.sf.xmlunit.util; + +namespace net.sf.xmlunit.diff { + + /// <summary> + /// Common ElementSelector implementations. + /// </summary> + public sealed class ElementSelectors { + private ElementSelectors() { } + + /// <summary> + /// Always returns true, i.e. each element can be compared to each + /// other element. + /// </summary> + /// <remarks> + /// Generally this means elements will be compared in document + /// order. + /// </remarks> + public static bool Default(XmlElement controlElement, + XmlElement testElement) { + return true; + } + + /// <summary> + /// Elements with the same local name (and namespace URI - if any) + /// can be compared. + /// </summary> + public static bool ByName(XmlElement controlElement, + XmlElement testElement) { + return controlElement != null && testElement != null + && BothNullOrEqual(Nodes.GetQName(controlElement), + Nodes.GetQName(testElement)); + } + + /// <summary> + /// Elements with the same local name (and namespace URI - if any) + /// and nested text (if any) can be compared. + /// </summary> + public static bool ByNameAndText(XmlElement controlElement, + XmlElement testElement) { + return ByName(controlElement, testElement) + && BothNullOrEqual(Nodes.GetMergedNestedText(controlElement), + Nodes.GetMergedNestedText(testElement)); + } + + /// <summary> + /// Elements with the same local name (and namespace URI - if any) + /// and attribute values for the given attribute names can be + /// compared. + /// </summary> + /// <remarks>Attributes are only searched for in the null + /// namespace.</remarks> + public static ElementSelector + ByNameAndAttributes(params string[] attribs) { + if (attribs == null) { + throw new ArgumentNullException("attribs"); + } + XmlQualifiedName[] qs = new XmlQualifiedName[attribs.Length]; + for (int i = 0; i < attribs.Length; i++) { + qs[i] = new XmlQualifiedName(attribs[i]); + } + return ByNameAndAttributes(qs); + } + + /// <summary> + /// Elements with the same local name (and namespace URI - if any) + /// and attribute values for the given attribute names can be + /// compared. + /// </summary> + public static ElementSelector + ByNameAndAttributes(params XmlQualifiedName[] attribs) { + if (attribs == null) { + throw new ArgumentNullException("attribs"); + } + XmlQualifiedName[] qs = new XmlQualifiedName[attribs.Length]; + Array.Copy(attribs, 0, qs, 0, qs.Length); + return delegate(XmlElement controlElement, XmlElement testElement) { + if (!ByName(controlElement, testElement)) { + return false; + } + return MapsEqualForKeys(Nodes.GetAttributes(controlElement), + Nodes.GetAttributes(testElement), + qs); + }; + } + + /// <summary> + /// Elements with the same local name (and namespace URI - if any) + /// and attribute values for the given attribute names can be + /// compared. + /// </summary> + /// <remarks> + /// Namespace URIs of attributes are those of the attributes on + /// the control element or the null namespace if the don't + /// exist. + /// </remarks> + public static ElementSelector + ByNameAndAttributesControlNS(params string[] attribs) { + if (attribs == null) { + throw new ArgumentNullException("attribs"); + } + List<string> ats = new List<string>(attribs); + return delegate(XmlElement controlElement, XmlElement testElement) { + if (!ByName(controlElement, testElement)) { + return false; + } + IDictionary<XmlQualifiedName, string> cAttrs = + Nodes.GetAttributes(controlElement); + IDictionary<string, XmlQualifiedName> qNameByLocalName = + new Dictionary<string, XmlQualifiedName>(); + foreach (XmlQualifiedName q in cAttrs.Keys) { + string local = q.Name; + if (ats.Contains(local)) { + qNameByLocalName[local] = q; + } + } + foreach (string a in ats) { + if (!qNameByLocalName.ContainsKey(a)) { + qNameByLocalName[a] = new XmlQualifiedName(a); + } + } + return MapsEqualForKeys(cAttrs, + Nodes.GetAttributes(testElement), + qNameByLocalName.Values); + }; + } + + /// <summary> + /// Elements with the same local name (and namespace URI - if any) + /// and attribute values for all attributes can be compared. + /// </summary> + public static bool ByNameAndAllAttributes(XmlElement controlElement, + XmlElement testElement) { + if (!ByName(controlElement, testElement)) { + return false; + } + IDictionary<XmlQualifiedName, string> cAttrs = + Nodes.GetAttributes(controlElement); + IDictionary<XmlQualifiedName, string> tAttrs = + Nodes.GetAttributes(testElement); + if (cAttrs.Count != tAttrs.Count) { + return false; + } + return MapsEqualForKeys(cAttrs, tAttrs, cAttrs.Keys); + } + + /// <summary> + /// Elements with the same local name (and namespace URI - if any) + /// and child elements and nested text at each level (if any) can + /// be compared. + /// </summary> + public static bool ByNameAndTextRec(XmlElement controlElement, + XmlElement testElement) { + if (!ByNameAndText(controlElement, testElement)) { + return false; + } + + XmlNodeList controlChildren = controlElement.ChildNodes; + XmlNodeList testChildren = testElement.ChildNodes; + int controlLen = controlChildren.Count; + int testLen = testChildren.Count; + int controlIndex, testIndex; + for (controlIndex = testIndex = 0; + controlIndex < controlLen && testIndex < testLen; + ) { + // find next non-text child nodes + XmlNode c = controlChildren[controlIndex]; + while (IsText(c) && ++controlIndex < controlLen) { + c = controlChildren[controlIndex]; + } + if (IsText(c)) { + break; + } + XmlNode t = testChildren[testIndex]; + while (IsText(t) && ++testIndex < testLen) { + t = testChildren[testIndex]; + } + if (IsText(t)) { + break; + } + + // different types of children make elements + // non-comparable + if (c.NodeType != t.NodeType) { + return false; + } + // recurse for child elements + if (c is XmlElement + && !ByNameAndTextRec(c as XmlElement, t as XmlElement)) { + return false; + } + + controlIndex++; + testIndex++; + } + + // child lists exhausted? + if (controlIndex < controlLen) { + XmlNode n = controlChildren[controlIndex]; + while (IsText(n) && ++controlIndex < controlLen) { + n = controlChildren[controlIndex]; + } + // some non-Text children remained + if (controlIndex < controlLen) { + return false; + } + } + if (testIndex < testLen) { + XmlNode n = testChildren[testIndex]; + while (IsText(n) && ++testIndex < testLen) { + n = testChildren[testIndex]; + } + // some non-Text children remained + if (testIndex < testLen) { + return false; + } + } + return true; + } + + private static bool BothNullOrEqual(object o1, object o2) { + return o1 == null ? o2 == null : o1.Equals(o2); + } + + private static bool + MapsEqualForKeys(IDictionary<XmlQualifiedName, string> control, + IDictionary<XmlQualifiedName, string> test, + IEnumerable<XmlQualifiedName> keys) { + foreach (XmlQualifiedName q in keys) { + string c, t; + if (control.TryGetValue(q, out c) != test.TryGetValue(q, out t)) { + return false; + } + if (!BothNullOrEqual(c, t)) { + return false; + } + } + return true; + } + + private static bool IsText(XmlNode n) { + return n is XmlText || n is XmlCDataSection; + } + } +} Property changes on: trunk/xmlunit/src/main/net-core/diff/ElementSelectors.cs ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/net-core/util/Nodes.cs =================================================================== --- trunk/xmlunit/src/main/net-core/util/Nodes.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/util/Nodes.cs 2010-05-07 05:48:03 UTC (rev 382) @@ -0,0 +1,68 @@ +/* + 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.Generic; +using System.Text; +using System.Xml; + +namespace net.sf.xmlunit.util { + /// <summary> + /// Utility algorithms that work on DOM nodes. + /// </summary> + public sealed class Nodes { + private Nodes() { } + + /// <summary> + /// Extracts a Node's name and namespace URI (if any). + /// </summary> + public static XmlQualifiedName GetQName(XmlNode n) { + return new XmlQualifiedName(n.LocalName, n.NamespaceURI); + } + + /// <summary> + /// Tries to merge all direct Text and CDATA children of the given + /// Node and concatenates their value. + /// </summary> + /// <return>an empty string if the Node has no Text or CDATA + /// children.</return> + public static string GetMergedNestedText(XmlNode n) { + StringBuilder sb = new StringBuilder(); + foreach (XmlNode child in n.ChildNodes) { + if (child is XmlText || child is XmlCDataSection) { + string s = child.Value; + if (s != null) { + sb.Append(s); + } + } + } + return sb.ToString(); + } + + /// <summary> + /// Obtains an element's attributes as dictionary. + /// </summary> + public static IDictionary<XmlQualifiedName, string> + GetAttributes(XmlNode n) { + IDictionary<XmlQualifiedName, string> map = + new Dictionary<XmlQualifiedName, string>(); + XmlAttributeCollection coll = n.Attributes; + if (coll != null) { + foreach (XmlAttribute a in coll) { + map[GetQName(a)] = a.Value; + } + } + return map; + } + } +} Property changes on: trunk/xmlunit/src/main/net-core/util/Nodes.cs ___________________________________________________________________ Added: svn:eol-style + native Copied: trunk/xmlunit/src/tests/net-core/diff/ElementSelectorsTest.cs (from rev 379, trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/ElementSelectorsTest.java) =================================================================== --- trunk/xmlunit/src/tests/net-core/diff/ElementSelectorsTest.cs (rev 0) +++ trunk/xmlunit/src/tests/net-core/diff/ElementSelectorsTest.cs 2010-05-07 05:48:03 UTC (rev 382) @@ -0,0 +1,268 @@ +/* + 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.Xml; +using NUnit.Framework; + +namespace net.sf.xmlunit.diff { + + [TestFixture] + public class ElementSelectorsTest { + private const string FOO = "foo"; + private const string BAR = "bar"; + private const string SOME_URI = "urn:some:uri"; + + private XmlDocument doc; + + [SetUp] public void CreateDoc() { + doc = new XmlDocument(); + } + + private void PureElementNameComparisons(ElementSelector s) { + XmlElement control = doc.CreateElement(FOO); + XmlElement equal = doc.CreateElement(FOO); + XmlElement different = doc.CreateElement(BAR); + XmlElement controlNS = doc.CreateElement(BAR, FOO, SOME_URI); + + Assert.IsFalse(s(null, null)); + Assert.IsFalse(s(null, control)); + Assert.IsFalse(s(control, null)); + Assert.IsTrue(s(control, equal)); + Assert.IsFalse(s(control, different)); + Assert.IsFalse(s(control, controlNS)); + Assert.IsTrue(s(doc.CreateElement(FOO, SOME_URI), controlNS)); + } + + [Test] public void ByName() { + PureElementNameComparisons(ElementSelectors.ByName); + } + + [Test] public void ByNameAndText_NamePart() { + PureElementNameComparisons(ElementSelectors.ByNameAndText); + } + + private void ByNameAndText_SingleLevel(ElementSelector s) { + XmlElement control = doc.CreateElement(FOO); + control.AppendChild(doc.CreateTextNode(BAR)); + XmlElement equal = doc.CreateElement(FOO); + equal.AppendChild(doc.CreateTextNode(BAR)); + XmlElement equalC = doc.CreateElement(FOO); + equalC.AppendChild(doc.CreateCDataSection(BAR)); + XmlElement noText = doc.CreateElement(FOO); + XmlElement differentText = doc.CreateElement(FOO); + differentText.AppendChild(doc.CreateTextNode(BAR)); + differentText.AppendChild(doc.CreateTextNode(BAR)); + + Assert.IsTrue(s(control, equal)); + Assert.IsTrue(s(control, equalC)); + Assert.IsFalse(s(control, noText)); + Assert.IsFalse(s(control, differentText)); + } + + [Test] public void ByNameAndText() { + ByNameAndText_SingleLevel(ElementSelectors.ByNameAndText); + } + + [Test] public void ByNameAndTextRec_NamePart() { + PureElementNameComparisons(ElementSelectors.ByNameAndTextRec); + } + + [Test] public void ByNameAndTextRec_Single() { + ByNameAndText_SingleLevel(ElementSelectors.ByNameAndTextRec); + } + + [Test] public void ByNameAndTextRec() { + XmlElement control = doc.CreateElement(FOO); + XmlElement child = doc.CreateElement(BAR); + control.AppendChild(child); + child.AppendChild(doc.CreateTextNode(BAR)); + XmlElement equal = doc.CreateElement(FOO); + XmlElement child2 = doc.CreateElement(BAR); + equal.AppendChild(child2); + child2.AppendChild(doc.CreateTextNode(BAR)); + XmlElement equalC = doc.CreateElement(FOO); + XmlElement child3 = doc.CreateElement(BAR); + equalC.AppendChild(child3); + child3.AppendChild(doc.CreateCDataSection(BAR)); + XmlElement noText = doc.CreateElement(FOO); + XmlElement differentLevel = doc.CreateElement(FOO); + differentLevel.AppendChild(doc.CreateTextNode(BAR)); + XmlElement differentElement = doc.CreateElement(FOO); + XmlElement child4 = doc.CreateElement(FOO); + differentElement.AppendChild(child4); + child4.AppendChild(doc.CreateTextNode(BAR)); + XmlElement differentText = doc.CreateElement(FOO); + XmlElement child5 = doc.CreateElement(BAR); + differentText.AppendChild(child5); + child5.AppendChild(doc.CreateTextNode(FOO)); + + ElementSelector s = ElementSelectors.ByNameAndTextRec; + Assert.IsTrue(s(control, equal)); + Assert.IsTrue(s(control, equalC)); + Assert.IsFalse(s(control, noText)); + Assert.IsFalse(s(control, differentLevel)); + Assert.IsFalse(s(control, differentElement)); + Assert.IsFalse(s(control, differentText)); + } + + [Test] public void ByNameAndAllAttributes_NamePart() { + PureElementNameComparisons(ElementSelectors.ByNameAndAllAttributes); + } + + [Test] public void ByNameAndAllAttributes() { + XmlElement control = doc.CreateElement(FOO); + control.SetAttribute(BAR, BAR); + XmlElement equal = doc.CreateElement(FOO); + equal.SetAttribute(BAR, BAR); + XmlElement noAttributes = doc.CreateElement(FOO); + XmlElement differentValue = doc.CreateElement(FOO); + differentValue.SetAttribute(BAR, FOO); + XmlElement differentName = doc.CreateElement(FOO); + differentName.SetAttribute(FOO, FOO); + XmlElement differentNS = doc.CreateElement(FOO); + differentNS.SetAttribute(BAR, SOME_URI, BAR); + + Assert.IsTrue(ElementSelectors.ByNameAndAllAttributes(control, + equal)); + Assert.IsFalse(ElementSelectors.ByNameAndAllAttributes(control, + noAttributes)); + Assert.IsFalse(ElementSelectors.ByNameAndAllAttributes(noAttributes, + control)); + Assert.IsFalse(ElementSelectors.ByNameAndAllAttributes(control, + differentValue)); + Assert.IsFalse(ElementSelectors.ByNameAndAllAttributes(control, + differentName)); + Assert.IsFalse(ElementSelectors.ByNameAndAllAttributes(control, + differentNS)); + } + + [Test] public void ByNameAndAttributes_NamePart() { + PureElementNameComparisons(ElementSelectors + .ByNameAndAttributes(new string[] {})); + PureElementNameComparisons(ElementSelectors + .ByNameAndAttributes(new XmlQualifiedName[] {})); + PureElementNameComparisons(ElementSelectors.ByNameAndAttributes(BAR)); + PureElementNameComparisons(ElementSelectors + .ByNameAndAttributes(new XmlQualifiedName(BAR, + SOME_URI))); + } + + [Test] public void ByNameAndAttributes_String() { + XmlElement control = doc.CreateElement(FOO); + control.SetAttribute(BAR, BAR); + XmlElement equal = doc.CreateElement(FOO); + equal.SetAttribute(BAR, BAR); + XmlElement noAttributes = doc.CreateElement(FOO); + XmlElement differentValue = doc.CreateElement(FOO); + differentValue.SetAttribute(BAR, FOO); + XmlElement differentName = doc.CreateElement(FOO); + differentName.SetAttribute(FOO, FOO); + XmlElement differentNS = doc.CreateElement(FOO); + differentNS.SetAttribute(BAR, SOME_URI, BAR); + + Assert.IsTrue(ElementSelectors.ByNameAndAttributes(BAR)(control, + equal)); + Assert.IsFalse(ElementSelectors.ByNameAndAttributes(BAR)(control, + noAttributes)); + Assert.IsTrue(ElementSelectors.ByNameAndAttributes(FOO)(control, + noAttributes)); + Assert.IsTrue(ElementSelectors.ByNameAndAttributes(new string[] {}) + (control, noAttributes)); + Assert.IsFalse(ElementSelectors.ByNameAndAttributes(BAR)(noAttributes, + control)); + Assert.IsFalse(ElementSelectors.ByNameAndAttributes(BAR)(control, + differentValue)); + Assert.IsFalse(ElementSelectors.ByNameAndAttributes(BAR)(control, + differentName)); + Assert.IsFalse(ElementSelectors.ByNameAndAttributes(BAR)(control, + differentNS)); + } + + [Test] public void byNameAndAttributes_QName() { + XmlElement control = doc.CreateElement(FOO); + control.SetAttribute(BAR, BAR); + XmlElement equal = doc.CreateElement(FOO); + equal.SetAttribute(BAR, BAR); + XmlElement noAttributes = doc.CreateElement(FOO); + XmlElement differentValue = doc.CreateElement(FOO); + differentValue.SetAttribute(BAR, FOO); + XmlElement differentName = doc.CreateElement(FOO); + differentName.SetAttribute(FOO, FOO); + XmlElement differentNS = doc.CreateElement(FOO); + differentNS.SetAttribute(BAR, SOME_URI, BAR); + + Assert.IsTrue(ElementSelectors.ByNameAndAttributes(new XmlQualifiedName(BAR)) + (control, equal)); + Assert.IsFalse(ElementSelectors.ByNameAndAttributes(new XmlQualifiedName(BAR)) + (control, noAttributes)); + Assert.IsTrue(ElementSelectors.ByNameAndAttributes(new XmlQualifiedName(FOO)) + (control, noAttributes)); + Assert.IsTrue(ElementSelectors.ByNameAndAttributes(new XmlQualifiedName[] {}) + (control, noAttributes)); + Assert.IsFalse(ElementSelectors.ByNameAndAttributes(new XmlQualifiedName(BAR)) + (noAttributes, control)); + Assert.IsFalse(ElementSelectors.ByNameAndAttributes(new XmlQualifiedName(BAR)) + (control, differentValue)); + Assert.IsFalse(ElementSelectors.ByNameAndAttributes(new XmlQualifiedName(BAR)) + (control, differentName)); + Assert.IsFalse(ElementSelectors.ByNameAndAttributes(new XmlQualifiedName(BAR)) + (control, differentNS)); + } + + [Test] public void ByNameAndAttributesControlNS_NamePart() { + PureElementNameComparisons(ElementSelectors + .ByNameAndAttributesControlNS()); + PureElementNameComparisons(ElementSelectors + .ByNameAndAttributesControlNS(BAR)); + } + + [Test] public void ByNameAndAttributesControlNS() { + XmlElement control = doc.CreateElement(FOO); + control.SetAttribute(BAR, SOME_URI, BAR); + XmlElement equal = doc.CreateElement(FOO); + equal.SetAttribute(BAR, SOME_URI, BAR); + XmlElement noAttributes = doc.CreateElement(FOO); + XmlElement differentValue = doc.CreateElement(FOO); + differentValue.SetAttribute(BAR, SOME_URI, FOO); + XmlElement differentName = doc.CreateElement(FOO); + differentName.SetAttribute(FOO, SOME_URI, FOO); + XmlElement differentNS = doc.CreateElement(FOO); + differentNS.SetAttribute(BAR, SOME_URI + "2", BAR); + XmlElement noNS = doc.CreateElement(FOO); + noNS.SetAttribute(BAR, BAR); + + Assert.IsTrue(ElementSelectors.ByNameAndAttributesControlNS(BAR) + (control, equal)); + Assert.IsFalse(ElementSelectors.ByNameAndAttributesControlNS(BAR) + (control, noAttributes)); + Assert.IsTrue(ElementSelectors.ByNameAndAttributesControlNS(FOO) + (control, noAttributes)); + Assert.IsTrue(ElementSelectors.ByNameAndAttributesControlNS() + (control, noAttributes)); + Assert.IsTrue(ElementSelectors.ByNameAndAttributesControlNS(BAR) + (noAttributes, control)); + Assert.IsFalse(ElementSelectors.ByNameAndAttributesControlNS(BAR) + (noAttributes, noNS)); + Assert.IsFalse(ElementSelectors.ByNameAndAttributesControlNS(BAR) + (control, differentValue)); + Assert.IsFalse(ElementSelectors.ByNameAndAttributesControlNS(BAR) + (control, differentName)); + Assert.IsFalse(ElementSelectors.ByNameAndAttributesControlNS(BAR) + (control, differentNS)); + Assert.IsFalse(ElementSelectors.ByNameAndAttributesControlNS(BAR) + (control, noNS)); + } + + } +} \ No newline at end of file Added: trunk/xmlunit/src/tests/net-core/util/NodesTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/util/NodesTest.cs (rev 0) +++ trunk/xmlunit/src/tests/net-core/util/NodesTest.cs 2010-05-07 05:48:03 UTC (rev 382) @@ -0,0 +1,125 @@ +/* + 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.Generic; +using System.Xml; +using NUnit.Framework; + +namespace net.sf.xmlunit.util { + [TestFixture] + public class NodesTest { + + private const string FOO = "foo"; + private const string BAR = "bar"; + private const string SOME_URI = "urn:some:uri"; + + private XmlDocument doc; + + [SetUp] + public void CreateDoc() { + doc = new XmlDocument(); + } + + [Test] public void QNameOfElementWithNoNs() { + XmlElement e = doc.CreateElement(FOO); + XmlQualifiedName q = Nodes.GetQName(e); + Assert.AreEqual(FOO, q.Name); + Assert.AreEqual(string.Empty, q.Namespace); + Assert.AreEqual(new XmlQualifiedName(FOO), q); + } + + [Test] public void QNameOfXmlElementWithNsNoPrefix() { + XmlElement e = doc.CreateElement(FOO, SOME_URI); + XmlQualifiedName q = Nodes.GetQName(e); + Assert.AreEqual(FOO, q.Name); + Assert.AreEqual(SOME_URI, q.Namespace); + Assert.AreEqual(new XmlQualifiedName(FOO, SOME_URI), q); + } + + [Test] public void QNameOfXmlElementWithNsAndPrefix() { + XmlElement e = doc.CreateElement(BAR, FOO, SOME_URI); + XmlQualifiedName q = Nodes.GetQName(e); + Assert.AreEqual(FOO, q.Name); + Assert.AreEqual(SOME_URI, q.Namespace); + Assert.AreEqual(new XmlQualifiedName(FOO, SOME_URI), q); + } + + [Test] public void MergeNoTexts() { + XmlElement e = doc.CreateElement(FOO); + Assert.AreEqual(string.Empty, Nodes.GetMergedNestedText(e)); + } + + [Test] public void MergeSingleTextNode() { + XmlElement e = doc.CreateElement(FOO); + XmlText t = doc.CreateTextNode(BAR); + e.AppendChild(t); + Assert.AreEqual(BAR, Nodes.GetMergedNestedText(e)); + } + + [Test] public void MergeSingleCDATASection() { + XmlElement e = doc.CreateElement(FOO); + XmlCDataSection t = doc.CreateCDataSection(BAR); + e.AppendChild(t); + Assert.AreEqual(BAR, Nodes.GetMergedNestedText(e)); + } + + [Test] public void MergeIgnoresTextOfChildren() { + XmlElement e = doc.CreateElement(FOO); + XmlElement c = doc.CreateElement("child"); + XmlText t = doc.CreateTextNode(BAR); + e.AppendChild(c); + c.AppendChild(t); + Assert.AreEqual(string.Empty, Nodes.GetMergedNestedText(e)); + } + + [Test] public void MergeIgnoresComments() { + XmlElement e = doc.CreateElement(FOO); + XmlComment c = doc.CreateComment(BAR); + e.AppendChild(c); + Assert.AreEqual(string.Empty, Nodes.GetMergedNestedText(e)); + } + + [Test] public void MergeMultipleChildren() { + XmlElement e = doc.CreateElement(FOO); + XmlCDataSection c = doc.CreateCDataSection(BAR); + e.AppendChild(c); + e.AppendChild(doc.CreateElement("child")); + XmlText t = doc.CreateTextNode(BAR); + e.AppendChild(t); + Assert.AreEqual(BAR + BAR, Nodes.GetMergedNestedText(e)); + } + + [Test] public void AttributeMapNoAttributes() { + XmlElement e = doc.CreateElement(FOO); + IDictionary<XmlQualifiedName, string> m = Nodes.GetAttributes(e); + Assert.AreEqual(0, m.Count); + } + + [Test] public void AttributeIDictionaryNoNS() { + XmlElement e = doc.CreateElement(FOO); + e.SetAttribute(FOO, BAR); + IDictionary<XmlQualifiedName, string> m = Nodes.GetAttributes(e); + Assert.AreEqual(1, m.Count); + Assert.AreEqual(BAR, m[new XmlQualifiedName(FOO)]); + } + + [Test] public void AttributeIDictionarywithNS() { + XmlElement e = doc.CreateElement(FOO); + e.SetAttribute(FOO, SOME_URI, BAR); + IDictionary<XmlQualifiedName, string> m = Nodes.GetAttributes(e); + Assert.AreEqual(1, m.Count); + Assert.AreEqual(BAR, m[new XmlQualifiedName(FOO, SOME_URI)]); + } + } +} Property changes on: trunk/xmlunit/src/tests/net-core/util/NodesTest.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-05-05 15:47:27
|
Revision: 379 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=379&view=rev Author: bodewig Date: 2010-05-05 15:47:17 +0000 (Wed, 05 May 2010) Log Message: ----------- replace old ElementQualifiers with new code that (almost) does the same Modified Paths: -------------- trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/ElementNameAndAttributeQualifier.java trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/ElementNameAndTextQualifier.java trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/ElementNameQualifier.java trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/examples/RecursiveElementNameAndTextQualifier.java trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_ElementNameAndAttributeQualifier.java Added Paths: ----------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ElementSelectors.java trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Nodes.java trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/ElementSelectorsTest.java trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/NodesTest.java Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ElementSelectors.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ElementSelectors.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ElementSelectors.java 2010-05-05 15:47:17 UTC (rev 379) @@ -0,0 +1,277 @@ +/* + 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.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import javax.xml.namespace.QName; +import net.sf.xmlunit.util.Nodes; +import org.w3c.dom.CDATASection; +import org.w3c.dom.Element; +import org.w3c.dom.Text; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * Common ElementSelector implementations. + */ +public final class ElementSelectors { + private ElementSelectors() { } + + /** + * Always returns true, i.e. each element can be compared to each + * other element. + * + * <p>Generally this means elements will be compared in document + * order.</p> + */ + public static final ElementSelector Default = new ElementSelector() { + public boolean canBeCompared(Element controlElement, + Element testElement) { + return true; + } + }; + + /** + * Elements with the same local name (and namespace URI - if any) + * can be compared. + */ + public static final ElementSelector byName = new ElementSelector() { + public boolean canBeCompared(Element controlElement, + Element testElement) { + return controlElement != null + && testElement != null + && bothNullOrEqual(Nodes.getQName(controlElement), + Nodes.getQName(testElement)); + } + }; + + /** + * Elements with the same local name (and namespace URI - if any) + * and nested text (if any) can be compared. + */ + public static final ElementSelector byNameAndText = new ElementSelector() { + public boolean canBeCompared(Element controlElement, + Element testElement) { + return byName.canBeCompared(controlElement, testElement) + && bothNullOrEqual(Nodes.getMergedNestedText(controlElement), + Nodes.getMergedNestedText(testElement)); + } + }; + + /** + * Elements with the same local name (and namespace URI - if any) + * and attribute values for the given attribute names can be + * compared. + * + * <p>Attributes are only searched for in the null namespace.</p> + */ + public static ElementSelector byNameAndAttributes(String... attribs) { + if (attribs == null) { + throw new IllegalArgumentException("attributes must not be null"); + } + QName[] qs = new QName[attribs.length]; + for (int i = 0; i < attribs.length; i++) { + qs[i] = new QName(attribs[i]); + } + return byNameAndAttributes(qs); + } + + /** + * Elements with the same local name (and namespace URI - if any) + * and attribute values for the given attribute names can be + * compared. + * + * <p>Namespace URIs of attributes are those of the attributes on + * the control element or the null namespace if the don't + * exist.</p> + */ + public static ElementSelector + byNameAndAttributesControlNS(final String... attribs) { + + if (attribs == null) { + throw new IllegalArgumentException("attributes must not be null"); + } + final HashSet<String> as = new HashSet(Arrays.asList(attribs)); + return new ElementSelector() { + public boolean canBeCompared(Element controlElement, + Element testElement) { + if (!byName.canBeCompared(controlElement, testElement)) { + return false; + } + Map<QName, String> cAttrs = Nodes.getAttributes(controlElement); + Map<String, QName> qNameByLocalName = + new HashMap<String, QName>(); + for (QName q : cAttrs.keySet()) { + String local = q.getLocalPart(); + if (as.contains(local)) { + qNameByLocalName.put(local, q); + } + } + for (String a : attribs) { + QName q = qNameByLocalName.get(a); + if (q == null) { + qNameByLocalName.put(a, new QName(a)); + } + } + return mapsEqualForKeys(cAttrs, + Nodes.getAttributes(testElement), + qNameByLocalName.values()); + } + }; + } + + /** + * Elements with the same local name (and namespace URI - if any) + * and attribute values for the given attribute names can be + * compared. + */ + public static ElementSelector byNameAndAttributes(final QName... attribs) { + if (attribs == null) { + throw new IllegalArgumentException("attributes must not be null"); + } + final Collection<QName> qs = Arrays.asList(attribs); + return new ElementSelector() { + public boolean canBeCompared(Element controlElement, + Element testElement) { + if (!byName.canBeCompared(controlElement, testElement)) { + return false; + } + return mapsEqualForKeys(Nodes.getAttributes(controlElement), + Nodes.getAttributes(testElement), + qs); + } + }; + } + + /** + * Elements with the same local name (and namespace URI - if any) + * and attribute values for all attributes can be compared. + */ + public static final ElementSelector byNameAndAllAttributes = + new ElementSelector() { + public boolean canBeCompared(Element controlElement, + Element testElement) { + if (!byName.canBeCompared(controlElement, testElement)) { + return false; + } + Map<QName, String> cAttrs = Nodes.getAttributes(controlElement); + Map<QName, String> tAttrs = Nodes.getAttributes(testElement); + if (cAttrs.size() != tAttrs.size()) { + return false; + } + return mapsEqualForKeys(cAttrs, tAttrs, cAttrs.keySet()); + } + }; + + /** + * Elements with the same local name (and namespace URI - if any) + * and child elements and nested text at each level (if any) can + * be compared. + */ + public static final ElementSelector + byNameAndTextRec = new ElementSelector() { + public boolean canBeCompared(Element controlElement, + Element testElement) { + if (!byNameAndText.canBeCompared(controlElement, + testElement)) { + return false; + } + NodeList controlChildren = controlElement.getChildNodes(); + NodeList testChildren = testElement.getChildNodes(); + final int controlLen = controlChildren.getLength(); + final int testLen = testChildren.getLength(); + int controlIndex, testIndex; + for (controlIndex = testIndex = 0; + controlIndex < controlLen && testIndex < testLen; + ) { + // find next non-text child nodes + Node c = controlChildren.item(controlIndex); + while (isText(c) && ++controlIndex < controlLen) { + c = controlChildren.item(controlIndex); + } + if (isText(c)) { + break; + } + Node t = testChildren.item(testIndex); + while (isText(t) && ++testIndex < testLen) { + t = testChildren.item(testIndex); + } + if (isText(t)) { + break; + } + + // different types of children make elements + // non-comparable + if (c.getNodeType() != t.getNodeType()) { + return false; + } + // recurse for child elements + if (c instanceof Element + && !byNameAndTextRec.canBeCompared((Element) c, + (Element) t)) { + return false; + } + + controlIndex++; + testIndex++; + } + + // child lists exhausted? + if (controlIndex < controlLen) { + Node n = controlChildren.item(controlIndex); + while (isText(n) && ++controlIndex < controlLen) { + n = controlChildren.item(controlIndex); + } + // some non-Text children remained + if (controlIndex < controlLen) { + return false; + } + } + if (testIndex < testLen) { + Node n = testChildren.item(testIndex); + while (isText(n) && ++testIndex < testLen) { + n = testChildren.item(testIndex); + } + // some non-Text children remained + if (testIndex < testLen) { + return false; + } + } + return true; + } + }; + + private static boolean bothNullOrEqual(Object o1, Object o2) { + return o1 == null ? o2 == null : o1.equals(o2); + } + + private static boolean mapsEqualForKeys(Map<QName, String> control, + Map<QName, String> test, + Iterable<QName> keys) { + for (QName q : keys) { + if (!bothNullOrEqual(control.get(q), test.get(q))) { + return false; + } + } + return true; + } + + private static boolean isText(Node n) { + return n instanceof Text || n instanceof CDATASection; + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ElementSelectors.java ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Nodes.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Nodes.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Nodes.java 2010-05-05 15:47:17 UTC (rev 379) @@ -0,0 +1,80 @@ +/* + 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.Map; +import java.util.LinkedHashMap; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.w3c.dom.Attr; +import org.w3c.dom.CDATASection; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.Text; + +/** + * Utility algorithms that work on DOM nodes. + */ +public final class Nodes { + private Nodes() { } + + /** + * Extracts a Node's name, namespace URI (if any) and prefix as a + * QName. + */ + public static QName getQName(Node n) { + String s = n.getLocalName(); + String p = n.getPrefix(); + return s != null + ? new QName(n.getNamespaceURI(), s, + p != null ? p: XMLConstants.DEFAULT_NS_PREFIX) + : new QName(n.getNodeName()); + } + + /** + * Tries to merge all direct Text and CDATA children of the given + * Node and concatenates their value. + * + * @return an empty string if the Node has no Text or CDATA + * children. + */ + public static String getMergedNestedText(Node n) { + StringBuilder sb = new StringBuilder(); + for (Node child : new IterableNodeList(n.getChildNodes())) { + if (child instanceof Text || child instanceof CDATASection) { + String s = child.getNodeValue(); + if (s != null) { + sb.append(s); + } + } + } + return sb.toString(); + } + + /** + * Obtains an element's attributes as Map. + */ + public static Map<QName, String> getAttributes(Node n) { + Map<QName, String> map = new LinkedHashMap<QName, String>(); + NamedNodeMap m = n.getAttributes(); + if (m != null) { + final int len = m.getLength(); + for (int i = 0; i < len; i++) { + Attr a = (Attr) m.item(i); + map.put(getQName(a), a.getValue()); + } + } + return map; + } +} Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/util/Nodes.java ___________________________________________________________________ Added: svn:eol-style + native Modified: trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/ElementNameAndAttributeQualifier.java =================================================================== --- trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/ElementNameAndAttributeQualifier.java 2010-05-03 16:08:17 UTC (rev 378) +++ trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/ElementNameAndAttributeQualifier.java 2010-05-05 15:47:17 UTC (rev 379) @@ -37,6 +37,8 @@ package org.custommonkey.xmlunit; import java.util.Arrays; +import net.sf.xmlunit.diff.ElementSelector; +import net.sf.xmlunit.diff.ElementSelectors; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; @@ -50,10 +52,11 @@ * @see Diff#overrideElementQualifier(ElementQualifier) */ public class ElementNameAndAttributeQualifier extends ElementNameQualifier { + private final ElementSelector selector; private static final String[] ALL_ATTRIBUTES = {"*"}; - + private final String[] qualifyingAttrNames; - + /** * No-args constructor: use all attributes from all elements to determine * whether elements qualify for comparability @@ -61,7 +64,7 @@ public ElementNameAndAttributeQualifier() { this(ALL_ATTRIBUTES); } - + /** * Simple constructor for a single qualifying attribute name * @param attrName the value to use to qualify whether two elements can be @@ -80,6 +83,9 @@ this.qualifyingAttrNames = new String[attrNames.length]; System.arraycopy(attrNames, 0, qualifyingAttrNames, 0, attrNames.length); + selector = matchesAllAttributes(attrNames) + ? ElementSelectors.byNameAndAllAttributes + : ElementSelectors.byNameAndAttributesControlNS(attrNames); } /** @@ -94,12 +100,9 @@ * false otherwise */ public boolean qualifyForComparison(Element control, Element test) { - if (super.qualifyForComparison(control, test)) { - return areAttributesComparable(control, test); - } - return false; + return selector.canBeCompared(control, test); } - + /** * Determine whether the qualifying attributes are present in both elements * and if so whether their values are the same @@ -123,7 +126,7 @@ qualifyingAttributes[n] = (Attr) namedNodeMap.getNamedItem(qualifyingAttrNames[n]); } } - + String nsURI, name; for (int i=0; i < qualifyingAttributes.length; ++i) { if (qualifyingAttributes[i] != null) { Modified: trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/ElementNameAndTextQualifier.java =================================================================== --- trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/ElementNameAndTextQualifier.java 2010-05-03 16:08:17 UTC (rev 378) +++ trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/ElementNameAndTextQualifier.java 2010-05-05 15:47:17 UTC (rev 379) @@ -36,6 +36,7 @@ package org.custommonkey.xmlunit; +import net.sf.xmlunit.diff.ElementSelectors; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -60,19 +61,16 @@ * elements; false otherwise */ public boolean qualifyForComparison(Element control, Element test) { - if (super.qualifyForComparison(control, test)) { - return similar(extractText(control), extractText(test)); - } - return false; + return ElementSelectors.byNameAndText.canBeCompared(control, test); } - + /** * Determine whether the text nodes contain similar values * @param control * @param test * @return true if text nodes are similar, false otherwise */ - protected boolean similar(Text control, Text test) { + protected boolean similar(Text control, Text test) { if (control == null) { return test == null; } else if (test == null) { @@ -97,6 +95,6 @@ } } return null; - } + } } Modified: trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/ElementNameQualifier.java =================================================================== --- trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/ElementNameQualifier.java 2010-05-03 16:08:17 UTC (rev 378) +++ trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/ElementNameQualifier.java 2010-05-05 15:47:17 UTC (rev 379) @@ -36,6 +36,7 @@ package org.custommonkey.xmlunit; +import net.sf.xmlunit.diff.ElementSelectors; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -58,10 +59,9 @@ * false otherwise */ public boolean qualifyForComparison(Element control, Element test) { - return control != null && test !=null - && equalsNamespace(control, test) - && getNonNamespacedNodeName(control).equals(getNonNamespacedNodeName(test)); + return ElementSelectors.byName.canBeCompared(control, test); } + /** * Determine whether two nodes are defined by the same namespace URI * @param control @@ -77,7 +77,7 @@ } return controlNS.equals(testNS); } - + /** * Strip any namespace information off a node name * @param node Modified: trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/examples/RecursiveElementNameAndTextQualifier.java =================================================================== --- trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/examples/RecursiveElementNameAndTextQualifier.java 2010-05-03 16:08:17 UTC (rev 378) +++ trunk/xmlunit/src/main/java-legacy/org/custommonkey/xmlunit/examples/RecursiveElementNameAndTextQualifier.java 2010-05-05 15:47:17 UTC (rev 379) @@ -36,11 +36,8 @@ package org.custommonkey.xmlunit.examples; +import net.sf.xmlunit.diff.ElementSelectors; import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import org.custommonkey.xmlunit.ElementNameQualifier; import org.custommonkey.xmlunit.ElementQualifier; /** @@ -52,9 +49,6 @@ */ public class RecursiveElementNameAndTextQualifier implements ElementQualifier { - private static final ElementNameQualifier NAME_QUALIFIER = - new ElementNameQualifier(); - /** * Uses element names and the text nested an arbitrary level of * child elements deeper into the element to compare @@ -71,128 +65,7 @@ */ public boolean qualifyForComparison(Element currentControl, Element currentTest) { - return compareNodes(currentControl, currentTest); + return ElementSelectors.byNameAndTextRec.canBeCompared(currentControl, + currentTest); } - - private boolean compareNodes(Node currentControl, Node currentTest) { - try { - - // if they are elements, compare names of the two nodes - if (!NAME_QUALIFIER.qualifyForComparison((Element) currentControl, - (Element) currentTest)) { - return false; - } - - // Compare the control and test elements' children - - NodeList controlNodes = null; - NodeList testNodes = null; - - // Check that both nodes have children and, if so, get lists of them - - if (currentControl.hasChildNodes() && currentTest.hasChildNodes()) { - controlNodes = currentControl.getChildNodes(); - testNodes = currentTest.getChildNodes(); - } else if (currentControl.hasChildNodes() - || currentTest.hasChildNodes()) { - return false; - - // if both nodes are empty, they are comparable - } else { - return true; - } - - // check that both node lists have the same length - - if (countNodesWithoutConsecutiveTextNodes(controlNodes) - != countNodesWithoutConsecutiveTextNodes(testNodes)) { - return false; - } - - // Do checks of test and control nodes' children - - final int cNodes = controlNodes.getLength(); - final int tNodes = testNodes.getLength(); - - int i, j; - for (i = j = 0; i < cNodes && j < tNodes; i++, j++) { - Node testNode = testNodes.item(i); - Node controlNode = controlNodes.item(j); - - // check if both node are same type - if (controlNode.getNodeType() != testNode.getNodeType()) { - return false; - } - // compare text nodes - if (controlNode.getNodeType() == Node.TEXT_NODE) { - // compare concatenated, trimmed text nodes - if (!catText(controlNode).equals(catText(testNode))) { - return false; - } - - // swallow adjacent Text nodes - for (; i < cNodes - 1 - && controlNodes.item(i + 1).getNodeType() == Node.TEXT_NODE; - i++); - for (; j < tNodes - 1 - && testNodes.item(j + 1).getNodeType() == Node.TEXT_NODE; - j++); - - // recursive check of current child control and test nodes' - // children - - } else if (!compareNodes((Element) controlNode, - (Element) testNode)) { - return false; - } - } - if (i != cNodes || j != tNodes) { - return false; - } - - // All descendants of current control and test nodes are comparable - return true; - } catch (Exception e) { - return false; - } - } - /** - * Concatenates contiguous Text nodes and removes all leading and - * trailing whitespace. - * @param textNode - * @return - */ - private static String catText(Node textNode) { - StringBuffer text = new StringBuffer(); - Node next = textNode; - - do { - if (next.getNodeValue() != null) { - text.append(next.getNodeValue().trim()); - next = next.getNextSibling(); - } - } while (next != null && next.getNodeType() == Node.TEXT_NODE); - - return text.toString(); - } - - /** - * Calculates the number of Nodes that are either not Text nodes - * or are Text nodes whose previous sibling isn't a Text node as - * well. I.e. consecutive Text nodes are counted as a single - * node. - */ - private static int countNodesWithoutConsecutiveTextNodes(NodeList l) { - int count = 0; - boolean lastNodeWasText = false; - final int length = l.getLength(); - for (int i = 0; i < length; i++) { - Node n = l.item(i); - if (!lastNodeWasText || n.getNodeType() != Node.TEXT_NODE) { - count++; - } - lastNodeWasText = n.getNodeType() == Node.TEXT_NODE; - } - return count; - } } Added: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/ElementSelectorsTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/ElementSelectorsTest.java (rev 0) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/ElementSelectorsTest.java 2010-05-05 15:47:17 UTC (rev 379) @@ -0,0 +1,278 @@ +/* + 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 javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.CDATASection; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.Text; + +import static org.junit.Assert.*; + +public class ElementSelectorsTest { + private static final String FOO = "foo"; + private static final String BAR = "bar"; + private static final String SOME_URI = "urn:some:uri"; + + private Document doc; + + @Before public void createDoc() throws Exception { + doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() + .newDocument(); + } + + private void pureElementNameComparisons(ElementSelector s) { + Element control = doc.createElement(FOO); + Element equal = doc.createElement(FOO); + Element different = doc.createElement(BAR); + Element controlNS = doc.createElementNS(SOME_URI, FOO); + controlNS.setPrefix(BAR); + + assertFalse(s.canBeCompared(null, null)); + assertFalse(s.canBeCompared(null, control)); + assertFalse(s.canBeCompared(control, null)); + assertTrue(s.canBeCompared(control, equal)); + assertFalse(s.canBeCompared(control, different)); + assertFalse(s.canBeCompared(control, controlNS)); + assertTrue(s.canBeCompared(doc.createElementNS(SOME_URI, FOO), + controlNS)); + } + + @Test public void byName() { + pureElementNameComparisons(ElementSelectors.byName); + } + + @Test public void byNameAndText_NamePart() { + pureElementNameComparisons(ElementSelectors.byNameAndText); + } + + private void byNameAndText_SingleLevel(ElementSelector s) { + Element control = doc.createElement(FOO); + control.appendChild(doc.createTextNode(BAR)); + Element equal = doc.createElement(FOO); + equal.appendChild(doc.createTextNode(BAR)); + Element equalC = doc.createElement(FOO); + equalC.appendChild(doc.createCDATASection(BAR)); + Element noText = doc.createElement(FOO); + Element differentText = doc.createElement(FOO); + differentText.appendChild(doc.createTextNode(BAR)); + differentText.appendChild(doc.createTextNode(BAR)); + + assertTrue(s.canBeCompared(control, equal)); + assertTrue(s.canBeCompared(control, equalC)); + assertFalse(s.canBeCompared(control, noText)); + assertFalse(s.canBeCompared(control, differentText)); + } + + @Test public void byNameAndText() { + byNameAndText_SingleLevel(ElementSelectors.byNameAndText); + } + + @Test public void byNameAndTextRec_NamePart() { + pureElementNameComparisons(ElementSelectors.byNameAndTextRec); + } + + @Test public void byNameAndTextRec_Single() { + byNameAndText_SingleLevel(ElementSelectors.byNameAndTextRec); + } + + private void byNameAndTextRec() { + Element control = doc.createElement(FOO); + Element child = doc.createElement(BAR); + control.appendChild(child); + child.appendChild(doc.createTextNode(BAR)); + Element equal = doc.createElement(FOO); + Element child2 = doc.createElement(BAR); + equal.appendChild(child2); + child2.appendChild(doc.createTextNode(BAR)); + Element equalC = doc.createElement(FOO); + Element child3 = doc.createElement(BAR); + equalC.appendChild(child3); + child3.appendChild(doc.createCDATASection(BAR)); + Element noText = doc.createElement(FOO); + Element differentLevel = doc.createElement(FOO); + differentLevel.appendChild(doc.createTextNode(BAR)); + Element differentElement = doc.createElement(FOO); + Element child4 = doc.createElement(FOO); + differentElement.appendChild(child4); + child4.appendChild(doc.createTextNode(BAR)); + Element differentText = doc.createElement(FOO); + Element child5 = doc.createElement(BAR); + differentText.appendChild(child5); + child5.appendChild(doc.createTextNode(FOO)); + + ElementSelector s = ElementSelectors.byNameAndTextRec; + assertTrue(s.canBeCompared(control, equal)); + assertTrue(s.canBeCompared(control, equalC)); + assertFalse(s.canBeCompared(control, noText)); + assertFalse(s.canBeCompared(control, differentLevel)); + assertFalse(s.canBeCompared(control, differentElement)); + assertFalse(s.canBeCompared(control, differentText)); + } + + @Test public void byNameAndAllAttributes_NamePart() { + pureElementNameComparisons(ElementSelectors.byNameAndAllAttributes); + } + + @Test public void byNameAndAllAttributes() { + Element control = doc.createElement(FOO); + control.setAttribute(BAR, BAR); + Element equal = doc.createElement(FOO); + equal.setAttribute(BAR, BAR); + Element noAttributes = doc.createElement(FOO); + Element differentValue = doc.createElement(FOO); + differentValue.setAttribute(BAR, FOO); + Element differentName = doc.createElement(FOO); + differentName.setAttribute(FOO, FOO); + Element differentNS = doc.createElement(FOO); + differentNS.setAttributeNS(SOME_URI, BAR, BAR); + + assertTrue(ElementSelectors.byNameAndAllAttributes + .canBeCompared(control, equal)); + assertFalse(ElementSelectors.byNameAndAllAttributes + .canBeCompared(control, noAttributes)); + assertFalse(ElementSelectors.byNameAndAllAttributes + .canBeCompared(noAttributes, control)); + assertFalse(ElementSelectors.byNameAndAllAttributes + .canBeCompared(control, differentValue)); + assertFalse(ElementSelectors.byNameAndAllAttributes + .canBeCompared(control, differentName)); + assertFalse(ElementSelectors.byNameAndAllAttributes + .canBeCompared(control, differentNS)); + } + + @Test public void byNameAndAttributes_NamePart() { + pureElementNameComparisons(ElementSelectors + .byNameAndAttributes(new String[] {})); + pureElementNameComparisons(ElementSelectors + .byNameAndAttributes(new QName[] {})); + pureElementNameComparisons(ElementSelectors.byNameAndAttributes(BAR)); + pureElementNameComparisons(ElementSelectors + .byNameAndAttributes(new QName(SOME_URI, + BAR))); + } + + @Test public void byNameAndAttributes_String() { + Element control = doc.createElement(FOO); + control.setAttribute(BAR, BAR); + Element equal = doc.createElement(FOO); + equal.setAttribute(BAR, BAR); + Element noAttributes = doc.createElement(FOO); + Element differentValue = doc.createElement(FOO); + differentValue.setAttribute(BAR, FOO); + Element differentName = doc.createElement(FOO); + differentName.setAttribute(FOO, FOO); + Element differentNS = doc.createElement(FOO); + differentNS.setAttributeNS(SOME_URI, BAR, BAR); + + assertTrue(ElementSelectors.byNameAndAttributes(BAR) + .canBeCompared(control, equal)); + assertFalse(ElementSelectors.byNameAndAttributes(BAR) + .canBeCompared(control, noAttributes)); + assertTrue(ElementSelectors.byNameAndAttributes(FOO) + .canBeCompared(control, noAttributes)); + assertTrue(ElementSelectors.byNameAndAttributes(new String[] {}) + .canBeCompared(control, noAttributes)); + assertFalse(ElementSelectors.byNameAndAttributes(BAR) + .canBeCompared(noAttributes, control)); + assertFalse(ElementSelectors.byNameAndAttributes(BAR) + .canBeCompared(control, differentValue)); + assertFalse(ElementSelectors.byNameAndAttributes(BAR) + .canBeCompared(control, differentName)); + assertFalse(ElementSelectors.byNameAndAttributes(BAR) + .canBeCompared(control, differentNS)); + } + + @Test public void byNameAndAttributes_QName() { + Element control = doc.createElement(FOO); + control.setAttribute(BAR, BAR); + Element equal = doc.createElement(FOO); + equal.setAttribute(BAR, BAR); + Element noAttributes = doc.createElement(FOO); + Element differentValue = doc.createElement(FOO); + differentValue.setAttribute(BAR, FOO); + Element differentName = doc.createElement(FOO); + differentName.setAttribute(FOO, FOO); + Element differentNS = doc.createElement(FOO); + differentNS.setAttributeNS(SOME_URI, BAR, BAR); + + assertTrue(ElementSelectors.byNameAndAttributes(new QName(BAR)) + .canBeCompared(control, equal)); + assertFalse(ElementSelectors.byNameAndAttributes(new QName(BAR)) + .canBeCompared(control, noAttributes)); + assertTrue(ElementSelectors.byNameAndAttributes(new QName(FOO)) + .canBeCompared(control, noAttributes)); + assertTrue(ElementSelectors.byNameAndAttributes(new QName[] {}) + .canBeCompared(control, noAttributes)); + assertFalse(ElementSelectors.byNameAndAttributes(new QName(BAR)) + .canBeCompared(noAttributes, control)); + assertFalse(ElementSelectors.byNameAndAttributes(new QName(BAR)) + .canBeCompared(control, differentValue)); + assertFalse(ElementSelectors.byNameAndAttributes(new QName(BAR)) + .canBeCompared(control, differentName)); + assertFalse(ElementSelectors.byNameAndAttributes(new QName(BAR)) + .canBeCompared(control, differentNS)); + } + + @Test public void byNameAndAttributesControlNS_NamePart() { + pureElementNameComparisons(ElementSelectors + .byNameAndAttributesControlNS()); + pureElementNameComparisons(ElementSelectors + .byNameAndAttributesControlNS(BAR)); + } + + @Test public void byNameAndAttributesControlNS() { + Element control = doc.createElement(FOO); + control.setAttributeNS(SOME_URI, BAR, BAR); + Element equal = doc.createElement(FOO); + equal.setAttributeNS(SOME_URI, BAR, BAR); + Element noAttributes = doc.createElement(FOO); + Element differentValue = doc.createElement(FOO); + differentValue.setAttributeNS(SOME_URI, BAR, FOO); + Element differentName = doc.createElement(FOO); + differentName.setAttributeNS(SOME_URI, FOO, FOO); + Element differentNS = doc.createElement(FOO); + differentNS.setAttributeNS(SOME_URI + "2", BAR, BAR); + Element noNS = doc.createElement(FOO); + noNS.setAttribute(BAR, BAR); + + assertTrue(ElementSelectors.byNameAndAttributesControlNS(BAR) + .canBeCompared(control, equal)); + assertFalse(ElementSelectors.byNameAndAttributesControlNS(BAR) + .canBeCompared(control, noAttributes)); + assertTrue(ElementSelectors.byNameAndAttributesControlNS(FOO) + .canBeCompared(control, noAttributes)); + assertTrue(ElementSelectors.byNameAndAttributesControlNS(new String[] {}) + .canBeCompared(control, noAttributes)); + assertTrue(ElementSelectors.byNameAndAttributesControlNS(BAR) + .canBeCompared(noAttributes, control)); + assertFalse(ElementSelectors.byNameAndAttributesControlNS(BAR) + .canBeCompared(noAttributes, noNS)); + assertFalse(ElementSelectors.byNameAndAttributesControlNS(BAR) + .canBeCompared(control, differentValue)); + assertFalse(ElementSelectors.byNameAndAttributesControlNS(BAR) + .canBeCompared(control, differentName)); + assertFalse(ElementSelectors.byNameAndAttributesControlNS(BAR) + .canBeCompared(control, differentNS)); + assertFalse(ElementSelectors.byNameAndAttributesControlNS(BAR) + .canBeCompared(control, noNS)); + } + +} Property changes on: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/diff/ElementSelectorsTest.java ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/NodesTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/NodesTest.java (rev 0) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/NodesTest.java 2010-05-05 15:47:17 UTC (rev 379) @@ -0,0 +1,141 @@ +/* + 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.Map; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +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.Node; +import org.w3c.dom.Text; + +import static org.junit.Assert.*; + +public class NodesTest { + + private static final String FOO = "foo"; + private static final String BAR = "bar"; + private static final String SOME_URI = "urn:some:uri"; + + private Document doc; + + @Before public void createDoc() throws Exception { + doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() + .newDocument(); + } + + @Test public void qNameOfElementWithNoNs() { + Element e = doc.createElement(FOO); + QName q = Nodes.getQName(e); + assertEquals(FOO, q.getLocalPart()); + assertEquals(XMLConstants.NULL_NS_URI, q.getNamespaceURI()); + assertEquals(XMLConstants.DEFAULT_NS_PREFIX, q.getPrefix()); + assertEquals(new QName(FOO), q); + } + + @Test public void qNameOfElementWithNsNoPrefix() { + Element e = doc.createElementNS(SOME_URI, FOO); + QName q = Nodes.getQName(e); + assertEquals(FOO, q.getLocalPart()); + assertEquals(SOME_URI, q.getNamespaceURI()); + assertEquals(XMLConstants.DEFAULT_NS_PREFIX, q.getPrefix()); + assertEquals(new QName(SOME_URI, FOO), q); + } + + @Test public void qNameOfElementWithNsAndPrefix() { + Element e = doc.createElementNS(SOME_URI, FOO); + e.setPrefix(BAR); + QName q = Nodes.getQName(e); + assertEquals(FOO, q.getLocalPart()); + assertEquals(SOME_URI, q.getNamespaceURI()); + assertEquals(BAR, q.getPrefix()); + assertEquals(new QName(SOME_URI, FOO), q); + assertEquals(new QName(SOME_URI, FOO, BAR), q); + } + + @Test public void mergeNoTexts() { + Element e = doc.createElement(FOO); + assertEquals("", Nodes.getMergedNestedText(e)); + } + + @Test public void mergeSingleTextNode() { + Element e = doc.createElement(FOO); + Text t = doc.createTextNode(BAR); + e.appendChild(t); + assertEquals(BAR, Nodes.getMergedNestedText(e)); + } + + @Test public void mergeSingleCDATASection() { + Element e = doc.createElement(FOO); + CDATASection t = doc.createCDATASection(BAR); + e.appendChild(t); + assertEquals(BAR, Nodes.getMergedNestedText(e)); + } + + @Test public void mergeIgnoresTextOfChildren() { + Element e = doc.createElement(FOO); + Element c = doc.createElement("child"); + Text t = doc.createTextNode(BAR); + e.appendChild(c); + c.appendChild(t); + assertEquals("", Nodes.getMergedNestedText(e)); + } + + @Test public void mergeIgnoresComments() { + Element e = doc.createElement(FOO); + Comment c = doc.createComment(BAR); + e.appendChild(c); + assertEquals("", Nodes.getMergedNestedText(e)); + } + + @Test public void mergeMultipleChildren() { + Element e = doc.createElement(FOO); + CDATASection c = doc.createCDATASection(BAR); + e.appendChild(c); + e.appendChild(doc.createElement("child")); + Text t = doc.createTextNode(BAR); + e.appendChild(t); + assertEquals(BAR + BAR, Nodes.getMergedNestedText(e)); + } + + @Test public void attributeMapNoAttributes() { + Element e = doc.createElement(FOO); + Map<QName, String> m = Nodes.getAttributes(e); + assertEquals(0, m.size()); + } + + @Test public void attributeMapNoNS() { + Element e = doc.createElement(FOO); + e.setAttribute(FOO, BAR); + Map<QName, String> m = Nodes.getAttributes(e); + assertEquals(1, m.size()); + assertEquals(BAR, m.get(new QName(FOO))); + } + + @Test public void attributeMapwithNS() { + Element e = doc.createElement(FOO); + e.setAttributeNS(SOME_URI, FOO, BAR); + Map<QName, String> m = Nodes.getAttributes(e); + assertEquals(1, m.size()); + assertEquals(BAR, m.get(new QName(SOME_URI, FOO))); + assertEquals(BAR, m.get(new QName(SOME_URI, FOO, BAR))); + } +} Property changes on: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/NodesTest.java ___________________________________________________________________ Added: svn:eol-style + native Modified: trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_ElementNameAndAttributeQualifier.java =================================================================== --- trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_ElementNameAndAttributeQualifier.java 2010-05-03 16:08:17 UTC (rev 378) +++ trunk/xmlunit/src/tests/java-legacy/org/custommonkey/xmlunit/test_ElementNameAndAttributeQualifier.java 2010-05-05 15:47:17 UTC (rev 379) @@ -142,13 +142,15 @@ final String nsURI = "http://xmlunit.sourceforge.net/tests"; elementNameAndAttributeQualifier = new ElementNameAndAttributeQualifier(); - testAssertionsFor(attrName, nsURI, new boolean[] {false, false}); + testAssertionsFor(attrName, nsURI, new boolean[] {false, false}, true); elementNameAndAttributeQualifier = new ElementNameAndAttributeQualifier(attrName); - testAssertionsFor(attrName, nsURI, new boolean[] {true, true}); + testAssertionsFor(attrName, nsURI, new boolean[] {true, true}, false); } - private void testAssertionsFor(String attrName, String nsURI, boolean[] expectedValues) + private void testAssertionsFor(String attrName, String nsURI, + boolean[] expectedValues, + boolean matchesAllAttributes) throws Exception { Element control = document.createElement(TAG_NAME); control.setAttributeNS(nsURI, attrName, "1"); @@ -161,10 +163,12 @@ assertTrue("qwerty id 1 comparable to qwerty id 1", elementNameAndAttributeQualifier.qualifyForComparison(control, test)); - String otherNsURI = nsURI + "/2"; - test.setAttributeNS(otherNsURI, attrName, "2"); - assertTrue("qwerty id 1 comparable to qwerty id 1 and other-NS id 2", - elementNameAndAttributeQualifier.qualifyForComparison(control, test)); + if (!matchesAllAttributes) { + String otherNsURI = nsURI + "/2"; + test.setAttributeNS(otherNsURI, attrName, "2"); + assertTrue("qwerty id 1 comparable to qwerty id 1 and other-NS id 2", + elementNameAndAttributeQualifier.qualifyForComparison(control, test)); + } control.setAttributeNS(nsURI, "uiop","true"); assertEquals("qwerty id 1 && uiop comparable to qwerty id 1", expectedValues[0], This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-05-03 16:08:25
|
Revision: 378 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=378&view=rev Author: bodewig Date: 2010-05-03 16:08:17 +0000 (Mon, 03 May 2010) Log Message: ----------- preliminary interfaces for difference engine Added Paths: ----------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/Comparison.java trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonListener.java trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonResult.java trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonType.java trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluator.java trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ElementSelector.java trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/IDifferenceEngine.java trunk/xmlunit/src/main/net-core/diff/ trunk/xmlunit/src/main/net-core/diff/Comparison.cs trunk/xmlunit/src/main/net-core/diff/ComparisonListener.cs trunk/xmlunit/src/main/net-core/diff/ComparisonResult.cs trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluator.cs trunk/xmlunit/src/main/net-core/diff/ElementSelector.cs trunk/xmlunit/src/main/net-core/diff/IDifferenceEngine.cs Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/Comparison.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/Comparison.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/Comparison.java 2010-05-03 16:08:17 UTC (rev 378) @@ -0,0 +1,83 @@ +/* + 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.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. + */ + public static class Detail { + private final Node node; + private final String xpath; + private final Object value; + + private Detail(Node n, String x, Object v) { + node = n; + xpath = x; + value = v; + } + + /** + * The actual Node. + */ + public Node getNode() { return node; } + /** + * XPath leading to the Node. + */ + public String getXPath() { return xpath; } + /** + * The value for comparision found at the current node. + */ + public Object getValue() { return value; } + } + + private final Detail control, test; + private final ComparisonType type; + + public Comparison(ComparisonType t, Node controlNode, + String controlXPath, Object controlValue, + Node testNode, String testXPath, Object testValue) { + type = t; + control = new Detail(controlNode, controlXPath, controlValue); + test = new Detail(testNode, testXPath, testValue); + } + + /** + * The kind of comparision performed. + */ + public ComparisonType getType() { + return type; + } + + /** + * Details of the control node. + */ + public Detail getControlNodeDetails() { + return control; + } + + /** + * Details of the test node. + */ + public Detail getTestNodeDetails() { + return test; + } + +} Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/Comparison.java ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonListener.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonListener.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonListener.java 2010-05-03 16:08:17 UTC (rev 378) @@ -0,0 +1,21 @@ +/* + 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; + +/** + * Is notified of comparisions and their results. + */ +public interface ComparisonListener { + void comparisonPerformed(Comparison comparison, ComparisonResult outcome); +} Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonListener.java ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonResult.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonResult.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonResult.java 2010-05-03 16:08:17 UTC (rev 378) @@ -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. +*/ +package net.sf.xmlunit.diff; + +/** + * The possible outcomes of a comparision. + */ +public enum ComparisonResult { + /** + * The two nodes are the same for the sake of this comparison. + */ + EQUAL, + /** + * The two nodes are different but similar enough to satisfy a + * weak equality constraint + */ + SIMILAR, + /** + * The two nodes are different. + */ + DIFFERENT, + /** + * The two nodes are different and comparison should stop + * immediately. + * + * <p>Only used as a return type by {@link DifferenceEvaluator} + */ + CRITICAL, +} Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonResult.java ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonType.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonType.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonType.java 2010-05-03 16:08:17 UTC (rev 378) @@ -0,0 +1,120 @@ +/* + 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; + +/** + * The kinds of comparisons XMLUnit performs. + */ +public enum ComparisonType { + /** + * Do both documents have a DOCTYPE (or neither of each)? + */ + HAS_DOCTYPE_DECLARATION, + /** + * If the documents both have DOCTYPEs, compare the names. + */ + DOCTYPE_NAME, + /** + * If the documents both have DOCTYPEs, compare the PUBLIC + * identifiers. + */ + DOCTYPE_PUBLIC, + /** + * If the documents both have DOCTYPEs, compare the SYSTEM + * identifiers. + */ + DOCTYPE_SYSTEM, + + /** + * Check whether both documents provide the same values for + * xsi:schemaLocation (may even be null). + */ + SCHEMA_LOCATION, + /** + * Check whether both documents provide the same values for + * xsi:noNamspaceSchemaLocation (may even be null). + */ + NO_NAMESPACE_SCHEMA_LOCATION, + + /** + * Compare the node types. + */ + NODE_TYPE, + + /** + * Compare the node's namespace prefixes. + */ + NAMESPACE_PREFIX, + /** + * Compare the node's namespace URIs. + */ + NAMESPACE_URI, + + /** + * Compare content of CDATA sections. + */ + CDATA_VALUE, + /** + * Compare content of comments. + */ + COMMENT_VALUE, + /** + * Compare content of text nodes. + */ + TEXT_VALUE, + /** + * Compare targets of processing instructions. + */ + PROCESSING_INSTRUCTION_TARGET, + /** + * Compare data of processing instructions. + */ + PROCESSING_INSTRUCTION_DATA, + + /** + * Compare element names. + */ + ELEMENT_TAG_NAME, + /** + * Compare explicit/implicit status of attributes. + */ + ATTR_VALUE_EXPLICITLY_SPECIFIED, + /** + * Compare number of attributes. + */ + ELEMENT_NUM_ATTRIBUTES, + /** + * Compare attribute's value. + */ + ATTR_VALUE, + /** + * Compare number of child nodes. + */ + CHILD_NODELIST_LENGTH, + /** + * Compare order of child nodes. + */ + CHILD_NODELIST_SEQUENCE, + + /** + * Search for a child node matching a specific child node of the + * other node. + */ + CHILD_LOOKUP, + /** + * Search for an atribute with a name matching a specific + * attribute of the other node. + */ + ATTR_NAME_LOOKUP, +} Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ComparisonType.java ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluator.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluator.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluator.java 2010-05-03 16:08:17 UTC (rev 378) @@ -0,0 +1,28 @@ +/* + 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; + +/** + * May decide to up- or downgrade the severity of a difference and + * even to stop the comparison completely. + */ +public interface DifferenceEvaluator { + /** + * May alter the outcome of a comparison. + * + * @return the new result of the comparison, should return {@link + * ComaprisonResult#CRITICAL} to stop the comparison completely. + */ + ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome); +} Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/DifferenceEvaluator.java ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ElementSelector.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ElementSelector.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ElementSelector.java 2010-05-03 16:08:17 UTC (rev 378) @@ -0,0 +1,27 @@ +/* + 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.w3c.dom.Element; + +/** + * Strategy for selecting matching elements. + */ +public interface ElementSelector { + /** + * Determine whether the two elements from the control and test + * XML can be compared. + */ + boolean canBeCompared(Element controlElement, Element testElement); +} Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/ElementSelector.java ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/IDifferenceEngine.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/IDifferenceEngine.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/IDifferenceEngine.java 2010-05-03 16:08:17 UTC (rev 378) @@ -0,0 +1,54 @@ +/* + 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 javax.xml.transform.Source; + +/** + * XMLUnit's difference engine. + */ +public interface IDifferenceEngine { + /** + * Registers a listener that is notified of each comparison. + */ + void addComparisonListener(ComparisonListener l); + + /** + * Registers a listener that is notified of each comparison with + * outcome {@link ComparisonResult#EQUAL}. + */ + void addMatchListener(ComparisonListener l); + + /** + * Registers a listener that is notified of each comparison with + * outcome other than {@link ComparisonResult#EQUAL}. + */ + void addDifferenceListener(ComparisonListener l); + + /** + * Sets the strategy for selecting elements to compare. + */ + void setElementSelector(ElementSelector s); + + /** + * Determines whether the comparison should stop after given + * difference has been found. + */ + void setDifferenceEvaluator(DifferenceEvaluator e); + + /** + * Compares two pieces of XML and invokes the registered listeners. + */ + void compare(Source control, Source test); +} Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/diff/IDifferenceEngine.java ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/net-core/diff/Comparison.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/Comparison.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/diff/Comparison.cs 2010-05-03 16:08:17 UTC (rev 378) @@ -0,0 +1,92 @@ +/* + 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.Xml; + +namespace net.sf.xmlunit.diff { + + /// <summary> + /// Details of a single comparison XMLUnit has performed. + /// </summary> + public class Comparison { + + /// <summary> + /// The details of a Node that took part in the comparision. + /// </summary> + public sealed class Detail { + private readonly XmlNode node; + private readonly string xpath; + private readonly object value; + + internal Detail(XmlNode n, string x, object v) { + node = n; + xpath = x; + value = v; + } + + /// <summary> + /// The actual Node. + /// </summary> + public XmlNode Node { get { return node; } } + /// <summary> + /// XPath leading to the Node. + /// </summary> + public string XPath { get { return xpath; } } + /// <summary> + /// The value for comparision found at the current node. + /// </summary> + public object Value { get { return value; } } + } + + private readonly Detail control, test; + private readonly ComparisonType type; + + public Comparison(ComparisonType t, XmlNode controlNode, + string controlXPath, object controlValue, + XmlNode testNode, string testXPath, + object testValue) { + type = t; + control = new Detail(controlNode, controlXPath, controlValue); + test = new Detail(testNode, testXPath, testValue); + } + + /// <summary> + /// The kind of comparision performed. + /// </summary> + public ComparisonType Type { + get { + return type; + } + } + + /// <summary> + /// Details of the control node. + /// </summary> + public Detail ControlNodeDetails { + get { + return control; + } + } + + /// <summary> + /// Details of the test node. + /// </summary> + public Detail TestNodeDetails { + get { + return test; + } + } + + } +} Property changes on: trunk/xmlunit/src/main/net-core/diff/Comparison.cs ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/net-core/diff/ComparisonListener.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/ComparisonListener.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/diff/ComparisonListener.cs 2010-05-03 16:08:17 UTC (rev 378) @@ -0,0 +1,21 @@ +/* + 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. +*/ + +namespace net.sf.xmlunit.diff { + /// <summary> + /// Is notified of comparisions and their results. + /// </summary> + public delegate void ComparisonListener(Comparison comparison, + ComparisonResult outcome); +} Property changes on: trunk/xmlunit/src/main/net-core/diff/ComparisonListener.cs ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/net-core/diff/ComparisonResult.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/ComparisonResult.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/diff/ComparisonResult.cs 2010-05-03 16:08:17 UTC (rev 378) @@ -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. +*/ + +namespace net.sf.xmlunit.diff { + + /// <summary> + /// The possible outcomes of a comparision. + /// </summary> + public enum ComparisonResult { + /// <summary> + /// The two nodes are the same for the sake of this comparison. + /// </summary> + EQUAL, + /// <summary> + /// The two nodes are different but similar enough to satisfy a + /// weak equality constraint + /// </summary> + SIMILAR, + /// <summary> + /// The two nodes are different. + /// </summary> + DIFFERENT, + /// <summary> + /// The two nodes are different and comparison should stop + /// immediately. + /// </summary> + /// <remarks>Only used as a return type by {@link DifferenceEvaluator}</remarks> + CRITICAL, + } +} Property changes on: trunk/xmlunit/src/main/net-core/diff/ComparisonResult.cs ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs 2010-05-03 16:08:17 UTC (rev 378) @@ -0,0 +1,122 @@ +/* + 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. +*/ + +namespace net.sf.xmlunit.diff { + + /// <summary> + /// The kinds of comparisons XMLUnit performs. + /// </summary> + public enum ComparisonType { + /// <summary> + /// Do both documents have a DOCTYPE (or neither of each)? + /// </summary> + HAS_DOCTYPE_DECLARATION, + /// <summary> + /// If the documents both have DOCTYPEs, compare the names. + /// </summary> + DOCTYPE_NAME, + /// <summary> + /// If the documents both have DOCTYPEs, compare the PUBLIC + /// identifiers. + /// </summary> + DOCTYPE_PUBLIC, + /// <summary> + /// If the documents both have DOCTYPEs, compare the SYSTEM + /// identifiers. + /// </summary> + DOCTYPE_SYSTEM, + + /// <summary> + /// Check whether both documents provide the same values for + /// xsi:schemaLocation (may even be null). + /// </summary> + SCHEMA_LOCATION, + /// <summary> + /// Check whether both documents provide the same values for + /// xsi:noNamspaceSchemaLocation (may even be null). + /// </summary> + NO_NAMESPACE_SCHEMA_LOCATION, + + /// <summary> + /// Compare the node types. + /// </summary> + NODE_TYPE, + + /// <summary> + /// Compare the node's namespace prefixes. + /// </summary> + NAMESPACE_PREFIX, + /// <summary> + /// Compare the node's namespace URIs. + /// </summary> + NAMESPACE_URI, + + /// <summary> + /// Compare content of 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> + PROCESSING_INSTRUCTION_TARGET, + /// <summary> + /// Compare data of processing instructions. + /// </summary> + PROCESSING_INSTRUCTION_DATA, + + /// <summary> + /// Compare element names. + /// </summary> + ELEMENT_TAG_NAME, + /// <summary> + /// Compare explicit/implicit status of attributes. + /// </summary> + ATTR_VALUE_EXPLICITLY_SPECIFIED, + /// <summary> + /// Compare number of attributes. + /// </summary> + ELEMENT_NUM_ATTRIBUTES, + /// <summary> + /// Compare attribute's value. + /// </summary> + ATTR_VALUE, + /// <summary> + /// Compare number of child nodes. + /// </summary> + CHILD_NODELIST_LENGTH, + /// <summary> + /// Compare order of child nodes. + /// </summary> + CHILD_NODELIST_SEQUENCE, + + /// <summary> + /// Search for a child node matching a specific child node of the + /// other node. + /// </summary> + CHILD_LOOKUP, + /// <summary> + /// Search for an atribute with a name matching a specific + /// attribute of the other node. + /// </summary> + ATTR_NAME_LOOKUP, + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/main/net-core/diff/ComparisonType.cs ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluator.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluator.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluator.cs 2010-05-03 16:08:17 UTC (rev 378) @@ -0,0 +1,25 @@ +/* + 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. +*/ + +namespace net.sf.xmlunit.diff { + + /// <summary> + /// May alter the outcome of a comparison. + /// </summary> + /// <return>the new result of the comparison, should return {@link + /// ComaprisonResult#CRITICAL} to stop the comparison + /// completely.</return> + public delegate ComparisonResult DifferenceEvaluator(Comparison comparison, + ComparisonResult outcome); +} Property changes on: trunk/xmlunit/src/main/net-core/diff/DifferenceEvaluator.cs ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/net-core/diff/ElementSelector.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/ElementSelector.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/diff/ElementSelector.cs 2010-05-03 16:08:17 UTC (rev 378) @@ -0,0 +1,24 @@ +/* + 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.Xml; + +namespace net.sf.xmlunit.diff { + + /// <summary> + /// Strategy for selecting matching elements. + /// </summary> + public delegate bool ElementSelector(XmlElement controlElement, + XmlElement testElement); +} Property changes on: trunk/xmlunit/src/main/net-core/diff/ElementSelector.cs ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/net-core/diff/IDifferenceEngine.cs =================================================================== --- trunk/xmlunit/src/main/net-core/diff/IDifferenceEngine.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/diff/IDifferenceEngine.cs 2010-05-03 16:08:17 UTC (rev 378) @@ -0,0 +1,54 @@ +/* + 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. +*/ + +namespace net.sf.xmlunit.diff { + + /// <summary> + /// XMLUnit's difference engine. + /// </summary> + public interface IDifferenceEngine { + /// <summary> + /// Is notified of each comparison. + /// </summary> + event ComparisonListener ComparisonListener; + + /// <summary> + /// Is notified of each comparison with outcome {@link + /// ComparisonResult#EQUAL}. + /// </summary> + event ComparisonListener MatchListener; + + /// <summary> + /// Is notified of each comparison with + /// outcome other than {@link ComparisonResult#EQUAL}. + /// </summary> + event ComparisonListener DifferenceListener; + + /// <summary> + /// Sets the strategy for selecting elements to compare. + /// </summary> + ElementSelector ElementSelector { set; } + + /// <summary> + /// Determines whether the comparison should stop after given + /// difference has been found. + /// </summary> + DifferenceEvaluator DifferenceEvaluator { set; } + + /// <summary> + /// Compares two pieces of XML and invokes the registered listeners. + /// </summary> + void Compare(ISource control, ISource test); + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/main/net-core/diff/IDifferenceEngine.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-05-03 10:28:31
|
Revision: 377 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=377&view=rev Author: bodewig Date: 2010-05-03 10:28:25 +0000 (Mon, 03 May 2010) Log Message: ----------- make tests reusable in case there will ever be different implementations Modified Paths: -------------- trunk/xmlunit/build.xml trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/JAXPXPathEngineTest.java trunk/xmlunit/src/tests/net-core/xpath/XPathEngineTest.cs Added Paths: ----------- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/AbstractXPathEngineTest.java trunk/xmlunit/src/tests/net-core/xpath/AbstractXPathEngineTest.cs Modified: trunk/xmlunit/build.xml =================================================================== --- trunk/xmlunit/build.xml 2010-05-03 10:26:23 UTC (rev 376) +++ trunk/xmlunit/build.xml 2010-05-03 10:28:25 UTC (rev 377) @@ -157,6 +157,7 @@ </fileset> <fileset dir="${test.dir}/java-core"> <include name="**/*Test.java"/> + <exclude name="**/Abstract*.java"/> </fileset> </batchtest> </junit> Copied: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/AbstractXPathEngineTest.java (from rev 374, trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/JAXPXPathEngineTest.java) =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/AbstractXPathEngineTest.java (rev 0) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/AbstractXPathEngineTest.java 2010-05-03 10:28:25 UTC (rev 377) @@ -0,0 +1,137 @@ +/* + 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.xpath; + +import java.util.HashMap; +import java.util.Iterator; +import javax.xml.transform.Source; +import net.sf.xmlunit.TestResources; +import net.sf.xmlunit.builder.Input; +import net.sf.xmlunit.exceptions.XMLUnitException; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.Node; + +import static org.junit.Assert.*; + +public abstract class AbstractXPathEngineTest { + + protected abstract IXPathEngine getEngine(); + + private Source source; + + @Before public void readSource() throws Exception { + source = Input.fromFile(TestResources.BLAME_FILE).build(); + } + + @Test public void selectNodesWithNoMatches() { + Iterable<Node> i = getEngine().selectNodes("foo", source); + assertNotNull(i); + assertFalse(i.iterator().hasNext()); + } + + @Test public void selectNodesWithSingleMatch() { + Iterable<Node> i = getEngine().selectNodes("//ul", source); + assertNotNull(i); + Iterator<Node> it = i.iterator(); + assertTrue(it.hasNext()); + assertEquals("ul", it.next().getNodeName()); + assertFalse(it.hasNext()); + } + + @Test public void selectNodesWithMultipleMatchs() { + Iterable<Node> i = getEngine().selectNodes("//li", source); + assertNotNull(i); + int count = 0; + for (Iterator<Node> it = i.iterator(); it.hasNext(); ) { + count++; + assertEquals("li", it.next().getNodeName()); + } + assertEquals(4, count); + } + + @Test(expected=XMLUnitException.class) + public void selectNodesWithInvalidXPath() { + getEngine().selectNodes("//li[", source); + } + + @Test public void evaluateWithNoMatches() { + assertEquals("", getEngine().evaluate("foo", source)); + } + + @Test public void evaluateWithSingleMatch() { + assertEquals("Don't blame it on the...", + getEngine().evaluate("//title", source)); + } + + @Test public void evaluateWithSingleMatchTextSelector() { + assertEquals("Don't blame it on the...", + getEngine().evaluate("//title/text()", source)); + } + + @Test public void evaluateWithMultipleMatches() { + assertEquals("sunshine", + getEngine().evaluate("//li", source)); + } + + @Test(expected=XMLUnitException.class) + public void evaluateWithInvalidXPath() { + getEngine().evaluate("//li[", source); + } + + @Test public void selectNodesWithNS() { + IXPathEngine e = getEngine(); + source = Input.fromMemory("<n:d xmlns:n='urn:test:1'><n:e/></n:d>") + .build(); + HashMap<String, String> m = new HashMap<String, String>(); + m.put("x", "urn:test:1"); + e.setNamespaceContext(m); + Iterable<Node> it = e.selectNodes("/x:d/x:e", source); + assertTrue(it.iterator().hasNext()); + } + + @Test public void selectNodesWithDefaultNS() { + IXPathEngine e = getEngine(); + source = Input.fromMemory("<d xmlns='urn:test:1'><e/></d>") + .build(); + HashMap<String, String> m = new HashMap<String, String>(); + m.put("x", "urn:test:1"); + e.setNamespaceContext(m); + Iterable<Node> it = e.selectNodes("/x:d/x:e", source); + assertTrue(it.iterator().hasNext()); + } + + @Test public void selectNodesWithDefaultNSEmptyPrefix() { + IXPathEngine e = getEngine(); + source = Input.fromMemory("<d xmlns='urn:test:1'><e/></d>") + .build(); + HashMap<String, String> m = new HashMap<String, String>(); + m.put("", "urn:test:1"); + e.setNamespaceContext(m); + Iterable<Node> it = e.selectNodes("/:d/:e", source); + assertTrue(it.iterator().hasNext()); + } + + // doesn't match + public void selectNodesWithDefaultNSNoPrefix() { + IXPathEngine e = getEngine(); + source = Input.fromMemory("<d xmlns='urn:test:1'><e/></d>") + .build(); + HashMap<String, String> m = new HashMap<String, String>(); + m.put("", "urn:test:1"); + e.setNamespaceContext(m); + Iterable<Node> it = e.selectNodes("/d/e", source); + assertTrue(it.iterator().hasNext()); + } +} Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/JAXPXPathEngineTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/JAXPXPathEngineTest.java 2010-05-03 10:26:23 UTC (rev 376) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/JAXPXPathEngineTest.java 2010-05-03 10:28:25 UTC (rev 377) @@ -13,123 +13,8 @@ */ package net.sf.xmlunit.xpath; -import java.util.HashMap; -import java.util.Iterator; -import javax.xml.transform.Source; -import net.sf.xmlunit.TestResources; -import net.sf.xmlunit.builder.Input; -import net.sf.xmlunit.exceptions.XMLUnitException; -import org.junit.Before; -import org.junit.Test; -import org.w3c.dom.Node; - -import static org.junit.Assert.*; - -public class JAXPXPathEngineTest { - - private Source source; - - @Before public void readSource() throws Exception { - source = Input.fromFile(TestResources.BLAME_FILE).build(); +public class JAXPXPathEngineTest extends AbstractXPathEngineTest { + @Override protected IXPathEngine getEngine() { + return new JAXPXPathEngine(); } - - @Test public void selectNodesWithNoMatches() { - Iterable<Node> i = new JAXPXPathEngine().selectNodes("foo", source); - assertNotNull(i); - assertFalse(i.iterator().hasNext()); - } - - @Test public void selectNodesWithSingleMatch() { - Iterable<Node> i = new JAXPXPathEngine().selectNodes("//ul", source); - assertNotNull(i); - Iterator<Node> it = i.iterator(); - assertTrue(it.hasNext()); - assertEquals("ul", it.next().getNodeName()); - assertFalse(it.hasNext()); - } - - @Test public void selectNodesWithMultipleMatchs() { - Iterable<Node> i = new JAXPXPathEngine().selectNodes("//li", source); - assertNotNull(i); - int count = 0; - for (Iterator<Node> it = i.iterator(); it.hasNext(); ) { - count++; - assertEquals("li", it.next().getNodeName()); - } - assertEquals(4, count); - } - - @Test(expected=XMLUnitException.class) - public void selectNodesWithInvalidXPath() { - new JAXPXPathEngine().selectNodes("//li[", source); - } - - @Test public void evaluateWithNoMatches() { - assertEquals("", new JAXPXPathEngine().evaluate("foo", source)); - } - - @Test public void evaluateWithSingleMatch() { - assertEquals("Don't blame it on the...", - new JAXPXPathEngine().evaluate("//title", source)); - } - - @Test public void evaluateWithSingleMatchTextSelector() { - assertEquals("Don't blame it on the...", - new JAXPXPathEngine().evaluate("//title/text()", source)); - } - - @Test public void evaluateWithMultipleMatches() { - assertEquals("sunshine", - new JAXPXPathEngine().evaluate("//li", source)); - } - - @Test(expected=XMLUnitException.class) - public void evaluateWithInvalidXPath() { - new JAXPXPathEngine().evaluate("//li[", source); - } - - @Test public void selectNodesWithNS() { - JAXPXPathEngine e = new JAXPXPathEngine(); - source = Input.fromMemory("<n:d xmlns:n='urn:test:1'><n:e/></n:d>") - .build(); - HashMap<String, String> m = new HashMap<String, String>(); - m.put("x", "urn:test:1"); - e.setNamespaceContext(m); - Iterable<Node> it = e.selectNodes("/x:d/x:e", source); - assertTrue(it.iterator().hasNext()); - } - - @Test public void selectNodesWithDefaultNS() { - JAXPXPathEngine e = new JAXPXPathEngine(); - source = Input.fromMemory("<d xmlns='urn:test:1'><e/></d>") - .build(); - HashMap<String, String> m = new HashMap<String, String>(); - m.put("x", "urn:test:1"); - e.setNamespaceContext(m); - Iterable<Node> it = e.selectNodes("/x:d/x:e", source); - assertTrue(it.iterator().hasNext()); - } - - @Test public void selectNodesWithDefaultNSEmptyPrefix() { - JAXPXPathEngine e = new JAXPXPathEngine(); - source = Input.fromMemory("<d xmlns='urn:test:1'><e/></d>") - .build(); - HashMap<String, String> m = new HashMap<String, String>(); - m.put("", "urn:test:1"); - e.setNamespaceContext(m); - Iterable<Node> it = e.selectNodes("/:d/:e", source); - assertTrue(it.iterator().hasNext()); - } - - // doesn't match - public void selectNodesWithDefaultNSNoPrefix() { - JAXPXPathEngine e = new JAXPXPathEngine(); - source = Input.fromMemory("<d xmlns='urn:test:1'><e/></d>") - .build(); - HashMap<String, String> m = new HashMap<String, String>(); - m.put("", "urn:test:1"); - e.setNamespaceContext(m); - Iterable<Node> it = e.selectNodes("/d/e", source); - assertTrue(it.iterator().hasNext()); - } } Copied: trunk/xmlunit/src/tests/net-core/xpath/AbstractXPathEngineTest.cs (from rev 375, trunk/xmlunit/src/tests/net-core/xpath/XPathEngineTest.cs) =================================================================== --- trunk/xmlunit/src/tests/net-core/xpath/AbstractXPathEngineTest.cs (rev 0) +++ trunk/xmlunit/src/tests/net-core/xpath/AbstractXPathEngineTest.cs 2010-05-03 10:28:25 UTC (rev 377) @@ -0,0 +1,145 @@ +/* + 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.Generic; +using System.Xml; +using NUnit.Framework; +using net.sf.xmlunit.builder; +using net.sf.xmlunit.exceptions; + +namespace net.sf.xmlunit.xpath { + + public abstract class AbstractXPathEngineTest { + + private ISource source; + + protected abstract IXPathEngine Engine { get; } + + [SetUp] public void ReadSource() { + source = Input.FromFile(TestResources.BLAME_FILE).Build(); + } + + [Test] public void SelectNodesWithNoMatches() { + IEnumerable<XmlNode> i = Engine.SelectNodes("foo", + source); + Assert.IsNotNull(i); + Assert.IsFalse(i.GetEnumerator().MoveNext()); + } + + [Test] public void SelectNodesWithSingleMatch() { + IEnumerable<XmlNode> i = Engine.SelectNodes("//ul", source); + Assert.IsNotNull(i); + IEnumerator<XmlNode> it = i.GetEnumerator(); + Assert.IsTrue(it.MoveNext()); + Assert.AreEqual("ul", it.Current.Name); + Assert.IsFalse(it.MoveNext()); + } + + [Test] public void SelectNodesWithMultipleMatchs() { + IEnumerable<XmlNode> i = Engine.SelectNodes("//li", source); + Assert.IsNotNull(i); + int count = 0; + foreach (XmlNode n in i) { + count++; + Assert.AreEqual("li", n.Name); + } + Assert.AreEqual(4, count); + } + + [Test] + public void SelectNodesWithInvalidXPath() { + try { + Engine.SelectNodes("//li[", source); + Assert.Fail("expected an exception"); + } catch (XMLUnitException) { + // expected + } + } + + [Test] public void EvaluateWithNoMatches() { + Assert.AreEqual(string.Empty, Engine.Evaluate("foo", source)); + } + + [Test] public void EvaluateWithSingleMatch() { + Assert.AreEqual("Don't blame it on the...", + Engine.Evaluate("//title", source)); + } + + [Test] public void EvaluateWithSingleMatchTextSelector() { + Assert.AreEqual("Don't blame it on the...", + Engine.Evaluate("//title/text()", source)); + } + + [Test] public void EvaluateWithMultipleMatches() { + Assert.AreEqual("sunshine", + Engine.Evaluate("//li", source)); + } + + [Test] + public void EvaluateWithInvalidXPath() { + try { + Engine.Evaluate("//li[", source); + Assert.Fail("expected an exception"); + } catch (XMLUnitException) { + // expected + } + } + + [Test] public void SelectNodesWithNS() { + IXPathEngine e = Engine; + source = Input.FromMemory("<n:d xmlns:n='urn:test:1'><n:e/></n:d>") + .Build(); + Dictionary<string, string> m = new Dictionary<string, string>(); + m["x"] = "urn:test:1"; + e.NamespaceContext = m; + IEnumerable<XmlNode> it = e.SelectNodes("/x:d/x:e", source); + Assert.IsTrue(it.GetEnumerator().MoveNext()); + } + + [Test] public void SelectNodesWithDefaultNS() { + IXPathEngine e = Engine; + source = Input.FromMemory("<d xmlns='urn:test:1'><e/></d>") + .Build(); + Dictionary<string, string> m = new Dictionary<string, string>(); + m["x"] = "urn:test:1"; + e.NamespaceContext = m; + IEnumerable<XmlNode> it = e.SelectNodes("/x:d/x:e", source); + Assert.IsTrue(it.GetEnumerator().MoveNext()); + } + + // throws an exception "'/:d/:e' has an invalid token." + public void SelectNodesWithDefaultNSEmptyPrefix() { + IXPathEngine e = Engine; + source = Input.FromMemory("<d xmlns='urn:test:1'><e/></d>") + .Build(); + Dictionary<string, string> m = new Dictionary<string, string>(); + m[string.Empty] = "urn:test:1"; + e.NamespaceContext = m; + IEnumerable<XmlNode> it = e.SelectNodes("/:d/:e", source); + Assert.IsTrue(it.GetEnumerator().MoveNext()); + } + + // doesn't match + public void SelectNodesWithDefaultNSNoPrefix() { + IXPathEngine e = Engine; + source = Input.FromMemory("<d xmlns='urn:test:1'><e/></d>") + .Build(); + Dictionary<string, string> m = new Dictionary<string, string>(); + m[string.Empty] = "urn:test:1"; + e.NamespaceContext = m; + IEnumerable<XmlNode> it = e.SelectNodes("/d/e", source); + Assert.IsTrue(it.GetEnumerator().MoveNext()); + } + } +} Modified: trunk/xmlunit/src/tests/net-core/xpath/XPathEngineTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/xpath/XPathEngineTest.cs 2010-05-03 10:26:23 UTC (rev 376) +++ trunk/xmlunit/src/tests/net-core/xpath/XPathEngineTest.cs 2010-05-03 10:28:25 UTC (rev 377) @@ -12,137 +12,16 @@ limitations under the License. */ -using System.Collections.Generic; -using System.Xml; using NUnit.Framework; -using net.sf.xmlunit.builder; -using net.sf.xmlunit.exceptions; namespace net.sf.xmlunit.xpath { [TestFixture] - public class XPathEngineTest { - - private ISource source; - - [SetUp] public void ReadSource() { - source = Input.FromFile(TestResources.BLAME_FILE).Build(); - } - - [Test] public void SelectNodesWithNoMatches() { - IEnumerable<XmlNode> i = new XPathEngine().SelectNodes("foo", - source); - Assert.IsNotNull(i); - Assert.IsFalse(i.GetEnumerator().MoveNext()); - } - - [Test] public void SelectNodesWithSingleMatch() { - IEnumerable<XmlNode> i = new XPathEngine().SelectNodes("//ul", - source); - Assert.IsNotNull(i); - IEnumerator<XmlNode> it = i.GetEnumerator(); - Assert.IsTrue(it.MoveNext()); - Assert.AreEqual("ul", it.Current.Name); - Assert.IsFalse(it.MoveNext()); - } - - [Test] public void SelectNodesWithMultipleMatchs() { - IEnumerable<XmlNode> i = new XPathEngine().SelectNodes("//li", - source); - Assert.IsNotNull(i); - int count = 0; - foreach (XmlNode n in i) { - count++; - Assert.AreEqual("li", n.Name); + public class XPathEngineTest : AbstractXPathEngineTest { + protected override IXPathEngine Engine { + get { + return new XPathEngine(); } - Assert.AreEqual(4, count); } - - [Test] - public void SelectNodesWithInvalidXPath() { - try { - new XPathEngine().SelectNodes("//li[", source); - Assert.Fail("expected an exception"); - } catch (XMLUnitException) { - // expected - } - } - - [Test] public void EvaluateWithNoMatches() { - Assert.AreEqual(string.Empty, new XPathEngine().Evaluate("foo", - source)); - } - - [Test] public void EvaluateWithSingleMatch() { - Assert.AreEqual("Don't blame it on the...", - new XPathEngine().Evaluate("//title", source)); - } - - [Test] public void EvaluateWithSingleMatchTextSelector() { - Assert.AreEqual("Don't blame it on the...", - new XPathEngine().Evaluate("//title/text()", - source)); - } - - [Test] public void EvaluateWithMultipleMatches() { - Assert.AreEqual("sunshine", - new XPathEngine().Evaluate("//li", source)); - } - - [Test] - public void EvaluateWithInvalidXPath() { - try { - new XPathEngine().Evaluate("//li[", source); - Assert.Fail("expected an exception"); - } catch (XMLUnitException) { - // expected - } - } - - [Test] public void SelectNodesWithNS() { - XPathEngine e = new XPathEngine(); - source = Input.FromMemory("<n:d xmlns:n='urn:test:1'><n:e/></n:d>") - .Build(); - Dictionary<string, string> m = new Dictionary<string, string>(); - m["x"] = "urn:test:1"; - e.NamespaceContext = m; - IEnumerable<XmlNode> it = e.SelectNodes("/x:d/x:e", source); - Assert.IsTrue(it.GetEnumerator().MoveNext()); - } - - [Test] public void SelectNodesWithDefaultNS() { - XPathEngine e = new XPathEngine(); - source = Input.FromMemory("<d xmlns='urn:test:1'><e/></d>") - .Build(); - Dictionary<string, string> m = new Dictionary<string, string>(); - m["x"] = "urn:test:1"; - e.NamespaceContext = m; - IEnumerable<XmlNode> it = e.SelectNodes("/x:d/x:e", source); - Assert.IsTrue(it.GetEnumerator().MoveNext()); - } - - // throws an exception "'/:d/:e' has an invalid token." - public void SelectNodesWithDefaultNSEmptyPrefix() { - XPathEngine e = new XPathEngine(); - source = Input.FromMemory("<d xmlns='urn:test:1'><e/></d>") - .Build(); - Dictionary<string, string> m = new Dictionary<string, string>(); - m[string.Empty] = "urn:test:1"; - e.NamespaceContext = m; - IEnumerable<XmlNode> it = e.SelectNodes("/:d/:e", source); - Assert.IsTrue(it.GetEnumerator().MoveNext()); - } - - // doesn't match - public void SelectNodesWithDefaultNSNoPrefix() { - XPathEngine e = new XPathEngine(); - source = Input.FromMemory("<d xmlns='urn:test:1'><e/></d>") - .Build(); - Dictionary<string, string> m = new Dictionary<string, string>(); - m[string.Empty] = "urn:test:1"; - e.NamespaceContext = m; - IEnumerable<XmlNode> it = e.SelectNodes("/d/e", source); - Assert.IsTrue(it.GetEnumerator().MoveNext()); - } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-05-03 10:26:29
|
Revision: 376 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=376&view=rev Author: bodewig Date: 2010-05-03 10:26:23 +0000 (Mon, 03 May 2010) Log Message: ----------- extract an interface Modified Paths: -------------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/xpath/JAXPXPathEngine.java trunk/xmlunit/src/main/net-core/xpath/XPathEngine.cs Added Paths: ----------- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/xpath/IXPathEngine.java trunk/xmlunit/src/main/net-core/xpath/IXPathEngine.cs Added: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/xpath/IXPathEngine.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/xpath/IXPathEngine.java (rev 0) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/xpath/IXPathEngine.java 2010-05-03 10:26:23 UTC (rev 376) @@ -0,0 +1,39 @@ +/* + 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.xpath; + +import java.util.Map; +import javax.xml.transform.Source; +import org.w3c.dom.Node; + +/** + * Interface for XMLUnit's XPath abstraction. + */ +public interface IXPathEngine { + /** + * Returns a potentially empty collection of Nodes matching an + * XPath expression. + */ + Iterable<Node> selectNodes(String xPath, Source s); + /** + * Evaluates an XPath expression and stringifies the result. + */ + String evaluate(String xPath, Source s); + /** + * Establish a namespace context. + * + * @param prefix2Uri maps from prefix to namespace URI. + */ + void setNamespaceContext(Map<String, String> prefix2Uri); +} Property changes on: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/xpath/IXPathEngine.java ___________________________________________________________________ Added: svn:eol-style + native Modified: trunk/xmlunit/src/main/java-core/net/sf/xmlunit/xpath/JAXPXPathEngine.java =================================================================== --- trunk/xmlunit/src/main/java-core/net/sf/xmlunit/xpath/JAXPXPathEngine.java 2010-05-03 06:49:13 UTC (rev 375) +++ trunk/xmlunit/src/main/java-core/net/sf/xmlunit/xpath/JAXPXPathEngine.java 2010-05-03 10:26:23 UTC (rev 376) @@ -29,7 +29,7 @@ /** * Simplified access to JAXP's XPath API. */ -public class JAXPXPathEngine { +public class JAXPXPathEngine implements IXPathEngine { private final XPath xpath; public JAXPXPathEngine(XPathFactory fac) { @@ -49,8 +49,7 @@ } /** - * Returns a potentially empty collection of Nodes matching an - * XPath expression. + * {@inheritDoc} */ public Iterable<Node> selectNodes(String xPath, Source s) { try { @@ -64,7 +63,7 @@ } /** - * Evaluates an XPath expression and stringifies the result. + * {@inheritDoc} */ public String evaluate(String xPath, Source s) { try { @@ -75,9 +74,7 @@ } /** - * Establish a namespace context. - * - * @param prefix2Uri maps from prefix to namespace URI. + * {@inheritDoc} */ public void setNamespaceContext(Map<String, String> prefix2Uri) { xpath.setNamespaceContext(Convert.toNamespaceContext(prefix2Uri)); Added: trunk/xmlunit/src/main/net-core/xpath/IXPathEngine.cs =================================================================== --- trunk/xmlunit/src/main/net-core/xpath/IXPathEngine.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/xpath/IXPathEngine.cs 2010-05-03 10:26:23 UTC (rev 376) @@ -0,0 +1,38 @@ +/* + 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.Generic; +using System.Xml; + +namespace net.sf.xmlunit.xpath { + + /// <summary> + /// Interface for XMLUnit's XPath abstraction. + /// </summary> + public interface IXPathEngine { + /// <summary> + /// Returns a potentially empty collection of Nodes matching an + /// XPath expression. + /// </summary> + IEnumerable<XmlNode> SelectNodes(string xPath, ISource s); + /// <summary> + /// Evaluates an XPath expression and stringifies the result. + /// </summary> + string Evaluate(string xPath, ISource s); + /// <summary> + /// Establish a namespace context - maps from prefix to namespace URI. + /// </summary> + IDictionary<string, string> NamespaceContext { set; } + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/main/net-core/xpath/IXPathEngine.cs ___________________________________________________________________ Added: svn:eol-style + native Modified: trunk/xmlunit/src/main/net-core/xpath/XPathEngine.cs =================================================================== --- trunk/xmlunit/src/main/net-core/xpath/XPathEngine.cs 2010-05-03 06:49:13 UTC (rev 375) +++ trunk/xmlunit/src/main/net-core/xpath/XPathEngine.cs 2010-05-03 10:26:23 UTC (rev 376) @@ -23,7 +23,7 @@ /// <summary> /// Simplified access to System.Xml.XPath API. /// </summary> - public class XPathEngine { + public class XPathEngine : IXPathEngine { private XmlNamespaceManager nsContext; /// <summary> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-05-03 06:49:19
|
Revision: 375 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=375&view=rev Author: bodewig Date: 2010-05-03 06:49:13 +0000 (Mon, 03 May 2010) Log Message: ----------- .NET version of XPath engine Modified Paths: -------------- trunk/xmlunit/src/tests/net-core/builder/InputTest.cs Added Paths: ----------- trunk/xmlunit/src/main/net-core/util/ trunk/xmlunit/src/main/net-core/util/Convert.cs trunk/xmlunit/src/main/net-core/xpath/ trunk/xmlunit/src/main/net-core/xpath/XPathEngine.cs trunk/xmlunit/src/tests/net-core/TestResources.cs trunk/xmlunit/src/tests/net-core/xpath/ trunk/xmlunit/src/tests/net-core/xpath/XPathEngineTest.cs Added: trunk/xmlunit/src/main/net-core/util/Convert.cs =================================================================== --- trunk/xmlunit/src/main/net-core/util/Convert.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/util/Convert.cs 2010-05-03 06:49:13 UTC (rev 375) @@ -0,0 +1,38 @@ +/* + 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.Generic; +using System.Xml; + +namespace net.sf.xmlunit.util { + /// <summary> + /// Conversion methods. + /// </summary> + public sealed class Convert { + private Convert() { } + + /// <summary> + /// Creates a namespace resolver from a Map prefix => + /// Namespace URI. + /// </summary> + public static XmlNamespaceManager + ToNamespaceContext(IDictionary<string, string> prefix2URI) { + XmlNamespaceManager man = new XmlNamespaceManager(new NameTable()); + foreach (KeyValuePair<string, string> kv in prefix2URI) { + man.AddNamespace(kv.Key, kv.Value); + } + return man; + } + } +} Property changes on: trunk/xmlunit/src/main/net-core/util/Convert.cs ___________________________________________________________________ Added: svn:eol-style + native Added: trunk/xmlunit/src/main/net-core/xpath/XPathEngine.cs =================================================================== --- trunk/xmlunit/src/main/net-core/xpath/XPathEngine.cs (rev 0) +++ trunk/xmlunit/src/main/net-core/xpath/XPathEngine.cs 2010-05-03 06:49:13 UTC (rev 375) @@ -0,0 +1,80 @@ +/* + 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.Generic; +using System.Xml; +using System.Xml.XPath; +using net.sf.xmlunit.exceptions; +using net.sf.xmlunit.util; + +namespace net.sf.xmlunit.xpath { + + /// <summary> + /// Simplified access to System.Xml.XPath API. + /// </summary> + public class XPathEngine { + private XmlNamespaceManager nsContext; + + /// <summary> + /// Returns a potentially empty collection of Nodes matching an + /// XPath expression. + /// </summary> + public IEnumerable<XmlNode> SelectNodes(string xPath, ISource s) { + try { + XmlDocument doc = new XmlDocument(); + doc.Load(s.Reader); + return ToNodeEnumerable(doc.SelectNodes(xPath, nsContext)); + } catch (XPathException ex) { + throw new XMLUnitException(ex); + } + } + + /// <summary> + /// Evaluates an XPath expression and stringifies the result. + /// </summary> + public string Evaluate(string xPath, ISource s) { + try { + XPathDocument doc = new XPathDocument(s.Reader); + object v = doc.CreateNavigator().Evaluate(xPath, nsContext); + if (v == null) { + return string.Empty; + } else if (v is XPathNodeIterator) { + XPathNodeIterator it = v as XPathNodeIterator; + if (it.MoveNext()) { + return (string) it.Current + .ValueAs(typeof(string), nsContext); + } + return string.Empty; + } + return v.ToString(); + } catch (XPathException ex) { + throw new XMLUnitException(ex); + } + } + + public IDictionary<string, string> NamespaceContext { + set { + nsContext = Convert.ToNamespaceContext(value); + } + } + + private IEnumerable<XmlNode> ToNodeEnumerable(XmlNodeList it) { + LinkedList<XmlNode> l = new LinkedList<XmlNode>(); + foreach (XmlNode n in it) { + l.AddLast(n); + } + return l; + } + } +} \ No newline at end of file Property changes on: trunk/xmlunit/src/main/net-core/xpath/XPathEngine.cs ___________________________________________________________________ Added: svn:eol-style + native Copied: trunk/xmlunit/src/tests/net-core/TestResources.cs (from rev 372, trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/TestResources.java) =================================================================== --- trunk/xmlunit/src/tests/net-core/TestResources.cs (rev 0) +++ trunk/xmlunit/src/tests/net-core/TestResources.cs 2010-05-03 06:49:13 UTC (rev 375) @@ -0,0 +1,22 @@ +/* + 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. +*/ +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 TestResources() { } + } +} Modified: trunk/xmlunit/src/tests/net-core/builder/InputTest.cs =================================================================== --- trunk/xmlunit/src/tests/net-core/builder/InputTest.cs 2010-04-30 14:29:47 UTC (rev 374) +++ trunk/xmlunit/src/tests/net-core/builder/InputTest.cs 2010-05-03 06:49:13 UTC (rev 375) @@ -22,8 +22,6 @@ [TestFixture] public class InputTest { - private const string TEST_FILE = "../../../src/tests/resources/test1.xml"; - private static XmlDocument Parse(ISource s) { XmlDocument d = new XmlDocument(); d.Load(s.Reader); @@ -31,23 +29,25 @@ } [Test] public void ShouldParseADocument() { - XmlDocument d = Parse(Input.FromFile(TEST_FILE).Build()); + XmlDocument d = Parse(Input.FromFile(TestResources.ANIMAL_FILE) + .Build()); AllIsWellFor(Input.FromDocument(d).Build()); } [Test] public void ShouldParseAnExistingFileByName() { - AllIsWellFor(Input.FromFile(TEST_FILE).Build()); + AllIsWellFor(Input.FromFile(TestResources.ANIMAL_FILE).Build()); } [Test] public void ShouldParseAnExistingFileFromStream() { - using (FileStream fs = new FileStream(TEST_FILE, FileMode.Open, + using (FileStream fs = new FileStream(TestResources.ANIMAL_FILE, + FileMode.Open, FileAccess.Read)) { AllIsWellFor(Input.FromStream(fs).Build()); } } [Test] public void ShouldParseAnExistingFileFromReader() { - using (StreamReader r = new StreamReader(TEST_FILE)) { + using (StreamReader r = new StreamReader(TestResources.ANIMAL_FILE)) { AllIsWellFor(Input.FromReader(r).Build()); } } @@ -63,12 +63,15 @@ [Ignore("looks as if file-URIs didn't work, revisit")] [Test] public void ShouldParseFileFromURIString() { - AllIsWellFor(Input.FromURI("file:" + TEST_FILE).Build()); + AllIsWellFor(Input.FromURI("file:" + TestResources.ANIMAL_FILE) + .Build()); } [Ignore("looks as if file-URIs didn't work, revisit")] [Test] public void ShouldParseFileFromURI() { - AllIsWellFor(Input.FromURI(new Uri("file:" + TEST_FILE)).Build()); + AllIsWellFor(Input.FromURI(new Uri("file:" + + TestResources.ANIMAL_FILE)) + .Build()); } [Test] public void ShouldParseATransformationFromSource() { @@ -102,7 +105,7 @@ } private static byte[] ReadTestFile() { - using (FileStream fs = new FileStream(TEST_FILE, FileMode.Open, + using (FileStream fs = new FileStream(TestResources.ANIMAL_FILE, FileMode.Open, FileAccess.Read)) using (MemoryStream ms = new MemoryStream()) { byte[] buffer = new byte[1024]; Copied: trunk/xmlunit/src/tests/net-core/xpath/XPathEngineTest.cs (from rev 370, trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/JAXPXPathEngineTest.java) =================================================================== --- trunk/xmlunit/src/tests/net-core/xpath/XPathEngineTest.cs (rev 0) +++ trunk/xmlunit/src/tests/net-core/xpath/XPathEngineTest.cs 2010-05-03 06:49:13 UTC (rev 375) @@ -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. +*/ + +using System.Collections.Generic; +using System.Xml; +using NUnit.Framework; +using net.sf.xmlunit.builder; +using net.sf.xmlunit.exceptions; + +namespace net.sf.xmlunit.xpath { + + [TestFixture] + public class XPathEngineTest { + + private ISource source; + + [SetUp] public void ReadSource() { + source = Input.FromFile(TestResources.BLAME_FILE).Build(); + } + + [Test] public void SelectNodesWithNoMatches() { + IEnumerable<XmlNode> i = new XPathEngine().SelectNodes("foo", + source); + Assert.IsNotNull(i); + Assert.IsFalse(i.GetEnumerator().MoveNext()); + } + + [Test] public void SelectNodesWithSingleMatch() { + IEnumerable<XmlNode> i = new XPathEngine().SelectNodes("//ul", + source); + Assert.IsNotNull(i); + IEnumerator<XmlNode> it = i.GetEnumerator(); + Assert.IsTrue(it.MoveNext()); + Assert.AreEqual("ul", it.Current.Name); + Assert.IsFalse(it.MoveNext()); + } + + [Test] public void SelectNodesWithMultipleMatchs() { + IEnumerable<XmlNode> i = new XPathEngine().SelectNodes("//li", + source); + Assert.IsNotNull(i); + int count = 0; + foreach (XmlNode n in i) { + count++; + Assert.AreEqual("li", n.Name); + } + Assert.AreEqual(4, count); + } + + [Test] + public void SelectNodesWithInvalidXPath() { + try { + new XPathEngine().SelectNodes("//li[", source); + Assert.Fail("expected an exception"); + } catch (XMLUnitException) { + // expected + } + } + + [Test] public void EvaluateWithNoMatches() { + Assert.AreEqual(string.Empty, new XPathEngine().Evaluate("foo", + source)); + } + + [Test] public void EvaluateWithSingleMatch() { + Assert.AreEqual("Don't blame it on the...", + new XPathEngine().Evaluate("//title", source)); + } + + [Test] public void EvaluateWithSingleMatchTextSelector() { + Assert.AreEqual("Don't blame it on the...", + new XPathEngine().Evaluate("//title/text()", + source)); + } + + [Test] public void EvaluateWithMultipleMatches() { + Assert.AreEqual("sunshine", + new XPathEngine().Evaluate("//li", source)); + } + + [Test] + public void EvaluateWithInvalidXPath() { + try { + new XPathEngine().Evaluate("//li[", source); + Assert.Fail("expected an exception"); + } catch (XMLUnitException) { + // expected + } + } + + [Test] public void SelectNodesWithNS() { + XPathEngine e = new XPathEngine(); + source = Input.FromMemory("<n:d xmlns:n='urn:test:1'><n:e/></n:d>") + .Build(); + Dictionary<string, string> m = new Dictionary<string, string>(); + m["x"] = "urn:test:1"; + e.NamespaceContext = m; + IEnumerable<XmlNode> it = e.SelectNodes("/x:d/x:e", source); + Assert.IsTrue(it.GetEnumerator().MoveNext()); + } + + [Test] public void SelectNodesWithDefaultNS() { + XPathEngine e = new XPathEngine(); + source = Input.FromMemory("<d xmlns='urn:test:1'><e/></d>") + .Build(); + Dictionary<string, string> m = new Dictionary<string, string>(); + m["x"] = "urn:test:1"; + e.NamespaceContext = m; + IEnumerable<XmlNode> it = e.SelectNodes("/x:d/x:e", source); + Assert.IsTrue(it.GetEnumerator().MoveNext()); + } + + // throws an exception "'/:d/:e' has an invalid token." + public void SelectNodesWithDefaultNSEmptyPrefix() { + XPathEngine e = new XPathEngine(); + source = Input.FromMemory("<d xmlns='urn:test:1'><e/></d>") + .Build(); + Dictionary<string, string> m = new Dictionary<string, string>(); + m[string.Empty] = "urn:test:1"; + e.NamespaceContext = m; + IEnumerable<XmlNode> it = e.SelectNodes("/:d/:e", source); + Assert.IsTrue(it.GetEnumerator().MoveNext()); + } + + // doesn't match + public void SelectNodesWithDefaultNSNoPrefix() { + XPathEngine e = new XPathEngine(); + source = Input.FromMemory("<d xmlns='urn:test:1'><e/></d>") + .Build(); + Dictionary<string, string> m = new Dictionary<string, string>(); + m[string.Empty] = "urn:test:1"; + e.NamespaceContext = m; + IEnumerable<XmlNode> it = e.SelectNodes("/d/e", source); + Assert.IsTrue(it.GetEnumerator().MoveNext()); + } + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-04-30 14:29:53
|
Revision: 374 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=374&view=rev Author: bodewig Date: 2010-04-30 14:29:47 +0000 (Fri, 30 Apr 2010) Log Message: ----------- stop Ant 1.8.0's whining about includeantruntime, make compile-userguide-examples actually work Modified Paths: -------------- trunk/xmlunit/build.xml Modified: trunk/xmlunit/build.xml =================================================================== --- trunk/xmlunit/build.xml 2010-04-30 13:55:59 UTC (rev 373) +++ trunk/xmlunit/build.xml 2010-04-30 14:29:47 UTC (rev 374) @@ -84,6 +84,7 @@ <target name="compile-core" depends="-init" description="compiles legacy sources and tests"> <javac srcdir="${src.dir}/java-core" destdir="${core.out.dir}" + includeantruntime="false" debug="${javac.debug}" target="${javac.target}" source="${javac.source}"> </javac> @@ -92,7 +93,8 @@ <target name="compile-legacy" depends="compile-core" description="compiles legacy sources and tests"> <javac srcdir="${src.dir}/java-legacy" destdir="${legacy.out.dir}" - debug="${javac.debug}" target="${javac.target}" source="${javac.source}"> + includeantruntime="false" debug="${javac.debug}" + target="${javac.target}" source="${javac.source}"> <classpath> <pathelement location="${core.out.dir}"/> <pathelement path="${java.class.path}"/> @@ -105,7 +107,8 @@ <target name="compile-legacy-tests" depends="compile-legacy" description="Compiles the test for XMLUnit 1.x"> <javac srcdir="${test.dir}/java-legacy" destdir="${legacytest.out.dir}" - debug="${javac.debug}" target="${javac.target}" source="${javac.source}"> + includeantruntime="false" debug="${javac.debug}" + target="${javac.target}" source="${javac.source}"> <classpath> <pathelement location="${core.out.dir}"/> <pathelement location="${legacy.out.dir}"/> @@ -119,6 +122,7 @@ <target name="compile-core-tests" depends="compile-core" description="Compiles the test for XMLUnit2"> <javac srcdir="${test.dir}/java-core" destdir="${coretest.out.dir}" + includeantruntime="false" debug="${javac.debug}" target="${javac.target}" source="${javac.source}"> <classpath> @@ -288,9 +292,11 @@ <target name="compile-userguide-examples" depends="compile"> <mkdir dir="${userguide.out.dir}"/> <javac srcdir="src/user-guide" includes="org/" - destdir="${userguide.out.dir}" source="1.3" target="1.2"> + includeantruntime="false" + destdir="${userguide.out.dir}" source="1.3" target="1.2"> <classpath> <pathelement location="${legacy.out.dir}"/> + <fileset dir="lib" includes="junit-3*.jar"/> </classpath> </javac> <delete dir="${userguide.out.dir}"/> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-04-30 13:56:06
|
Revision: 373 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=373&view=rev Author: bodewig Date: 2010-04-30 13:55:59 +0000 (Fri, 30 Apr 2010) Log Message: ----------- a few more tests Modified Paths: -------------- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/JAXPXPathEngineTest.java Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/JAXPXPathEngineTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/JAXPXPathEngineTest.java 2010-04-30 09:24:27 UTC (rev 372) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/JAXPXPathEngineTest.java 2010-04-30 13:55:59 UTC (rev 373) @@ -73,7 +73,12 @@ new JAXPXPathEngine().evaluate("//title", source)); } - @Test public void evaluateWithMultipleMatchs() { + @Test public void evaluateWithSingleMatchTextSelector() { + assertEquals("Don't blame it on the...", + new JAXPXPathEngine().evaluate("//title/text()", source)); + } + + @Test public void evaluateWithMultipleMatches() { assertEquals("sunshine", new JAXPXPathEngine().evaluate("//li", source)); } @@ -104,4 +109,27 @@ Iterable<Node> it = e.selectNodes("/x:d/x:e", source); assertTrue(it.iterator().hasNext()); } + + @Test public void selectNodesWithDefaultNSEmptyPrefix() { + JAXPXPathEngine e = new JAXPXPathEngine(); + source = Input.fromMemory("<d xmlns='urn:test:1'><e/></d>") + .build(); + HashMap<String, String> m = new HashMap<String, String>(); + m.put("", "urn:test:1"); + e.setNamespaceContext(m); + Iterable<Node> it = e.selectNodes("/:d/:e", source); + assertTrue(it.iterator().hasNext()); + } + + // doesn't match + public void selectNodesWithDefaultNSNoPrefix() { + JAXPXPathEngine e = new JAXPXPathEngine(); + source = Input.fromMemory("<d xmlns='urn:test:1'><e/></d>") + .build(); + HashMap<String, String> m = new HashMap<String, String>(); + m.put("", "urn:test:1"); + e.setNamespaceContext(m); + Iterable<Node> it = e.selectNodes("/d/e", source); + assertTrue(it.iterator().hasNext()); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-04-30 09:24:33
|
Revision: 372 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=372&view=rev Author: bodewig Date: 2010-04-30 09:24:27 +0000 (Fri, 30 Apr 2010) Log Message: ----------- use a better name for test resources constants Modified Paths: -------------- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/builder/InputTest.java trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/ConvertTest.java trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/JAXPXPathEngineTest.java Added Paths: ----------- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/TestResources.java Removed Paths: ------------- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/Resources.java Deleted: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/Resources.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/Resources.java 2010-04-30 09:08:03 UTC (rev 371) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/Resources.java 2010-04-30 09:24:27 UTC (rev 372) @@ -1,22 +0,0 @@ -/* - 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; - -public final class Resources { - public static final String ANIMAL_FILE = "src/tests/resources/test1.xml"; - public static final String BLAME_FILE = "src/tests/resources/test.blame.html"; - - private Resources() { } - -} Copied: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/TestResources.java (from rev 370, trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/Resources.java) =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/TestResources.java (rev 0) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/TestResources.java 2010-04-30 09:24:27 UTC (rev 372) @@ -0,0 +1,22 @@ +/* + 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; + +public final class TestResources { + public static final String ANIMAL_FILE = "src/tests/resources/test1.xml"; + public static final String BLAME_FILE = "src/tests/resources/test.blame.html"; + + private TestResources() { } + +} Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/builder/InputTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/builder/InputTest.java 2010-04-30 09:08:03 UTC (rev 371) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/builder/InputTest.java 2010-04-30 09:24:27 UTC (rev 372) @@ -23,7 +23,7 @@ import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Source; import org.w3c.dom.Document; -import net.sf.xmlunit.Resources; +import net.sf.xmlunit.TestResources; import net.sf.xmlunit.util.Convert; import org.junit.Test; @@ -41,23 +41,23 @@ } @Test public void shouldParseADocument() throws Exception { - Document d = parse(Input.fromFile(Resources.ANIMAL_FILE).build()); + Document d = parse(Input.fromFile(TestResources.ANIMAL_FILE).build()); Source s = Input.fromDocument(d).build(); allIsWellFor(s); } @Test public void shouldParseAnExistingFileByName() throws Exception { - allIsWellFor(Input.fromFile(Resources.ANIMAL_FILE).build()); + allIsWellFor(Input.fromFile(TestResources.ANIMAL_FILE).build()); } @Test public void shouldParseAnExistingFileByFile() throws Exception { - allIsWellFor(Input.fromFile(new File(Resources.ANIMAL_FILE)).build()); + allIsWellFor(Input.fromFile(new File(TestResources.ANIMAL_FILE)).build()); } @Test public void shouldParseAnExistingFileFromStream() throws Exception { FileInputStream is = null; try { - is = new FileInputStream(Resources.ANIMAL_FILE); + is = new FileInputStream(TestResources.ANIMAL_FILE); allIsWellFor(Input.fromStream(is).build()); } finally { if (is != null) { @@ -69,7 +69,7 @@ @Test public void shouldParseAnExistingFileFromReader() throws Exception { FileReader r = null; try { - r = new FileReader(Resources.ANIMAL_FILE); + r = new FileReader(TestResources.ANIMAL_FILE); allIsWellFor(Input.fromReader(r).build()); } finally { if (r != null) { @@ -88,15 +88,15 @@ } @Test public void shouldParseFileFromURIString() throws Exception { - allIsWellFor(Input.fromURI("file:" + Resources.ANIMAL_FILE).build()); + allIsWellFor(Input.fromURI("file:" + TestResources.ANIMAL_FILE).build()); } @Test public void shouldParseFileFromURI() throws Exception { - allIsWellFor(Input.fromURI(new URI("file:" + Resources.ANIMAL_FILE)).build()); + allIsWellFor(Input.fromURI(new URI("file:" + TestResources.ANIMAL_FILE)).build()); } @Test public void shouldParseFileFromURL() throws Exception { - allIsWellFor(Input.fromURL(new URL("file:" + Resources.ANIMAL_FILE)).build()); + allIsWellFor(Input.fromURL(new URL("file:" + TestResources.ANIMAL_FILE)).build()); } @Test public void shouldParseATransformationFromSource() throws Exception { @@ -129,7 +129,7 @@ } private static byte[] readTestFile() throws Exception { - FileInputStream is = new FileInputStream(Resources.ANIMAL_FILE); + FileInputStream is = new FileInputStream(TestResources.ANIMAL_FILE); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = -1; Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/ConvertTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/ConvertTest.java 2010-04-30 09:08:03 UTC (rev 371) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/util/ConvertTest.java 2010-04-30 09:24:27 UTC (rev 372) @@ -21,7 +21,7 @@ import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamSource; -import net.sf.xmlunit.Resources; +import net.sf.xmlunit.TestResources; import org.hamcrest.core.IsNull; import org.junit.Test; import org.w3c.dom.Document; @@ -41,18 +41,18 @@ } @Test public void streamSourceToInputSource() throws Exception { - convertAndAssert(new StreamSource(new File(Resources.ANIMAL_FILE))); + convertAndAssert(new StreamSource(new File(TestResources.ANIMAL_FILE))); } @Test public void domSourceToInputSource() throws Exception { DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document d = b.parse(new File(Resources.ANIMAL_FILE)); + Document d = b.parse(new File(TestResources.ANIMAL_FILE)); convertAndAssert(new DOMSource(d)); } @Test public void saxSourceToInputSource() throws Exception { - InputSource s = new InputSource(new FileInputStream(Resources.ANIMAL_FILE)); + InputSource s = new InputSource(new FileInputStream(TestResources.ANIMAL_FILE)); convertAndAssert(new SAXSource(s)); } Modified: trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/JAXPXPathEngineTest.java =================================================================== --- trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/JAXPXPathEngineTest.java 2010-04-30 09:08:03 UTC (rev 371) +++ trunk/xmlunit/src/tests/java-core/net/sf/xmlunit/xpath/JAXPXPathEngineTest.java 2010-04-30 09:24:27 UTC (rev 372) @@ -16,7 +16,7 @@ import java.util.HashMap; import java.util.Iterator; import javax.xml.transform.Source; -import net.sf.xmlunit.Resources; +import net.sf.xmlunit.TestResources; import net.sf.xmlunit.builder.Input; import net.sf.xmlunit.exceptions.XMLUnitException; import org.junit.Before; @@ -30,7 +30,7 @@ private Source source; @Before public void readSource() throws Exception { - source = Input.fromFile(Resources.BLAME_FILE).build(); + source = Input.fromFile(TestResources.BLAME_FILE).build(); } @Test public void selectNodesWithNoMatches() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bo...@us...> - 2010-04-30 09:08:09
|
Revision: 371 http://xmlunit.svn.sourceforge.net/xmlunit/?rev=371&view=rev Author: bodewig Date: 2010-04-30 09:08:03 +0000 (Fri, 30 Apr 2010) Log Message: ----------- upgrade JUnit Added Paths: ----------- trunk/xmlunit/lib/junit-4.8.2.jar Removed Paths: ------------- trunk/xmlunit/lib/junit-4.7.jar Deleted: trunk/xmlunit/lib/junit-4.7.jar =================================================================== (Binary files differ) Added: trunk/xmlunit/lib/junit-4.8.2.jar =================================================================== (Binary files differ) Property changes on: trunk/xmlunit/lib/junit-4.8.2.jar ___________________________________________________________________ Added: svn:mime-type + application/octet-stream This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |