Java Code Examples for org.custommonkey.xmlunit.XMLUnit#compareXML()

The following examples show how to use org.custommonkey.xmlunit.XMLUnit#compareXML() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractSourceCodeAwareNodeProcessingTest.java    From jaxb2-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Compares XML documents provided by the two Readers.
 *
 * @param expected The expected document data.
 * @param actual   The actual document data.
 * @return A DetailedDiff object, describing all differences in documents supplied.
 * @throws org.xml.sax.SAXException If a SAXException was raised during parsing of the two Documents.
 * @throws IOException              If an I/O-related exception was raised while acquiring the data from the Readers.
 */
protected static Diff compareXmlIgnoringWhitespace(final String expected, final String actual) throws SAXException,
        IOException {

    // Check sanity
    Validate.notNull(expected, "Cannot handle null expected argument.");
    Validate.notNull(actual, "Cannot handle null actual argument.");

    // Ignore whitespace - and also normalize the Documents.
    XMLUnit.setNormalize(true);
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setNormalize(true);

    // Compare and return
    return XMLUnit.compareXML(expected, actual);
}
 
Example 2
Source File: N2oConfigConflictParserTest.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
private void testParse(String conflictFilePath, String originFilePath) throws IOException, SAXException {
    URL conflict = this.getClass().getClassLoader().getResource(RESOURCE_PATH + conflictFilePath);
    URL parent = this.getClass().getClassLoader().getResource(RESOURCE_PATH + originFilePath);
    Assert.assertTrue(conflict != null && parent != null);
    N2oConfigConflict configConflict = new N2oConfigConflict();
    configConflict.setConflictContent(IOUtils.toString(conflict, "UTF-8"));
    N2oConfigConflictParser.restoreContentsByConflict(configConflict);
    Diff diff = XMLUnit.compareXML(configConflict.getParentContent(), IOUtils.toString(parent, "UTF-8"));
    Assert.assertTrue(diff.identical());
}
 
Example 3
Source File: CheckstyleTestUtils.java    From sonar-checkstyle with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void assertSimilarXml(String expectedXml, String xml) {
    XMLUnit.setIgnoreWhitespace(true);
    final Diff diff;
    try {
        diff = XMLUnit.compareXML(xml, expectedXml);
    }
    catch (SAXException | IOException ex) {
        throw new IllegalArgumentException("Could not run XML comparison", ex);
    }
    final String message = "Diff: " + diff + CharUtils.LF + "XML: " + xml;
    assertTrue(message, diff.similar());
}
 
Example 4
Source File: TransformerEncodeTest.java    From exificient with MIT License 5 votes vote down vote up
@Test
public void testEncode() throws Exception {
	final StringReader reader = new StringReader(XML);
	final EXIFactory factory = getFactory(true);
	final byte[] bytes = encode(factory, reader).toByteArray();
	final Document decode = decode(factory, new InputSource(
			new ByteArrayInputStream(bytes)));
	final Diff diff = XMLUnit.compareXML(XMLUnit.buildControlDocument(XML),
			decode);
	Assert.assertTrue(diff.toString(), diff.similar());
}
 
Example 5
Source File: TransformerEncodeTest.java    From exificient with MIT License 5 votes vote down vote up
@Test
public void testEncodeTransformer() throws Exception {
	final StringReader reader = new StringReader(XML);
	final EXIFactory factory = getFactory(true);
	final byte[] bytes = transformerEncode(factory, new InputSource(reader))
			.toByteArray();
	final Document decode = decode(factory, new InputSource(
			new ByteArrayInputStream(bytes)));
	final Diff diff = XMLUnit.compareXML(XMLUnit.buildControlDocument(XML),
			decode);
	Assert.assertTrue(diff.toString(), diff.similar());
}
 
Example 6
Source File: DLNAServiceTest.java    From Connect-SDK-Android-Core with Apache License 2.0 5 votes vote down vote up
private void assertXMLEquals(String expectedXML, String actualXML) throws SAXException, IOException {
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setNormalize(true);
    DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expectedXML, actualXML));
    List<?> allDifferences = diff.getAllDifferences();
    Assert.assertEquals("XML differences found: " + diff.toString(), 0, allDifferences.size());
}
 
