Java Code Examples for org.custommonkey.xmlunit.Diff#overrideDifferenceListener()

The following examples show how to use org.custommonkey.xmlunit.Diff#overrideDifferenceListener() . 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: BatchJobUploadBodyProviderTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidOperations() throws BatchJobException, IOException, SAXException {
  RequestT request = createMutateRequest();
  addBudgetOperation(request, -1L, "Test budget", 50000000L, "STANDARD");
  addCampaignOperation(
      request, -2L, "Test campaign #1", "PAUSED", "SEARCH", -1L, "MANUAL_CPC", false);
  addCampaignOperation(
      request, -3L, "Test campaign #2", "PAUSED", "SEARCH", -1L, "MANUAL_CPC", false);
  addCampaignNegativeKeywordOperation(request, -2L, "venus", "BROAD");
  addCampaignNegativeKeywordOperation(request, -3L, "venus", "BROAD");
  ByteArrayContent httpContent =
      request.createBatchJobUploadBodyProvider().getHttpContent(request, true, true);
  String actualRequestXml = Streams.readAll(httpContent.getInputStream(), Charset.forName(UTF_8));
  actualRequestXml =
      SoapRequestXmlProvider.normalizeXmlForComparison(actualRequestXml, getApiVersion());
  String expectedRequestXml = SoapRequestXmlProvider.getTestBatchUploadRequest(getApiVersion());

  // Perform an XML diff using the custom difference listener that properly handles namespaces
  // and attributes.
  Diff diff = new Diff(expectedRequestXml, actualRequestXml);
  DifferenceListener diffListener = new CustomDifferenceListener();
  diff.overrideDifferenceListener(diffListener);
  XMLAssert.assertXMLEqual("Serialized upload request does not match expected XML", diff, true);
}
 
Example 2
Source File: XmlAsserter.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static XmlAsserter.AssertResult assertXml(String expected, String actual) {
   XmlAsserter.AssertResult result = new XmlAsserter.AssertResult();

   try {
      LOG.debug("expected  : " + linearize(expected));
      LOG.debug("actual    : " + linearize(actual));
      Diff diff = new Diff(expected, actual);
      diff.overrideDifferenceListener(listener);
      diff.overrideElementQualifier(qualifier);
      result.setSimilar(diff.similar());
      LOG.debug("Similar : " + result.isSimilar());
      DetailedDiff detDiff = new DetailedDiff(diff);
      List<Difference> differences = detDiff.getAllDifferences();
      Iterator var7 = differences.iterator();

      while(var7.hasNext()) {
         Difference difference = (Difference)var7.next();
         if (!difference.isRecoverable()) {
            LOG.debug(difference.toString() + " expected :" + difference.getControlNodeDetail() + " but was :" + difference.getTestNodeDetail() + "  " + difference.getDescription());
            result.getDifferences().add(difference);
         }
      }
   } catch (Exception var8) {
      LOG.error(var8.getMessage(), var8);
      Assert.fail(var8.getMessage());
   }

   return result;
}
 
Example 3
Source File: AnydataSerializeTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testAnydataLoadFromXML() throws IOException, SAXException, XMLStreamException, URISyntaxException {
    // Load XML file
    Document doc = loadXmlDocument("/test-anydata.xml");
    final DOMSource domSource = new DOMSource(doc.getDocumentElement());

    //Load XML from file and write it with xmlParseStream
    final DOMResult domResult = new DOMResult(UntrustedXML.newDocumentBuilder().newDocument());
    final XMLStreamWriter xmlStreamWriter = factory.createXMLStreamWriter(domResult);
    final AnydataSchemaNode anyDataSchemaNode = (AnydataSchemaNode) SchemaContextUtil.findDataSchemaNode(
            SCHEMA_CONTEXT, SchemaPath.create(true, FOO_QNAME));
    final NormalizedNodeStreamWriter streamWriter = XMLStreamNormalizedNodeStreamWriter.create(
            xmlStreamWriter, SCHEMA_CONTEXT);
    final XMLStreamReader reader = new DOMSourceXMLStreamReader(domSource);
    final XmlParserStream xmlParser = XmlParserStream.create(streamWriter, SCHEMA_CONTEXT, anyDataSchemaNode);

    xmlParser.parse(reader);
    xmlParser.flush();

    //Set XML comparing
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setNormalize(true);

    // Check diff
    final String expectedXml = toString(doc.getDocumentElement());
    final String serializedXml = toString(domResult.getNode());
    final Diff diff = new Diff(expectedXml, serializedXml);
    final DifferenceListener differenceListener = new IgnoreTextAndAttributeValuesDifferenceListener();
    diff.overrideDifferenceListener(differenceListener);

    XMLAssert.assertXMLEqual(diff, true);
}
 
