org.custommonkey.xmlunit.Diff Java Examples

The following examples show how to use org.custommonkey.xmlunit.Diff. 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: SxmpWriterTest.java    From cloudhopper-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void writeDeliveryReportResponse() throws Exception {
    DeliveryReportResponse deliveryResponse = new DeliveryReportResponse();
    deliveryResponse.setErrorCode(5);
    deliveryResponse.setErrorMessage("Success");

    StringWriter sw = new StringWriter();
    SxmpWriter.write(sw, deliveryResponse);

    logger.debug(sw.toString());

    StringBuilder expectedXML = new StringBuilder(200)
        .append("<?xml version=\"1.0\"?>\n")
        .append("<operation type=\"deliveryReport\">\n")
        .append(" <deliveryReportResponse>\n")
        .append("   <error code=\"5\" message=\"Success\"/>\n")
        .append(" </deliveryReportResponse>\n")
        .append("</operation>\n")
        .append("");

    // compare to actual correct submit response
    XMLUnit.setIgnoreWhitespace(true);
    Diff myDiff = new Diff(expectedXML.toString(), sw.toString());
    DetailedDiff myDetailedDiff = new DetailedDiff(myDiff);
    Assert.assertTrue("XML are similar " + myDetailedDiff, myDetailedDiff.similar());
}
 
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: 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 #4
Source File: SchemaOrderedNormalizedNodeWriterTest.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testWriteOrder() throws XMLStreamException, IOException, SAXException {
    final StringWriter stringWriter = new StringWriter();
    final XMLStreamWriter xmlStreamWriter = factory.createXMLStreamWriter(stringWriter);
    SchemaContext schemaContext = getSchemaContext("/bug1848/order.yang");
    NormalizedNodeStreamWriter writer = XMLStreamNormalizedNodeStreamWriter.create(xmlStreamWriter, schemaContext);

    try (NormalizedNodeWriter nnw = new SchemaOrderedNormalizedNodeWriter(writer, schemaContext, SchemaPath.ROOT)) {

        DataContainerChild<?, ?> cont = Builders.containerBuilder()
                .withNodeIdentifier(getNodeIdentifier(ORDER_NAMESPACE, "cont"))
                .withChild(ImmutableNodes.leafNode(createQName(ORDER_NAMESPACE, "content"), "content1"))
                .build();

        NormalizedNode<?, ?> root = Builders.containerBuilder()
                .withNodeIdentifier(getNodeIdentifier(ORDER_NAMESPACE, "root"))
                .withChild(cont)
                .withChild(ImmutableNodes.leafNode(createQName(ORDER_NAMESPACE, "id"), "id1"))
                .build();

        nnw.write(root);
    }

    XMLAssert.assertXMLIdentical(new Diff(EXPECTED_2, stringWriter.toString()), true);
}
 
Example #5
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 #6
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 #7
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 #8
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 #9
Source File: SplitterTest.java    From edireader with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testTwoInterchangeTwoDocumentsEachIntoDOMs() throws Exception {
    String ansiInterchange = EDITestData.getAnsiInterchange(2);
    ansiInterchange = ansiInterchange + ansiInterchange;
    inputReader = new StringReader(ansiInterchange);
    MyDomHandlerFactory factory = new MyDomHandlerFactory();
    new SplittingHandler(factory).split(new InputSource(inputReader));

    assertEquals(4, factory.getCreateCalls());
    assertEquals(1328, factory.getSAXEventsWritten());

    factory.shutdown();

    Document controlDom = generateDOM(EDITestData.getAnsiInputSource());
    Diff diff = new Diff(controlDom, factory.getDom());
    boolean identical = diff.identical();
    if (!identical) {
        fail(diff.toString());
    }
}
 
Example #10
Source File: XmlCombinerTest.java    From xml-combiner with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldWorkWithCustomIdAttribute2() throws IOException, SAXException, ParserConfigurationException,
		TransformerException {
	String recessive = "\n"
			+ "<config>\n"
			+ "    <nested>\n"
			+ "        <service name='a'>\n"
			+ "            <parameter>old value2</parameter>\n"
			+ "        </service>\n"
			+ "    </nested>\n"
			+ "</config>";
	String dominant = "\n"
			+ "<config>\n"
			+ "    <nested>\n"
			+ "        <service name='a'>\n"
			+ "            <parameter>new value</parameter>\n"
			+ "        </service>\n"
			+ "    </nested>\n"
			+ "</config>";
	String result = dominant;

	assertXMLIdentical(new Diff(result, combineWithKey("name", recessive, dominant)), true);
}
 