Example 7
Source File: IbisConsoleTest.java    From iaf with Apache License 2.0 5 votes vote down vote up
private void compareXML(String expectedFile, String result) throws SAXException, IOException, DomBuilderException, TransformerException {
	URL expectedUrl = ClassUtils.getResourceURL(IbisConsoleTest.class.getClassLoader(), expectedFile);
	if (expectedUrl == null) {
		throw new IOException("cannot find resource [" + expectedUrl + "]");
	}
	String expected = Misc.resourceToString(expectedUrl);
	XMLUnit.setIgnoreAttributeOrder(true);
	Diff diff = XMLUnit.compareXML(expected, result);
	assertTrue(diff.toString(), diff.identical());
}
 
Example 8
Source File: XmlBuilderTest.java    From iaf with Apache License 2.0 5 votes vote down vote up
private void compareXML(String expected, String actual)
		throws SAXException, IOException {
	// System.out.println(expected);
	// System.out.println(actual);
	Diff diff = XMLUnit.compareXML(expected, actual);
	assertTrue(diff.toString(), diff.identical());
}
 
Example 9
Source File: JdbcUtilTest.java    From iaf with Apache License 2.0 5 votes vote down vote up
private void compareXML(String expectedFile, String result)
		throws SAXException, IOException {
	URL expectedUrl = ClassUtils.getResourceURL(this, expectedFile);
	if (expectedUrl == null) {
		throw new IOException("cannot find resource [" + expectedUrl + "]");
	}
	String expected = Misc.resourceToString(expectedUrl);
	Diff diff = XMLUnit.compareXML(expected, result);
	assertTrue(diff.toString(), diff.identical());
}
 
Example 10
Source File: TestCreoleAnnotationHandler.java    From gate-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Take a skeleton creole.xml file, process the annotations on the classes it
 * mentions and compare the resulting XML to the expected result.
 */
public void testCreoleAnnotationHandler() throws Exception {
  URL originalUrl = new URL(TestDocument.getTestServerName()+"tests/creole-annotation-handler/initial-creole.xml");
  org.jdom.Document creoleXml =
    jdomBuilder.build(originalUrl.openStream());
  CreoleAnnotationHandler processor = new CreoleAnnotationHandler(new Plugin.Directory(new URL(TestDocument.getTestServerName()+"tests/creole-annotation-handler/")));
  processor.processAnnotations(creoleXml);

  URL expectedURL = new URL(TestDocument.getTestServerName()+"tests/creole-annotation-handler/expected-creole.xml");

  // XMLUnit requires the expected and actual results as W3C DOM rather than
  // JDOM
  DocumentBuilder docBuilder = jaxpFactory.newDocumentBuilder();
  org.w3c.dom.Document targetXmlDOM =
    docBuilder.parse(expectedURL.openStream());

  org.w3c.dom.Document actualXmlDOM = jdom2dom.output(creoleXml);

  Diff diff = XMLUnit.compareXML(targetXmlDOM, actualXmlDOM);

  // compare parameter elements with the same NAME, resources with the same
  // CLASS, and all other elements that have the same element name
  diff.overrideElementQualifier(new ElementNameQualifier() {
    @Override
    public boolean qualifyForComparison(Element control, Element test) {
      if("PARAMETER".equals(control.getTagName()) && "PARAMETER".equals(test.getTagName())) {
        return control.getAttribute("NAME").equals(test.getAttribute("NAME"));
      }
      else if("RESOURCE".equals(control.getTagName()) && "RESOURCE".equals(test.getTagName())) {
        String controlClass = findClass(control);
        String testClass = findClass(test);
        return (controlClass == null) ? (testClass == null)
                  : controlClass.equals(testClass);
      }
      else {
        return super.qualifyForComparison(control, test);
      }
    }

    private String findClass(Element resource) {
      Node node = resource.getFirstChild();
      while(node != null && !"CLASS".equals(node.getNodeName())) {
        node = node.getNextSibling();
      }

      if(node != null) {
        return node.getTextContent();
      }
      else {
        return null;
      }
    }
  });

  // do the comparison!
  boolean match = diff.similar();
  if(!match) {
    // if comparison failed, output the "actual" result document for
    // debugging purposes
    System.err.println("---------actual-----------");   	
    new XMLOutputter(Format.getPrettyFormat()).output(creoleXml, System.err);
  }

  assertTrue("XML produced by annotation handler does not match expected: "
      + diff.toString() , match);
}
 