Example 4
Source File: AnydataSerializeTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testAnydataSerialization()
        throws IOException, SAXException, XMLStreamException, URISyntaxException, TransformerException {
    //Get XML Data.
    Document doc = loadXmlDocument("/test-anydata.xml");
    final DOMSource domSource = new DOMSource(doc.getDocumentElement());

    //Get specific attribute from Yang file.
    final AnydataSchemaNode contWithAttr = (AnydataSchemaNode) SchemaContextUtil.findDataSchemaNode(
            SCHEMA_CONTEXT, SchemaPath.create(true, FOO_QNAME));

    //Create NormalizedNodeResult
    NormalizedNodeResult normalizedResult = new NormalizedNodeResult();
    final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(normalizedResult);

    //Initialize Reader with XML file
    final XMLStreamReader reader = new DOMSourceXMLStreamReader(domSource);
    final XmlParserStream xmlParser = XmlParserStream.create(streamWriter, SCHEMA_CONTEXT, contWithAttr);
    xmlParser.parse(reader);
    xmlParser.flush();

    //Get Result
    final NormalizedNode<?, ?> node = normalizedResult.getResult();
    assertTrue(node instanceof AnydataNode);
    final AnydataNode<?> anydataResult = (AnydataNode<?>) node;

    //Get Result in formatted String
    assertTrue(anydataResult.getValue() instanceof DOMSourceAnydata);
    final String serializedXml = getXmlFromDOMSource(((DOMSourceAnydata)anydataResult.getValue()).getSource());
    final String expectedXml = toString(doc.getDocumentElement());

    //Looking for difference in Serialized xml and in Loaded XML
    final Diff diff = new Diff(expectedXml, serializedXml);
    final DifferenceListener differenceListener = new IgnoreTextAndAttributeValuesDifferenceListener();
    diff.overrideDifferenceListener(differenceListener);

    XMLAssert.assertXMLEqual(diff, true);
}
 
Example 5
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 6
Source File: AnydataSerializeTest.java    From yangtools with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testXmlParseAnydata()
        throws IOException, SAXException, XMLStreamException, URISyntaxException, TransformerException {

    //Create Data Scheme from yang file
    SchemaPath anydataPath = SchemaPath.create(true, FOO_QNAME);
    final SchemaNode dataSchemaNode = SchemaContextUtil.findDataSchemaNode(SCHEMA_CONTEXT, anydataPath);
    assertTrue(dataSchemaNode instanceof AnydataSchemaNode);
    final AnydataSchemaNode anyDataSchemaNode = (AnydataSchemaNode) dataSchemaNode;

    // deserialization
    final XMLStreamReader reader
            = UntrustedXML.createXMLStreamReader(loadResourcesAsInputStream("/test-anydata.xml"));

    final NormalizedNodeResult result = new NormalizedNodeResult();
    final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
    final XmlParserStream xmlParser = XmlParserStream.create(streamWriter, SCHEMA_CONTEXT, anyDataSchemaNode);
    xmlParser.parse(reader);

    final NormalizedNode<?, ?> transformedInput = result.getResult();
    assertNotNull(transformedInput);
    assertTrue(transformedInput instanceof AnydataNode);
    AnydataNode<?> anydataNode = (AnydataNode<?>) transformedInput;

    // serialization
    final StringWriter writer = new StringWriter();
    final XMLStreamWriter xmlStreamWriter = factory.createXMLStreamWriter(writer);
    final NormalizedNodeStreamWriter xmlNormalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(
            xmlStreamWriter, SCHEMA_CONTEXT);
    final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(
            xmlNormalizedNodeStreamWriter);
    normalizedNodeWriter.write(transformedInput);
    normalizedNodeWriter.flush();

    final String serializedXml = writer.toString();
    final String deserializeXml = getXmlFromDOMSource(((DOMSourceAnydata) anydataNode.getValue()).getSource());
    assertFalse(serializedXml.isEmpty());

    // Check if is Serialize Node same as Deserialize Node
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setNormalize(true);
    final Diff diff = new Diff(deserializeXml, serializedXml);
    final DifferenceListener differenceListener = new IgnoreTextAndAttributeValuesDifferenceListener();
    diff.overrideDifferenceListener(differenceListener);

    XMLAssert.assertXMLEqual(diff, true);
}
 