Example #11
Source File: SxmpWriterTest.java    From cloudhopper-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void writeDeliverResponse() throws Exception {
    DeliverResponse deliverResponse = new DeliverResponse();
    deliverResponse.setErrorCode(5);
    deliverResponse.setErrorMessage("Success");

    StringWriter sw = new StringWriter();
    SxmpWriter.write(sw, deliverResponse);

    logger.debug(sw.toString());

    StringBuilder expectedXML = new StringBuilder(200)
        .append("<?xml version=\"1.0\"?>\n")
        .append("<operation type=\"deliver\">\n")
        .append(" <deliverResponse>\n")
        .append("   <error code=\"5\" message=\"Success\"/>\n")
        .append(" </deliverResponse>\n")
        .append("</operation>\n")
        .append("");

    // compare to actual correct submit response
    XMLUnit.setIgnoreWhitespace(true);
    Diff myDiff = new Diff(expectedXML.toString(), sw.toString());
    DetailedDiff myDetailedDiff = new DetailedDiff(myDiff);
    Assert.assertTrue("XML are similar " + myDetailedDiff, myDetailedDiff.similar());
}
 
Example #12
Source File: TckValidator.java    From juddi with Apache License 2.0 6 votes vote down vote up
public static void checkKeyInfo(KeyInfoType kit1, KeyInfoType kit2) {
    if (kit1 == null || kit2 == null) {
            assertEquals(kit1, kit2);
            return;
    }
    assertEquals(kit1.getId(), kit2.getId());

    DOMResult domResult1 = new DOMResult();
    DOMResult domResult2 = new DOMResult();
    JAXB.marshal(kit1, domResult1);
    JAXB.marshal(kit2, domResult2);
    
    Document doc1 = (Document)domResult1.getNode();
    DOMSource domSource1 = new DOMSource(doc1.getDocumentElement());
    Document doc2 = (Document)domResult2.getNode();
    DOMSource domSource2 = new DOMSource(doc2.getDocumentElement());
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setIgnoreComments(true);
    XMLUnit.setIgnoreWhitespace(true);
    Diff diff = new Diff(domSource1, domSource2);
    assertTrue("Key info elements should match", diff.similar());
}
 
Example #13
Source File: JaxbWlsTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
public void marshallAndUnmarshall(final String xmlFile) throws Exception {

        final InputStream in = this.getClass().getClassLoader().getResourceAsStream(xmlFile);
        final String expected = readContent(in);

        final Object object = JaxbWls.unmarshal(WeblogicEjbJar.class, new ByteArrayInputStream(expected.getBytes()));

        final JAXBElement element = (JAXBElement) object;

        assertTrue(element.getValue() instanceof WeblogicEjbJar);

        final String actual = JaxbWls.marshal(WeblogicEjbJar.class, element);

        XMLUnit.setIgnoreWhitespace(true);
        try {
            final Diff myDiff = new DetailedDiff(new Diff(expected, actual));
            assertTrue("Files are not similar " + myDiff, myDiff.similar());
        } catch (final AssertionFailedError e) {
            assertEquals(expected, actual);
            throw e;
        }
    }
 
Example #14
Source File: XmlCombinerTest.java    From xml-combiner with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleChildren() throws SAXException, IOException, ParserConfigurationException,
		TransformerException {
	String recessive = "\n"
			+ "<config>\n"
			+ "    <service id='1'>\n"
			+ "        <parameter>parameter</parameter>\n"
			+ "        <parameter9>parameter2</parameter9>\n"
			+ "        <parameter3>parameter3</parameter3>\n"
			+ "    </service>\n"
			+ "</config>";
	String dominant = "\n"
			+ "<config>\n"
			+ "    <service id='1'>\n"
			+ "    </service>\n"
			+ "</config>";
	String result = "\n"
			+ "<config>\n"
			+ "    <service id='1'>\n"
			+ "        <parameter>parameter</parameter>\n"
			+ "        <parameter9>parameter2</parameter9>\n"
			+ "        <parameter3>parameter3</parameter3>\n"
			+ "    </service>\n"
			+ "</config>";
	assertXMLIdentical(new Diff(result, combineWithIdKey(recessive, dominant)), true);
}
 