Example 11
Source File: ODataXmlSerializerTest.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private void checkXMLEqual(final String expected, final String resultString) throws SAXException, IOException {
  Diff diff = XMLUnit.compareXML(expected, resultString);
  diff.overrideDifferenceListener(DIFFERENCE_LISTENER);
  XMLAssert.assertXMLEqual(diff, true);
}
 
Example 12
Source File: XmlUnitService.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
@Override
public String getDifferencesFromXml(String left, String right) {
    try {
        // Gets the detailed diff between left and right argument
        Document leftDocument = inputTranslator.translate(left);
        Document rightDocument = inputTranslator.translate(right);
        DetailedDiff diffs = new DetailedDiff(XMLUnit.compareXML(leftDocument, rightDocument));

        // Creates the result structure which will contain difference list
        Differences resultDiff = new Differences();

        // Add each difference to our result structure
        for (Object diff : diffs.getAllDifferences()) {
            if (!(diff instanceof Difference)) {
                LOG.warn("Unable to handle no XMLUnit Difference " + diff);
                continue;
            }
            Difference wellTypedDiff = (Difference) diff;
            String xPathLocation = wellTypedDiff.getControlNodeDetail().getXpathLocation();
            // Null XPath location means additional data from the right
            // structure.
            // Then we retrieve XPath from the right structure.
            if (xPathLocation == null) {
                xPathLocation = wellTypedDiff.getTestNodeDetail().getXpathLocation();
            }
            // If location is still null, then both of left and right
            // differences have been marked as null
            // This case should never happen
            if (xPathLocation == null) {
                LOG.warn("Null left and right differences found");
                xPathLocation = NULL_XPATH;
            }
            resultDiff.addDifference(new org.cerberus.service.xmlunit.Difference(xPathLocation));
        }

        // Finally returns the String representation of our result structure
        return resultDiff.mkString();
    } catch (InputTranslatorException e) {
        LOG.warn("Unable to get differences from XML", e);
    }

    return null;
}
 
Example 13
Source File: HtmlUtils.java    From ogham with Apache License 2.0 3 votes vote down vote up
/**
 * Compare two HTML documents. The HTML strings are parsed into
 * {@link Document}s. The HTML are compared by elements and attributes, not
 * using directly using string.
 * 
 * <p>
 * A {@link DetailedDiff} is provided to know if the documents are
 * "identical" or "similar":
 * <ul>
 * <li>Two documents are considered to be "identical" if they contain the
 * same elements and attributes in the same order.</li>
 * <li>Two documents are considered to be "similar" if they contain the same
 * elements and attributes regardless of order.</li>
 * </ul>
 * 
 * 
 * @param expected
 *            the expected HTML
 * @param actual
 *            the HTML content to check
 * @return a report that let you know differences between the two HTML
 *         strings
 */
public static DetailedDiff compare(String expected, String actual) {
	if (expected == null) {
		throw new IllegalArgumentException("expected html can't be null");
	}
	try {
		HTMLDocumentBuilder builder = new HTMLDocumentBuilder(new TolerantSaxDocumentBuilder(XMLUnit.newTestParser()));
		Document expectedDoc = builder.parse(expected);
		Document actualDoc = builder.parse(actual==null ? "" : actual);
		return new DetailedDiff(XMLUnit.compareXML(expectedDoc, actualDoc));
	} catch (SAXException | IOException | ConfigurationException | ParserConfigurationException e) {
		throw new ComparisonException("Failed to compare HTML", e);
	}
}