Example 7
Source File: NormalizedNodeXmlTranslationTest.java    From yangtools with Eclipse Public License 1.0 4 votes vote down vote up
private void testTranslation(final XMLOutputFactory factory) throws Exception {
    final InputStream resourceAsStream = XmlToNormalizedNodesTest.class.getResourceAsStream(xmlPath);

    final XMLStreamReader reader = UntrustedXML.createXMLStreamReader(resourceAsStream);

    final NormalizedNodeResult result = new NormalizedNodeResult();
    final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);

    final XmlParserStream xmlParser = XmlParserStream.create(streamWriter, schema, containerNode);
    xmlParser.parse(reader);

    final NormalizedNode<?, ?> built = result.getResult();
    assertNotNull(built);

    if (expectedNode != null) {
        org.junit.Assert.assertEquals(expectedNode, built);
    }

    final Document document = UntrustedXML.newDocumentBuilder().newDocument();
    final DOMResult domResult = new DOMResult(document);

    final XMLStreamWriter xmlStreamWriter = factory.createXMLStreamWriter(domResult);

    final NormalizedNodeStreamWriter xmlNormalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter
            .create(xmlStreamWriter, schema);

    final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(
            xmlNormalizedNodeStreamWriter);

    normalizedNodeWriter.write(built);

    final Document doc = loadDocument(xmlPath);

    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreComments(true);
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setNormalize(true);

    final String expectedXml = toString(doc.getDocumentElement());
    final String serializedXml = toString(domResult.getNode());

    final Diff diff = new Diff(expectedXml, serializedXml);
    diff.overrideDifferenceListener(new IgnoreTextAndAttributeValuesDifferenceListener());
    diff.overrideElementQualifier(new ElementNameAndTextQualifier());

    // FIXME the comparison cannot be performed, since the qualifiers supplied by XMlUnit do not work correctly in
    // this case
    // We need to implement custom qualifier so that the element ordering does not mess the DIFF
    // dd.overrideElementQualifier(new MultiLevelElementNameAndTextQualifier(100, true));
    // assertTrue(dd.toString(), dd.similar());

    //new XMLTestCase() {}.assertXMLEqual(diff, true);
}
 
Example 8
Source File: Main.java    From libreveris with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void compare ()
{
    // Comparing
    try {
        output.println("Comparing " + controlFile + " to " + testFile);

        final Document controlDoc;
        final Document testDoc;

        try (InputStream cis = new FileInputStream(controlFile)) {
            controlDoc = new PositionalXMLReader().readXML(cis);
        }
        try (InputStream tis = new FileInputStream(testFile)) {
            testDoc = new PositionalXMLReader().readXML(tis);
        }

        // Tuning
        XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true);
        XMLUnit.setNormalizeWhitespace(true);
        XMLUnit.setIgnoreWhitespace(true);

        ///XMLUnit.setIgnoreComments(true); NO!!!!!!!!
        // The setIgnoreComments triggers the use of XSLT transform
        // which 1/ ruins userdata and 2/ fails on xml:space and xml:lang.
        // Moreover, comments are actually ignored by Diff

        ///XMLUnit.setCompareUnmatched(false); NO need

        // Customization
        Filter filter = (filterFile != null)
                ? new BasicFilter(new FileInputStream(filterFile))
                : null;

        Diff diff = new Diff(controlDoc, testDoc, null);
        diff.overrideElementQualifier(
                new ElementNameAndAttributeQualifier("number"));
        diff.overrideDifferenceListener(
                new MusicDifferenceListener(filter, output));

        output.println("Similar:     " + diff.similar());
        output.println("Identical:   " + diff.identical());

        DetailedDiff detDiff = new DetailedDiff(diff);

        List differences = detDiff.getAllDifferences();
        output.println();
        output.println("Physical differences: " + differences.size());

        int diffId = 0;

        for (Object object : differences) {
            Difference difference = (Difference) object;

            if (!difference.isRecoverable()
                && ((filter == null) || !filter.canIgnore(difference))) {
                diffId++;
                output.dump(diffId, difference);
            }
        }
        output.println("Logical  differences: " + diffId);
        logger.info("Logical  differences: {}", diffId);

    } catch (ConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
}
 