Example #15
Source File: XmlCombinerTest.java    From xml-combiner with Apache License 2.0 6 votes vote down vote up
@Test
public void override() throws SAXException, IOException, ParserConfigurationException,
		TransformerConfigurationException, TransformerException {
	String recessive = "\n"
			+ "<config>\n"
			+ "    <service id='1'>\n"
			+ "        <parameter>parameter</parameter>\n"
			+ "        <parameter2>parameter2</parameter2>\n"
			+ "    </service>\n"
			+ "</config>";
	String dominant = "\n"
			+ "<config>\n"
			+ "    <service id='1' combine.self='override'>\n"
			+ "        <parameter>other value</parameter>\n"
			+ "        <parameter3>parameter3</parameter3>\n"
			+ "    </service>\n"
			+ "</config>";
	String result = "\n"
			+ "<config>\n"
			+ "    <service id='1'>\n"
			+ "        <parameter>other value</parameter>\n"
			+ "        <parameter3>parameter3</parameter3>\n"
			+ "    </service>\n"
			+ "</config>";
	assertXMLIdentical(new Diff(result, combineWithIdKey(recessive, dominant)), true);
}
 
Example #16
Source File: XmlCombinerTest.java    From xml-combiner with Apache License 2.0 6 votes vote down vote up
@Test
public void attributes() throws SAXException, IOException, ParserConfigurationException,
		TransformerConfigurationException, TransformerException {
	String recessive = "\n"
			+ "<config>\n"
			+ "    <service id='1' parameter='parameter' parameter2='parameter2'/>\n"
			+ "</config>";
	String dominant = "\n"
			+ "<config>\n"
			+ "    <service id='1' parameter='other value' parameter3='parameter3'/>\n"
			+ "</config>";
	String result = "\n"
			+ "<config>\n"
			+ "    <service id='1' parameter='other value' parameter2='parameter2' parameter3='parameter3'/>\n"
			+ "</config>";
	assertXMLIdentical(new Diff(result, combineWithIdKey(recessive, dominant)), true);
}
 
Example #17
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 #18
Source File: YT1108Test.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testLeafOfUnionWithIdentityRefNNToXmlSerialization()
        throws XMLStreamException, IOException, SAXException {
    final Document doc = loadDocument("/yt1108/xml/foo-leaf-of-union-with-identity-ref-type.xml");
    final DOMResult domResult = convertNormalizedNodeToXml(buildLeafContainerNodeWithUnionIdentityRefLeaf());

    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);

    new XMLTestCase() {}.assertXMLEqual(diff, true);
}
 
Example #19
Source File: XSD.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Override
public int compareTo(XSD x) {
	if (x == null) return 1;
	if (namespace != null && x.namespace != null) {
		int c = namespace.compareTo(x.namespace);
		if (c != 0) return c;
	}
	if (wsdlSchema != null || url == null || (url.toString().compareTo(x.url.toString()) != 0)) {
		// Compare XSD content to prevent copies of the same XSD showing up
		// more than once in the WSDL. For example the
		// CommonMessageHeader.xsd used by the EsbSoapValidator will
		// normally also be imported by the XSD for the business response
		// message (for the Result part).
		try {
			InputSource control = new InputSource(getInputStream());
			InputSource test = new InputSource(x.getInputStream());
			Diff diff = new Diff(control, test);
			if (diff.similar()) {
				return 0;
			} else if (wsdlSchema != null || url == null) {
				return Misc.streamToString(getInputStream(), "\n", false).compareTo(Misc.streamToString(x.getInputStream(), "\n", false));
			}
		} catch (Exception e) {
			LOG.warn("Exception during XSD compare", e);
		}
	}
	return url.toString().compareTo(x.url.toString());
}
 
