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

The following examples show how to use org.custommonkey.xmlunit.Diff#overrideElementQualifier() . 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: XsdGeneratorHelperTest.java    From jaxb2-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void validateProcessingNodes()
{

    // Assemble
    final String newPrefix = "changedFoo";
    final String oldPrefix = "foo";
    final String originalXml = getXmlDocumentSample( oldPrefix );
    final String changedXml = getXmlDocumentSample( newPrefix );
    final NodeProcessor changeNamespacePrefixProcessor = new ChangeNamespacePrefixProcessor( oldPrefix, newPrefix );

    // Act
    final Document processedDocument = XsdGeneratorHelper.parseXmlStream( new StringReader( originalXml ) );
    XsdGeneratorHelper.process( processedDocument.getFirstChild(), true, changeNamespacePrefixProcessor );

    // Assert
    final Document expectedDocument = XsdGeneratorHelper.parseXmlStream( new StringReader( changedXml ) );
    final Diff diff = new Diff( expectedDocument, processedDocument, null, new ElementNameAndAttributeQualifier() );
    diff.overrideElementQualifier( new ElementNameAndAttributeQualifier() );

    XMLAssert.assertXMLEqual( processedDocument, expectedDocument );
}
 
Example 2
Source File: test_RecursiveElementNameAndTextQualifier.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
public void testUserGuideExample() throws Exception {
    String control =
        "<table>\n"
        + "  <tr>\n"
        + "    <td>foo</td>\n"
        + "  </tr>\n"
        + "  <tr>\n"
        + "    <td>bar</td>\n"
        + "  </tr>\n"
        + "</table>\n";
    String test =
        "<table>\n"
        + "  <tr>\n"
        + "    <td>bar</td>\n"
        + "  </tr>\n"
        + "  <tr>\n"
        + "    <td>foo</td>\n"
        + "  </tr>\n"
        + "</table>\n";

    Diff d = new Diff(control, test);
    d.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
    assertTrue(d.toString(), d.similar());
}
 
Example 3
Source File: PersistenceXmlTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception
 */
public void testPersistenceVersion1() throws Exception {
    final JAXBContext ctx = JAXBContextFactory.newInstance(Persistence.class);
    final Unmarshaller unmarshaller = ctx.createUnmarshaller();

    final URL resource = this.getClass().getClassLoader().getResource("persistence-example.xml");
    final InputStream in = resource.openStream();
    final java.lang.String expected = readContent(in);

    final Persistence element = (Persistence) unmarshaller.unmarshal(new ByteArrayInputStream(expected.getBytes()));
    unmarshaller.setEventHandler(new TestValidationEventHandler());
    System.out.println("unmarshalled");

    final Marshaller marshaller = ctx.createMarshaller();
    marshaller.setProperty("jaxb.formatted.output", true);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    marshaller.marshal(element, baos);

    final String actual = new String(baos.toByteArray());

    final Diff myDiff = new Diff(expected, actual);
    myDiff.overrideElementQualifier(new ElementNameAndAttributeQualifier());
    assertTrue("Files are similar " + myDiff, myDiff.similar());
}
 
Example 4
Source File: PersistenceXmlTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception
 */
public void testPersistenceVersion2() throws Exception {
    final JAXBContext ctx = JAXBContextFactory.newInstance(Persistence.class);
    final Unmarshaller unmarshaller = ctx.createUnmarshaller();

    final URL resource = this.getClass().getClassLoader().getResource("persistence_2.0-example.xml");
    final InputStream in = resource.openStream();
    final java.lang.String expected = readContent(in);

    final Persistence element = (Persistence) unmarshaller.unmarshal(new ByteArrayInputStream(expected.getBytes()));
    unmarshaller.setEventHandler(new TestValidationEventHandler());
    System.out.println("unmarshalled");

    final Marshaller marshaller = ctx.createMarshaller();
    marshaller.setProperty("jaxb.formatted.output", true);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    marshaller.marshal(element, baos);

    final String actual = new String(baos.toByteArray());

    final Diff myDiff = new Diff(expected, actual);
    myDiff.overrideElementQualifier(new ElementNameAndAttributeQualifier());
    assertTrue("Files are similar " + myDiff, myDiff.similar());
}
 
Example 5
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 6
Source File: XmlAsserts.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private static void doAssertXmlEquals(String expectedXml, String actualXml) throws Exception {
    Diff diff = new Diff(expectedXml, actualXml);
    diff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
    if (!diff.similar()) {
        fail("\nExpected the following XML\n" + formatXml(expectedXml) +
             "\nbut actual XML was\n\n" +
             formatXml(actualXml));
    }
}
 