Example 9
Source File: EjbJarXmlTest.java    From tomee with Apache License 2.0 4 votes vote down vote up
/**
 * TODO Doesn't seem there are any asserts here
 *
 * @throws Exception
 */
public void testEjbJar() throws Exception {
    final String fileName = "ejb-jar-example1.xml";

    final Event test = Event.start("Test");

    final URL resource = this.getClass().getClassLoader().getResource(fileName);

    final String expected = IO.slurp(resource);

    final Event ejbJarJAXBCreate = Event.start("EjbJarJAXBCreate");
    ejbJarJAXBCreate.stop();

    final Event unmarshalEvent = Event.start("unmarshal");
    final Object value;

    final EjbJar$JAXB jaxbType = new EjbJar$JAXB();
    value = Sxc.unmarshalJavaee(resource, jaxbType);

    unmarshalEvent.stop();

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    final Event marshall = Event.start("marshall");
    Sxc.marshall(jaxbType, value, baos);
    marshall.stop();

    final String result = new String(baos.toByteArray(), "UTF-8");

    XMLUnit.setIgnoreComments(Boolean.TRUE);
    XMLUnit.setIgnoreWhitespace(Boolean.TRUE);
    XMLUnit.setIgnoreAttributeOrder(Boolean.TRUE);
    XMLUnit.setIgnoreDiffBetweenTextAndCDATA(Boolean.TRUE);

    final Diff diff = new Diff(expected.trim(), result.trim());
    final Diff myDiff = new DetailedDiff(diff);

    final AtomicInteger differenceNumber = new AtomicInteger(0); // just to get an int wrapper for the test
    myDiff.overrideDifferenceListener(new IgnoreTextAndAttributeValuesDifferenceListener() {
        @Override
        public int differenceFound(final Difference difference) {
            if (!difference.isRecoverable()) {
                differenceNumber.incrementAndGet();
                System.err.println(">>> " + difference.toString());
            }
            return 0;
        }
    });

    assertTrue("Files are not identical", myDiff.identical());
    test.stop();
}
 
Example 10
Source File: ConversionTest.java    From tomee with Apache License 2.0 4 votes vote down vote up
public void testConversion() throws Exception {
    final JAXBElement element = (JAXBElement) JaxbOpenejbJar2.unmarshal(OpenejbJarType.class, getInputStream("openejb-jar-2-full.xml"));
    final OpenejbJarType o2 = (OpenejbJarType) element.getValue();

    final GeronimoEjbJarType g2 = new GeronimoEjbJarType();

    g2.setEnvironment(o2.getEnvironment());
    g2.setSecurity(o2.getSecurity());
    g2.getService().addAll(o2.getService());
    g2.getMessageDestination().addAll(o2.getMessageDestination());

    for (final EnterpriseBean bean : o2.getEnterpriseBeans()) {
        g2.getAbstractNamingEntry().addAll(bean.getAbstractNamingEntry());
        g2.getPersistenceContextRef().addAll(bean.getPersistenceContextRef());
        g2.getEjbLocalRef().addAll(bean.getEjbLocalRef());
        g2.getEjbRef().addAll(bean.getEjbRef());
        g2.getResourceEnvRef().addAll(bean.getResourceEnvRef());
        g2.getResourceRef().addAll(bean.getResourceRef());
        g2.getServiceRef().addAll(bean.getServiceRef());

        if (bean instanceof RpcBean) {
            final RpcBean rpcBean = (RpcBean) bean;
            if (rpcBean.getTssLink() != null) {
                g2.getTssLink().add(new TssLinkType(rpcBean.getEjbName(), rpcBean.getTssLink(), rpcBean.getJndiName()));
            }
        }
    }

    final JAXBElement root = new JAXBElement(new QName("http://geronimo.apache.org/xml/ns/j2ee/ejb/openejb-2.0", "ejb-jar"), GeronimoEjbJarType.class, g2);
    final String result = JaxbOpenejbJar2.marshal(GeronimoEjbJarType.class, root);
    final String expected = readContent(getInputStream("geronimo-openejb-converted.xml"));

    final Diff myDiff = new DetailedDiff(new Diff(expected, result));
    final AtomicInteger differenceNumber = new AtomicInteger(0); // just to get an int wrapper for the test
    myDiff.overrideDifferenceListener(new DifferenceListener() {
        @Override
        public int differenceFound(final Difference difference) {
            if (!difference.isRecoverable()) {
                differenceNumber.incrementAndGet();
                System.err.println(">>> " + difference.toString());
            }
            return 0;
        }

        @Override
        public void skippedComparison(final Node node, final Node node1) {
            // no-op
        }
    });
    assertTrue("Files are not similar", myDiff.similar());
}
 