Example #20
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 #21
Source File: SxmpWriterTest.java    From cloudhopper-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void writeDeliveryReportRequest0() throws Exception {
    DeliveryReportRequest request = new DeliveryReportRequest();
    request.setAccount(new Account("customer1", "test1"));
    //request.setOperatorId(20);
    request.setReferenceId("TESTREF");
    request.setStatus(new DeliveryStatus(5, "Expired"));
    request.setTicketId("000:20090118002220948:000");
    //request.setSourceAddress(new MobileAddress(MobileAddress.Type.NETWORK, "40404"));
    //request.setDestinationAddress(new MobileAddress(MobileAddress.Type.INTERNATIONAL, "+13135551212"));
    //request.setText("Hello World");

    StringWriter sw = new StringWriter();
    SxmpWriter.write(sw, request);

    logger.debug(sw.toString());

    StringBuilder expectedXML = new StringBuilder(200)
        .append("<?xml version=\"1.0\"?>\n")
        .append("<operation type=\"deliveryReport\">\n")
        .append(" <account username=\"customer1\" password=\"test1\"/>\n")
        .append(" <deliveryReportRequest referenceId=\"TESTREF\">\n")
        .append("   <status code=\"5\" message=\"Expired\"/>\n")
        .append("   <ticketId>000:20090118002220948:000</ticketId>\n")
        .append(" </deliveryReportRequest>\n")
        .append("</operation>\n")
        .append("");

    // compare to actual correct submit response
    XMLUnit.setIgnoreWhitespace(true);
    Diff myDiff = new Diff(expectedXML.toString(), sw.toString());
    DetailedDiff myDetailedDiff = new DetailedDiff(myDiff);
    Assert.assertTrue("XML are similar " + myDetailedDiff, myDetailedDiff.similar());
}
 
Example #22
Source File: XmlCombinerTest.java    From xml-combiner with Apache License 2.0 5 votes vote down vote up
@Test
public void overridableByTag() throws SAXException, IOException, ParserConfigurationException,
		TransformerException {
	String recessive = "\n"
			+ "<config>\n"
			+ "    <service id='id1' combine.self='overridable_by_tag'>\n"
			+ "        <test/>\n"
			+ "    </service>\n"
			+ "</config>";
	String dominant = "\n"
			+ "<config>\n"
			+ "</config>";
	String result = "\n"
			+ "<config>\n"
			+ "    <service id='id1'>\n"
			+ "        <test/>\n"
			+ "    </service>\n"
			+ "</config>";
	String dominant2 = "\n"
			+ "<config>\n"
			+ "    <service id='id1'/>\n"
			+ "</config>";
	String dominant3 = "\n"
			+ "<config>\n"
			+ "    <service id='id2'/>\n"
			+ "</config>";

	assertXMLIdentical(new Diff(result, combineWithIdKey(recessive, dominant)), true);
	assertXMLIdentical(new Diff(dominant2, combineWithIdKey(recessive, dominant2)), true);
	assertXMLIdentical(new Diff(dominant3, combineWithIdKey(recessive, dominant3)), true);
}
 
Example #23
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 #24
Source File: XmlCombinerTest.java    From xml-combiner with Apache License 2.0 5 votes vote down vote up
@Test
public void defaults() throws SAXException, IOException, ParserConfigurationException, TransformerException {
	String recessive = "\n"
			+ "<config>\n"
			+ "    <service id='1' combine.self='DEFAULTS'>\n"
			+ "        <parameter>parameter</parameter>\n"
			+ "        <parameter9>parameter2</parameter9>\n"
			+ "        <parameter3>parameter3</parameter3>\n"
			+ "    </service>\n"
			+ "    <service id='2' combine.self='DEFAULTS'>\n"
			+ "        <parameter>parameter</parameter>\n"
			+ "        <parameter2>parameter2</parameter2>\n"
			+ "    </service>\n"
			+ "</config>";
	String dominant = "\n"
			+ "<config>\n"
			+ "    <service id='2'>\n"
			+ "    </service>\n"
			+ "</config>";
	String result = "\n"
			+ "<config>\n"
			+ "    <service id='2'>\n"
			+ "        <parameter>parameter</parameter>\n"
			+ "        <parameter2>parameter2</parameter2>\n"
			+ "    </service>\n"
			+ "</config>";
	assertXMLIdentical(new Diff(result, combineWithIdKey(recessive, dominant)), true);
}
 