Example 7
Source File: AtomTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
protected void assertSimilar(final String filename, final String actual, 
    boolean isServerMode) throws Exception {
  final Diff diff = new Diff(cleanup(IOUtils.toString(getClass().getResourceAsStream(filename))), actual);
  diff.overrideElementQualifier(new AtomLinksQualifier());
  assertTrue(diff.similar());
}
 
Example 8
Source File: AbstractYinExportTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
private static void assertXMLEquals(final String fileName, final Document expectedXMLDoc, final String output)
        throws SAXException, IOException {
    final String expected = YinExportTestUtils.toString(expectedXMLDoc.getDocumentElement());

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

    final Diff diff = new Diff(expected, output);
    diff.overrideElementQualifier(new ElementNameAndAttributeQualifier());
    XMLAssert.assertXMLEqual(fileName, diff, true);
}
 
Example 9
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 10
Source File: XsdGeneratorHelperTest.java    From jaxb2-maven-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void validateProcessingXSDsWithEnumerations() throws Exception
{

    // Assemble
    final BufferingLog log = new BufferingLog();
    final JavaDocExtractor extractor = new JavaDocExtractor( log );
    extractor.setEncoding( "UTF-8" );

    final String parentPath = "testdata/schemageneration/javadoc/enums/";
    final URL parentPathURL = getClass().getClassLoader().getResource( parentPath );
    Assert.assertNotNull( parentPathURL );

    final File parentDir = new File( parentPathURL.getPath() );
    Assert.assertTrue( parentDir.exists() && parentDir.isDirectory() );

    final List<Filter<File>> excludeFilesMatching = new ArrayList<Filter<File>>();
    excludeFilesMatching.add( new PatternFileFilter( Collections.singletonList( "\\.xsd" ) ) );
    Filters.initialize( log, excludeFilesMatching );

    final List<File> allSourceFiles = FileSystemUtilities.filterFiles( parentDir, null, parentDir.getAbsolutePath(),
            log, "allJavaFiles", excludeFilesMatching );
    Assert.assertEquals( 3, allSourceFiles.size() );

    final List<URL> urls = new ArrayList<URL>();
    for ( File current : allSourceFiles )
    {
        try
        {
            urls.add( current.toURI().toURL() );
        }
        catch ( MalformedURLException e )
        {
            throw new IllegalArgumentException(
                    "Could not convert file [" + current.getAbsolutePath() + "] to a URL", e );
        }
    }
    Assert.assertEquals( 3, urls.size() );

    extractor.addSourceURLs( urls );
    final SearchableDocumentation docs = extractor.process();

    // #1) The raw / un-processed XSD (containing the 'before' state)
    // #2) The processed XSD (containing the 'expected' state)
    final String rawEnumSchema = PropertyResources.readFully( parentPath + "rawEnumSchema.xsd" );
    final String processedEnumSchema = PropertyResources.readFully( parentPath + "processedEnumSchema.xsd" );
    final NodeProcessor enumProcessor = new XsdEnumerationAnnotationProcessor( docs,
            new NoAuthorJavaDocRenderer() );

    // Act
    final Document processedDocument = XsdGeneratorHelper.parseXmlStream( new StringReader( rawEnumSchema ) );
    XsdGeneratorHelper.process( processedDocument.getFirstChild(), true, enumProcessor );
    // System.out.println("Got: " + AbstractSourceCodeAwareNodeProcessingTest.printDocument(processedDocument));

    // Assert
    final Document expectedDocument = XsdGeneratorHelper.parseXmlStream( new StringReader( processedEnumSchema ) );
    final Diff diff = new Diff( expectedDocument, processedDocument, null, new ElementNameAndAttributeQualifier() );
    diff.overrideElementQualifier( new ElementNameAndAttributeQualifier() );

    XMLAssert.assertXMLEqual( processedDocument, expectedDocument );
}
 
Example 11
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 12
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 13
Source File: test_RecursiveElementNameAndTextQualifier.java    From xmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * @see <a href="https://sourceforge.net/forum/forum.php?thread_id=2948005&amp;forum_id=73273"/>
 */