Example 11
Source File: QueryResultsComparator.java    From fosstrak-epcis with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Compares the two given QueryResults with each other and returns
 * <code>true</code> if they are identical, <code>false</code>
 * otherwise. If the two instances are not similar, it prints information to
 * System.out.
 * 
 * @param expResults
 *            The expected QueryResults object.
 * @param actResults
 *            The actual QueryResults object.
 * @return <code>true</code> if the two given QueryResults objects are
 *         identical, <code>false</code> otherwise.
 */
public static boolean identical(final QueryResults expResults, final QueryResults actResults) throws IOException {
    Document expDoc = QueryResultsParser.queryResultsToDocument(expResults);
    Document actDoc = QueryResultsParser.queryResultsToDocument(actResults);

    Diff diff = new Diff(expDoc, actDoc);
    diff.overrideDifferenceListener(new MyDifferenceLister());
    return diff.identical();
}
 
Example 12
Source File: NormalizedNodesToXmlTest.java    From yangtools with Eclipse Public License 1.0 3 votes vote down vote up
@Test
public void testNormalizedNodeToXmlSerialization() throws XMLStreamException, IOException, SAXException {
    final Document doc = loadDocument("/baz.xml");

    final DOMResult domResult = new DOMResult(UntrustedXML.newDocumentBuilder().newDocument());

    final XMLStreamWriter xmlStreamWriter = factory.createXMLStreamWriter(domResult);

    final NormalizedNodeStreamWriter xmlNormalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(
            xmlStreamWriter, SCHEMA_CONTEXT);

    final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(
            xmlNormalizedNodeStreamWriter);

    normalizedNodeWriter.write(buildOuterContainerNode());

    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setNormalize(true);

    final String expectedXml = toString(doc.getDocumentElement());
    final String serializedXml = toString(domResult.getNode());
    final Diff diff = new Diff(expectedXml, serializedXml);

    final DifferenceListener differenceListener = new IgnoreTextAndAttributeValuesDifferenceListener();
    diff.overrideDifferenceListener(differenceListener);

    new XMLTestCase() {}.assertXMLEqual(diff, true);
}
 
Example 13
Source File: SchemalessXMLStreamNormalizedNodeStreamWriterTest.java    From yangtools with Eclipse Public License 1.0 3 votes vote down vote up
@Test
public void testWrite() throws XMLStreamException, IOException, SAXException {
    final Document doc = loadDocument("/foobar.xml");

    final DOMResult domResult = new DOMResult(UntrustedXML.newDocumentBuilder().newDocument());

    final XMLStreamWriter xmlStreamWriter = factory.createXMLStreamWriter(domResult);

    final NormalizedNodeStreamWriter schemalessXmlNormalizedNodeStreamWriter =
            XMLStreamNormalizedNodeStreamWriter.createSchemaless(xmlStreamWriter);

    final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(
            schemalessXmlNormalizedNodeStreamWriter);

    normalizedNodeWriter.write(buildOuterContainerNode());

    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setNormalize(true);

    final String expectedXml = toString(doc.getDocumentElement());
    final String serializedXml = toString(domResult.getNode());
    final Diff diff = new Diff(expectedXml, serializedXml);

    final DifferenceListener differenceListener = new IgnoreTextAndAttributeValuesDifferenceListener();
    diff.overrideDifferenceListener(differenceListener);

    XMLAssert.assertXMLEqual(diff, true);
}