Example #25
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 #26
Source File: SxmpWriterTest.java    From cloudhopper-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void writeSubmitRequestWithLongPushDestination() throws Exception {
    SubmitRequest request = new SubmitRequest(SxmpParser.VERSION_1_1);
    request.setAccount(new Account("customer1", "test1"));
    request.setOperatorId(20);
    request.setDestinationAddress(new MobileAddress(MobileAddress.Type.PUSH_DESTINATION, "abcd1234fghi 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"));
    request.setText("Hello World");

    StringWriter sw = new StringWriter();
    SxmpWriter.write(sw, request);

    logger.debug(sw.toString());

    StringBuilder expectedXML = new StringBuilder(200)
        .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
        .append("<operation type=\"submit\">\n")
        .append(" <account username=\"customer1\" password=\"test1\"/>\n")
        .append(" <submitRequest>\n")
        .append("  <operatorId>20</operatorId>\n")
        .append("  <priority>0</priority>\n")
        .append("  <deliveryReport>false</deliveryReport>\n")
        .append("  <destinationAddress type=\"push_destination\">abcd1234fghi 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789</destinationAddress>\n")
        .append("  <text encoding=\"UTF-8\">48656C6C6F20576F726C64</text>\n")
        .append(" </submitRequest>\n")
        .append("</operation>\n")
        .append("");

    // compare to actual correct submit response
    XMLUnit.setIgnoreWhitespace(true);
    Diff myDiff = new Diff(expectedXML.toString(), sw.toString());
    DetailedDiff myDetailedDiff = new DetailedDiff(myDiff);
    Assert.assertTrue("XML are similar " + myDetailedDiff, myDetailedDiff.similar());
    // guarantee there's no optionalParams entry
    Assert.assertTrue(!expectedXML.toString().contains("optionalParams"));
}
 
Example #27
Source File: SxmpWriterTest.java    From cloudhopper-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void writeSubmitRequestWithUnicodeCharsInUTF8() throws Exception {
    SubmitRequest request = new SubmitRequest();
    request.setAccount(new Account("customer1", "test1"));
    request.setOperatorId(20);
    request.setReferenceId("TESTREF");
    request.setSourceAddress(new MobileAddress(MobileAddress.Type.NETWORK, "40404"));
    request.setDestinationAddress(new MobileAddress(MobileAddress.Type.INTERNATIONAL, "+13135551212"));
    request.setTextEncoding(TextEncoding.UTF_8);
    String text = "\u20AC\u0623\u0647\u0644\u0627\u0020\u0647\u0630\u0647\u0020\u0627\u0644\u062a\u062c\u0631\u0628\u0629\u0020\u0627\u0644\u0623\u0648\u0644\u0649";
    request.setText(text);

    StringWriter sw = new StringWriter();
    SxmpWriter.write(sw, request);

    logger.debug(sw.toString());

    StringBuilder expectedXML = new StringBuilder(200)
        .append("<?xml version=\"1.0\"?>\n")
        .append("<operation type=\"submit\">\n")
        .append(" <account username=\"customer1\" password=\"test1\"/>\n")
        .append(" <submitRequest referenceId=\"TESTREF\">\n")
        .append("  <operatorId>20</operatorId>\n")
        .append("  <priority>0</priority>\n")
        .append("  <deliveryReport>false</deliveryReport>\n")
        .append("  <sourceAddress type=\"network\">40404</sourceAddress>\n")
        .append("  <destinationAddress type=\"international\">+13135551212</destinationAddress>\n")
        .append("  <text encoding=\"UTF-8\">E282ACD8A3D987D984D8A720D987D8B0D98720D8A7D984D8AAD8ACD8B1D8A8D8A920D8A7D984D8A3D988D984D989</text>\n")
        .append(" </submitRequest>\n")
        .append("</operation>\n")
        .append("");

    // compare to actual correct submit response
    XMLUnit.setIgnoreWhitespace(true);
    Diff myDiff = new Diff(expectedXML.toString(), sw.toString());
    DetailedDiff myDetailedDiff = new DetailedDiff(myDiff);
    Assert.assertTrue("XML are similar " + myDetailedDiff, myDetailedDiff.similar());
}
 