public void testOpenDiscussionThread2948995_1() throws Exception {
    Diff myDiff = new Diff("<root>"
                           + "  <ent>"
                           + "    <value>"
                           + "      <int>1</int>"
                           + "    </value>"
                           + "    <value>"
                           + "      <int>2</int>"
                           + "    </value>"
                           + "  </ent>"
                           + "  <ent>"
                           + "    <value>"
                           + "      <int>3</int>"
                           + "    </value>"
                           + "    <value>"
                           + "      <int>4</int>"
                           + "    </value>"
                           + "  </ent>"
                           + "</root>",
                           "<root>"
                           + "  <ent>"
                           + "    <value>"
                           + "      <int>2</int>"
                           + "    </value>"
                           + "    <value>"
                           + "      <int>1</int>"
                           + "    </value>"
                           + "  </ent>"
                           + "  <ent>"
                           + "    <value>"
                           + "      <int>3</int>"
                           + "    </value>"
                           + "    <value>"
                           + "      <int>4</int>"
                           + "    </value>"
                           + "  </ent>"
                           + "</root>");
    myDiff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier()); 
    XMLAssert.assertXMLEqual("Not similar", myDiff, true); 
}
 
Example 14
Source File: test_RecursiveElementNameAndTextQualifier.java    From xmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * @see <a href="https://sourceforge.net/forum/forum.php?thread_id=2948005&amp;forum_id=73273"/>
 */
public void testOpenDiscussionThread2948995_2() throws Exception {
    Diff myDiff = new Diff("<root>"
                           + "  <ent>"
                           + "    <value>"
                           + "      <int>1</int>"
                           + "    </value>"
                           + "    <value>"
                           + "      <int>2</int>"
                           + "    </value>"
                           + "  </ent>"
                           + "  <ent>"
                           + "    <value>"
                           + "      <int>3</int>"
                           + "    </value>"
                           + "    <value>"
                           + "      <int>4</int>"
                           + "    </value>"
                           + "  </ent>"
                           + "</root>",
                           "<root>"
                           + "  <ent>"
                           + "    <value>"
                           + "      <int>1</int>"
                           + "    </value>"
                           + "    <value>"
                           + "      <int>2</int>"
                           + "    </value>"
                           + "  </ent>"
                           + "  <ent>"
                           + "    <value>"
                           + "      <int>4</int>"
                           + "    </value>"
                           + "    <value>"
                           + "      <int>3</int>"
                           + "    </value>"
                           + "  </ent>"
                           + "</root>");
    myDiff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier()); 
    XMLAssert.assertXMLEqual("Not similar", myDiff, true); 
}
 
Example 15
Source File: MetadataResourceTest.java    From oodt with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that {@link MetadataResource metadata resources} are marshalled to
 * the expected XML format.
 * @throws IOException if the {@link Diff} constructor fails
 * @throws JAXBException if the {@link JAXBContext} or {@link Marshaller} fail
 * @throws SAXException if the {@link Diff} constructor fails
 */
@Test
public void testXmlMarshalling() throws IOException, JAXBException,
  SAXException
{
  // Generate the expected output.
  String expectedXml =
    "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
    + "<metadata>"
    + "<keyval><key>1</key><val>one</val></keyval>"
    + "<keyval><key>2</key><val>two</val></keyval>"
    + "<keyval><key>3</key><val>three</val></keyval>"
    + "<keyval><key>4</key><val>a</val><val>b</val><val>c</val></keyval>"
    + "</metadata>";

  // Create a MetadataResource using a Metadata instance.
  Hashtable metadataEntries = new Hashtable<String, Object>();
  metadataEntries.put("1", "one");
  metadataEntries.put("2", "two");
  metadataEntries.put("3", "three");
  List<String> list = new ArrayList<String>();
  list.add("a");
  list.add("b");
  list.add("c");
  metadataEntries.put("4", list);

  Metadata metadata = new Metadata();
  metadata.addMetadata(metadataEntries);
  MetadataResource resource = new MetadataResource(metadata);


  // Set up a JAXB context and marshall the ReferenceResource to XML.
  JAXBContext context = JAXBContext.newInstance(resource.getClass());
  Marshaller marshaller = context.createMarshaller();
  StringWriter writer = new StringWriter();
  marshaller.marshal(resource, writer);

  // Compare the expected and actual outputs.
  XMLUnit.setIgnoreWhitespace(true);
  XMLUnit.setIgnoreComments(true);
  XMLUnit.setIgnoreAttributeOrder(true);
  Diff diff = new Diff(expectedXml, writer.toString());
  diff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
  assertTrue("The output XML was different to the expected XML: "
    + diff.toString(), diff.similar());
}