org.custommonkey.xmlunit.DifferenceListener Java Examples

The following examples show how to use org.custommonkey.xmlunit.DifferenceListener. 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: ODataXmlSerializerTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public int differenceFound(Difference difference) {
  final String xpath = "/updated[1]/text()[1]";
  if(difference.getControlNodeDetail().getXpathLocation().endsWith(xpath)) {
    String controlValue = difference.getControlNodeDetail().getValue();
    String testValue = difference.getTestNodeDetail().getValue();
    // Allow a difference of up to 2 seconds.
    try {
      long controlTime = UPDATED_FORMAT.parse(controlValue).getTime();
      long testTime = UPDATED_FORMAT.parse(testValue).getTime();
      long diff = controlTime - testTime;
      if (diff < 0) {
        diff = diff * -1;
      }
      if (diff <= MAX_ALLOWED_UPDATED_DIFFERENCE) {
        return DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR;
      }
    } catch (ParseException e) {
      throw new RuntimeException("Parse exception for updated value (see difference '" + difference + "').");
    }
  }
  // Yes it is a difference so throw an exception.
  return DifferenceListener.RETURN_ACCEPT_DIFFERENCE;
}
 
Example #2
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 #3
Source File: FloatingPointTolerantDifferenceListener.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
protected int textualDifference(Difference d) {
    String control = d.getControlNodeDetail().getValue();
    String test = d.getTestNodeDetail().getValue();
    if (control != null && test != null) {
        try {
            double controlVal = Double.parseDouble(control);
            double testVal = Double.parseDouble(test);
            return Math.abs(controlVal - testVal) <= tolerance
                ? DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL
                : DifferenceListener.RETURN_ACCEPT_DIFFERENCE;
        } catch (NumberFormatException nfe) {
            // ignore, delegate to nested DifferenceListener
        }
    }
    // no numbers or null, delegate
    return super.textualDifference(d);
}
 
Example #4
Source File: IgnoreWhiteCharsDiffListener.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public int differenceFound(Difference diff) {

    if (diff.getId() == DifferenceConstants.TEXT_VALUE.getId()) {
        String control = diff.getControlNodeDetail().getValue();
        if (control != null) {
            control = control.trim();
            if (diff.getTestNodeDetail().getValue() != null
                && control.equals(diff.getTestNodeDetail().getValue().trim())) {
                return
                    DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR;
            }
        }
    }
    return RETURN_ACCEPT_DIFFERENCE;
}
 
Example #5
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 #6
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 #7
Source File: CaseInsensitiveDifferenceListener.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
protected int textualDifference(Difference d) {
    String control = d.getControlNodeDetail().getValue();
    if (control != null) {
        control = control.toLowerCase(Locale.US);
        if (d.getTestNodeDetail().getValue() != null
            && control.equals(d.getTestNodeDetail().getValue()
                              .toLowerCase(Locale.US))) {
            return
                DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
        }
    }
    // some string is null, delegate
    return super.textualDifference(d);
}
 
Example #8
Source File: ExtendedJAXBEqualsStrategy.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected boolean equalsInternal(ObjectLocator leftLocator,
		ObjectLocator rightLocator, Node lhs, Node rhs) {
	final Diff diff = new Diff(new DOMSource(lhs), new DOMSource(rhs)) {
		@Override
		public int differenceFound(Difference difference) {
			if (difference.getId() == DifferenceConstants.NAMESPACE_PREFIX_ID) {
				return DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
			} else {
				return super.differenceFound(difference);
			}
		}
	};
	return diff.identical();
}
 
Example #9
Source File: CustomDifferenceListener.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
@Override
public int differenceFound(Difference difference) {
  switch (difference.getId()) {
    case DifferenceConstants.NAMESPACE_URI_ID:
      return namespaceDifferenceFound(difference);
    case DifferenceConstants.ELEMENT_NUM_ATTRIBUTES_ID:
    case DifferenceConstants.ATTR_NAME_NOT_FOUND_ID:
      return attributeDifferenceFound(difference);
    default:
      return DifferenceListener.RETURN_ACCEPT_DIFFERENCE;
  }
}
 
Example #10
Source File: CustomDifferenceListener.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Checks for logical equivalence of the qualified node names.
 */
private int namespaceDifferenceFound(Difference difference) {
  Node controlNode = difference.getControlNodeDetail().getNode();
  Node testNode = difference.getTestNodeDetail().getNode();
  String controlNs = getNamespaceURI(controlNode);
  String testNs = getNamespaceURI(testNode);
  if (Objects.equal(controlNs, testNs)) {
    if (Objects.equal(controlNode.getLocalName(), testNode.getLocalName())) {
      return DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR;
    }
  }
  return DifferenceListener.RETURN_ACCEPT_DIFFERENCE;
}
 
Example #11
Source File: CustomDifferenceListener.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Ignores differences that are only due to missing xsi:type.
 */
private int attributeDifferenceFound(Difference difference) {
  NamedNodeMap controlAttributes = difference.getControlNodeDetail().getNode().getAttributes();
  NamedNodeMap testAttributes = difference.getTestNodeDetail().getNode().getAttributes();
  Map<QName, Node> controlAttributesMap = createAttributesMapExcludingXsiType(controlAttributes);
  Map<QName, Node> testAttributesMap = createAttributesMapExcludingXsiType(testAttributes);
  if (controlAttributesMap.size() != testAttributesMap.size()) {
    return DifferenceListener.RETURN_ACCEPT_DIFFERENCE;
  }
  return DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR;
}
 
Example #12
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 #13
Source File: FloatingPointTolerantDifferenceListener.java    From xmlunit with Apache License 2.0 4 votes vote down vote up
public FloatingPointTolerantDifferenceListener(DifferenceListener delegateTo,
                                               double tolerance) {
    super(delegateTo);
    this.tolerance = tolerance;
}
 
Example #14
Source File: CaseInsensitiveDifferenceListener.java    From xmlunit with Apache License 2.0 4 votes vote down vote up
public CaseInsensitiveDifferenceListener(DifferenceListener delegateTo) {
    super(delegateTo);
}
 
Example #15
Source File: TextDifferenceListenerBase.java    From xmlunit with Apache License 2.0 4 votes vote down vote up
protected TextDifferenceListenerBase(DifferenceListener delegateTo) {
    this.delegateTo = delegateTo;
}
 
Example #16
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 #17
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 #18
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);
}