Example #28
Source File: JaxbTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
private <T> void unmarshalAndMarshal(final Class<T> type, final java.lang.String xmlFileName, final java.lang.String expectedFile) throws Exception {

        final Object object = JpaJaxbUtil.unmarshal(type, getInputStream(xmlFileName));

        final String actual = JpaJaxbUtil.marshal(type, object);

        final String expected;
        if (xmlFileName.equals(expectedFile)) {
            expected = readContent(getInputStream(xmlFileName));
        } else {
            expected = readContent(getInputStream(expectedFile));
        }
        final Diff myDiff = new Diff(expected, actual);
        assertTrue("Files are similar " + myDiff, myDiff.similar());
    }
 
Example #29
Source File: XmlCombinerTest.java    From xml-combiner with Apache License 2.0 5 votes vote down vote up
@Test
public void overridable() throws SAXException, IOException, ParserConfigurationException, TransformerException {
	String recessive = "\n"
			+ "<config>\n"
			+ "    <service id='id1' combine.self='overridable'>\n"
			+ "        <test/>\n"
			+ "    </service>\n"
			+ "</config>";
	String dominant = "\n"
			+ "<config>\n"
			+ "</config>";
	String result = "\n"
			+ "<config>\n"
			+ "    <service id='id1'>\n"
			+ "        <test/>\n"
			+ "    </service>\n"
			+ "</config>";
	String dominant2 = "\n"
			+ "<config>\n"
			+ "    <service id='id1'/>\n"
			+ "</config>";
	String dominant3 = "\n"
			+ "<config>\n"
			+ "    <service id='id2'/>\n"
			+ "</config>";
	String result3 = "\n"
			+ "<config>\n"
			+ "    <service id='id1'>\n"
			+ "        <test/>\n"
			+ "    </service>\n"
			+ "    <service id='id2'/>\n"
			+ "</config>";

	assertXMLIdentical(new Diff(result, combineWithIdKey(recessive, dominant)), true);
	assertXMLIdentical(new Diff(dominant2, combineWithIdKey(recessive, dominant2)), true);
	assertXMLIdentical(new Diff(result3, combineWithIdKey(recessive, dominant3)), true);
	assertXMLIdentical(new Diff(result3, combineWithIdKey(recessive, dominant, dominant3)), true);
}
 
Example #30
Source File: SxmpWriterTest.java    From cloudhopper-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void writeSubmitRequestWithUTF8PushDestination() throws Exception {
    SubmitRequest request = new SubmitRequest(SxmpParser.VERSION_1_1);
    request.setAccount(new Account("customer1", "test1"));
    request.setOperatorId(20);
    request.setDestinationAddress(new MobileAddress(MobileAddress.Type.PUSH_DESTINATION, "abcd\n1234\rfghi-€£æ_\u20AC\u0623\u0647\u0644"));
    request.setText("Hello World");

    StringWriter sw = new StringWriter();
    SxmpWriter.write(sw, request);

    logger.debug("UTF8 PUSH DEST: "+sw.toString());

    StringBuilder expectedXML = new StringBuilder(200)
        .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
        .append("<operation type=\"submit\">\n")
        .append(" <account username=\"customer1\" password=\"test1\"/>\n")
        .append(" <submitRequest>\n")
        .append("  <operatorId>20</operatorId>\n")
        .append("  <priority>0</priority>\n")
        .append("  <deliveryReport>false</deliveryReport>\n")
        .append("  <destinationAddress type=\"push_destination\">abcd\n1234\rfghi-€£æ_\u20AC\u0623\u0647\u0644</destinationAddress>\n")
        .append("  <text encoding=\"UTF-8\">48656C6C6F20576F726C64</text>\n")
        .append(" </submitRequest>\n")
        .append("</operation>\n")
        .append("");

    // compare to actual correct submit response
    XMLUnit.setIgnoreWhitespace(true);
    Diff myDiff = new Diff(expectedXML.toString(), sw.toString());
    DetailedDiff myDetailedDiff = new DetailedDiff(myDiff);
    Assert.assertTrue("XML are similar " + myDetailedDiff, myDetailedDiff.similar());
    // verify there's no optionalParams entry
    Assert.assertTrue(!expectedXML.toString().contains("optionalParams"));
}