org.xmlunit.diff.Diff Java Examples

The following examples show how to use org.xmlunit.diff.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 Project: staedi   Author: xlate   File: StaEDIXMLStreamReaderTest.java    License: Apache License 2.0 8 votes vote down vote up
@Test
void testReadXml() throws Exception {
    XMLStreamReader xmlReader = getXmlReader("/x12/extraDelimiter997.edi");
    xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StringWriter result = new StringWriter();
    transformer.transform(new StAXSource(xmlReader), new StreamResult(result));
    String resultString = result.toString();
    Diff d = DiffBuilder.compare(Input.fromFile("src/test/resources/x12/extraDelimiter997.xml"))
                        .withTest(resultString).build();
    assertTrue(!d.hasDifferences(), () -> "XML unexpectedly different:\n" + d.toString(new DefaultComparisonFormatter()));
}
 
Example #2
Source Project: vividus   Author: vividus-framework   File: XmlSteps.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Checks if XML is equal to expected XML
 * @param xml XML
 * @param expectedXml Expected XML
 */
@Then("XML `$xml` is equal to `$expectedXml`")
public void compareXmls(String xml, String expectedXml)
{
    Diff diff = DiffBuilder.compare(expectedXml).withTest(xml)
            .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndAllAttributes))
            .ignoreWhitespace()
            .checkForSimilar()
            .build();

    Iterable<?> allDifferences = diff.getDifferences();
    if (allDifferences.iterator().hasNext())
    {
        StringBuilder stringBuilder = new StringBuilder();
        for (Object difference : allDifferences)
        {
            stringBuilder.append(difference).append(System.lineSeparator());
        }
        softAssert.recordFailedAssertion(stringBuilder.toString());
    }
}
 
Example #3
Source Project: syndesis   Author: syndesisio   File: XmlSchemaTestHelper.java    License: Apache License 2.0 6 votes vote down vote up
private static void compareMatchingElement(List<Element> sourceChildNodes, Element element) {
    final String type = element.getLocalName();
    final String name = element.getAttribute(NAME_ATTRIBUTE);
    boolean matchFound = false;
    for (Element sourceElement : sourceChildNodes) {
        if (type.equals(sourceElement.getLocalName()) &&
            name.equals(sourceElement.getAttribute(NAME_ATTRIBUTE))) {
            // compare matching element
            Diff diff = DiffBuilder.compare(Input.fromNode(sourceElement))
                .withTest(Input.fromNode(sourceElement))
                .ignoreComments()
                .ignoreWhitespace()
                .checkForIdentical()
                .build();
            assertThat(diff.hasDifferences())
                .overridingErrorMessage("Schema differences " + diff.toString())
                .isFalse();
            matchFound = true;
        }
    }

    if (!matchFound) {
        fail(String.format("Missing source element %s[name=%s]", type, name));
    }
}
 
Example #4
Source Project: staedi   Author: xlate   File: StaEDIXMLStreamReaderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testTransactionElementWithXmlns() throws Exception {
    EDIInputFactory ediFactory = EDIInputFactory.newFactory();
    ediFactory.setProperty(EDIInputFactory.XML_DECLARE_TRANSACTION_XMLNS, Boolean.TRUE);
    InputStream stream = getClass().getResourceAsStream("/x12/extraDelimiter997.edi");
    ediReader = ediFactory.createEDIStreamReader(stream);
    XMLStreamReader xmlReader = ediFactory.createXMLStreamReader(ediReader);

    xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StringWriter result = new StringWriter();
    transformer.transform(new StAXSource(xmlReader), new StreamResult(result));
    String resultString = result.toString();
    Diff d = DiffBuilder.compare(Input.fromFile("src/test/resources/x12/extraDelimiter997-transaction-xmlns.xml"))
                        .withTest(resultString).build();
    assertTrue(!d.hasDifferences(), () -> "XML unexpectedly different:\n" + d.toString(new DefaultComparisonFormatter()));
}
 
Example #5
Source Project: artifactory-resource   Author: spring-io   File: MavenMetadataGeneratorTests.java    License: Apache License 2.0 6 votes vote down vote up
private Condition<File> xmlContent(URL expected) {
	return new Condition<File>("XML Content") {

		@Override
		public boolean matches(File actual) {
			Diff diff = DiffBuilder.compare(Input.from(expected)).withTest(Input.from(actual)).checkForSimilar()
					.ignoreWhitespace().build();
			if (diff.hasDifferences()) {
				try {
					String content = new String(FileCopyUtils.copyToByteArray(actual));
					throw new AssertionError(diff.toString() + "\n" + content);
				}
				catch (IOException ex) {
					throw new IllegalStateException(ex);
				}
			}
			return true;
		}

	};
}
 
Example #6
Source Project: archiva   Author: apache   File: MetadataTransferTest.java    License: Apache License 2.0 6 votes vote down vote up
private void assertMetadataEquals( String expectedMetadataXml, Path actualFile )
    throws Exception
{
    assertNotNull( "Actual File should not be null.", actualFile );

    assertTrue( "Actual file exists.", Files.exists(actualFile) );

    StringWriter actualContents = new StringWriter();
    FilesystemStorage fsStorage = new FilesystemStorage(actualFile.getParent(), new DefaultFileLockManager());
    StorageAsset actualFileAsset = fsStorage.getAsset(actualFile.getFileName().toString());
    ArchivaRepositoryMetadata metadata = metadataTools.getMetadataReader( null ).read( actualFileAsset );
    RepositoryMetadataWriter.write( metadata, actualContents );

    Diff detailedDiff = DiffBuilder.compare( expectedMetadataXml).withTest( actualContents.toString() ).checkForSimilar().build();
    if ( detailedDiff.hasDifferences() )
    {
        for ( Difference diff : detailedDiff.getDifferences() )
        {
            System.out.println( diff );
        }
        assertEquals( expectedMetadataXml, actualContents );
    }

    // assertEquals( "Check file contents.", expectedMetadataXml, actualContents );
}
 
Example #7
Source Project: archiva   Author: apache   File: MetadataToolsTest.java    License: Apache License 2.0 6 votes vote down vote up
private void assertProjectMetadata( String expectedMetadata, ManagedRepositoryContent repository,
                             ItemSelector reference )
    throws LayoutException, IOException, SAXException, ParserConfigurationException
{
    Path metadataFile = repository.getRepository().getRoot().getFilePath().resolve(tools.toPath( reference ) );
    String actualMetadata = org.apache.archiva.common.utils.FileUtils.readFileToString( metadataFile, Charset.defaultCharset() );

    Diff detailedDiff = DiffBuilder.compare( expectedMetadata ).withTest( actualMetadata ).checkForSimilar().build();
    if ( detailedDiff.hasDifferences() )
    {
        for ( Difference diff : detailedDiff.getDifferences() ) {
            System.out.println( diff );
        }
        // If it isn't similar, dump the difference.
        assertEquals( expectedMetadata, actualMetadata );
    }
}
 
Example #8
Source Project: archiva   Author: apache   File: MetadataToolsTest.java    License: Apache License 2.0 6 votes vote down vote up
private void assertMetadata( String expectedMetadata, ManagedRepositoryContent repository,
                             ItemSelector reference )
    throws LayoutException, IOException, SAXException, ParserConfigurationException
{
    Path metadataFile = repository.getRepository().getRoot().getFilePath().resolve( tools.toPath( reference ) );
    String actualMetadata = org.apache.archiva.common.utils.FileUtils.readFileToString( metadataFile, Charset.defaultCharset() );

    Diff detailedDiff = DiffBuilder.compare( expectedMetadata ).withTest( actualMetadata ).checkForSimilar().build();
    if ( detailedDiff.hasDifferences() )
    {
        for ( Difference diff : detailedDiff.getDifferences() ) {
            System.out.println( diff );
        }
        // If it isn't similar, dump the difference.
        assertEquals( expectedMetadata, actualMetadata );
    }
}
 
Example #9
Source Project: xmlunit   Author: xmlunit   File: DiffBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDiff_withIgnoreWhitespaces_shouldSucceed() {
    // prepare testData
    String controlXml = "<a><b>Test Value</b></a>";
    String testXml = "<a>\n <b>\n  Test Value\n </b>\n</a>";

    // run test
    Diff myDiff = DiffBuilder.compare(Input.fromString(controlXml).build())
                  .withTest(Input.fromString(testXml).build())
                  .ignoreWhitespace()
                  .build();

    // validate result
    Assert.assertFalse("XML similar " + myDiff.toString(), myDiff.hasDifferences());

}
 
Example #10
Source Project: xmlunit   Author: xmlunit   File: DiffBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDiff_withNormalizeWhitespaces_shouldSucceed() {
    // prepare testData
    String controlXml = "<a><b>Test Value</b></a>";
    String testXml = "<a>\n <b>\n  Test\n        Value\n </b>\n</a>";

    // run test
    Diff myDiff = DiffBuilder.compare(Input.fromString(controlXml).build())
                  .withTest(Input.fromString(testXml).build())
                  .normalizeWhitespace()
                  .build();

    // validate result
    Assert.assertFalse("XML similar " + myDiff.toString(), myDiff.hasDifferences());

}
 
Example #11
Source Project: xmlunit   Author: xmlunit   File: DiffBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDiff_withNormalizeAndIgnoreWhitespaces_shouldSucceed() {
    // prepare testData
    String controlXml = "<a><b>Test Value</b></a>";
    String testXml = "<a>\n <b>\n  Test\n        Value\n </b>\n</a>";

    // run test
    Diff myDiff = DiffBuilder.compare(Input.fromString(controlXml).build())
                  .withTest(Input.fromString(testXml).build())
                  .normalizeWhitespace()
                  .ignoreWhitespace()
                  .build();

    // validate result
    Assert.assertFalse("XML similar " + myDiff.toString(), myDiff.hasDifferences());

}
 
Example #12
Source Project: xmlunit   Author: xmlunit   File: DiffBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDiff_withCheckForIdentical_shouldFail() {
    // prepare testData
    String controlXml = "<a>Test Value</a>";
    String testXml = "<a><![CDATA[Test Value]]></a>";

    // run test
    Diff myDiff = DiffBuilder.compare(Input.fromString(controlXml).build())
                  .withTest(Input.fromString(testXml).build())
                  .checkForIdentical()
                  .build();

    // validate result
    Assert.assertTrue(myDiff.toString(), myDiff.hasDifferences());

}
 
Example #13
Source Project: xmlunit   Author: xmlunit   File: DiffBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDiff_withCheckForSimilar_shouldSucceed() {
    // prepare testData
    String controlXml = "<a>Test Value</a>";
    String testXml = "<a><![CDATA[Test Value]]></a>";

    // run test
    Diff myDiff = DiffBuilder.compare(Input.fromString(controlXml).build())
                  .withTest(Input.fromString(testXml).build())
                  .checkForSimilar()
                  .build();

    // validate result
    Assert.assertFalse("XML similar " + myDiff.toString(), myDiff.hasDifferences());

}
 
Example #14
Source Project: xmlunit   Author: xmlunit   File: DiffBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDiff_withIgnoreComments_shouldSucceed() {
    // prepare testData
    String controlXml = "<a><b><!-- A comment -->Test Value</b></a>";
    String testXml = "<a><b><!-- An other comment -->Test Value</b></a>";

    // run test
    Diff myDiff = DiffBuilder.compare(Input.fromString(controlXml).build())
                            .withTest(Input.fromString(testXml).build())
                            .ignoreComments()
                            .build();

    // validate result
    Assert.assertFalse("XML similar " + myDiff.toString(), myDiff.hasDifferences());

}
 
Example #15
Source Project: xmlunit   Author: xmlunit   File: DiffBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDiff_withIgnoreComments2_0_shouldSucceed() {
    // prepare testData
    String controlXml = "<a><b><!-- A comment -->Test Value</b></a>";
    String testXml = "<a><b><!-- An other comment -->Test Value</b></a>";

    // run test
    Diff myDiff = DiffBuilder.compare(Input.fromString(controlXml).build())
                            .withTest(Input.fromString(testXml).build())
                            .ignoreCommentsUsingXSLTVersion("2.0")
                            .build();

    // validate result
    Assert.assertFalse("XML similar " + myDiff.toString(), myDiff.hasDifferences());

}
 
Example #16
Source Project: xmlunit   Author: xmlunit   File: DiffBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDiff_withIgnoreComments1_0_shouldSucceed() {
    // prepare testData
    String controlXml = "<a><b><!-- A comment -->Test Value</b></a>";
    String testXml = "<a><b><!-- An other comment -->Test Value</b></a>";

    // run test
    Diff myDiff = DiffBuilder.compare(Input.fromString(controlXml).build())
                            .withTest(Input.fromString(testXml).build())
                            .ignoreCommentsUsingXSLTVersion("1.0")
                            .build();

    // validate result
    Assert.assertFalse("XML similar " + myDiff.toString(), myDiff.hasDifferences());

}
 
Example #17
Source Project: xmlunit   Author: xmlunit   File: DiffBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDiff_withComparisonListener_shouldCallListener() {
    // prepare testData
    final String control = "<a><b attr=\"abc\"></b></a>";
    final String test = "<a><b attr=\"xyz\"></b></a>";
    final List<Difference> diffs = new ArrayList<Difference>();
    final ComparisonListener comparisonListener = new ComparisonListener() {
        @Override
        public void comparisonPerformed(Comparison comparison, ComparisonResult outcome) {
            diffs.add(new Difference(comparison, outcome));
        }
    };

    // run test
    Diff myDiff = DiffBuilder.compare(control).withTest(test)
            .withComparisonListeners(comparisonListener)
            .build();

    // validate result
    Assert.assertTrue(myDiff.toString(), myDiff.hasDifferences());
    assertThat(diffs.size(), greaterThan(1));
}
 
Example #18
Source Project: xmlunit   Author: xmlunit   File: DiffBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDiff_withDifferenceListener_shouldCallListener() {
    // prepare testData
    final String control = "<a><b attr=\"abc\"></b></a>";
    final String test = "<a><b attr=\"xyz\"></b></a>";
    final List<Difference> diffs = new ArrayList<Difference>();
    final ComparisonListener comparisonListener = new ComparisonListener() {
        @Override
        public void comparisonPerformed(Comparison comparison, ComparisonResult outcome) {
            diffs.add(new Difference(comparison, outcome));
        }
    };

    // run test
    Diff myDiff = DiffBuilder.compare(control).withTest(test)
            .withDifferenceListeners(comparisonListener)
            .build();

    // validate result
    Assert.assertTrue(myDiff.toString(), myDiff.hasDifferences());
    assertThat(diffs.size(), is(1));
    assertThat(diffs.get(0).getResult(), is(ComparisonResult.DIFFERENT));
    assertThat(diffs.get(0).getComparison().getType(), is(ComparisonType.ATTR_VALUE));

}
 
Example #19
Source Project: xmlunit   Author: xmlunit   File: DiffBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDiff_withDifferenceEvaluator_shouldNotInterfereWithSimilar() {
    // prepare testData
    final String control = "<a><b><![CDATA[abc]]></b></a>";
    final String test = "<a><b>abc</b></a>";

    // run test
    Diff myDiff = DiffBuilder.compare(control).withTest(test)
            .withDifferenceEvaluator(
                DifferenceEvaluators.chain(DifferenceEvaluators.Default,
                new IgnoreAttributeDifferenceEvaluator("attr")))
            .checkForSimilar()
            .build();

    // validate result
    Assert.assertFalse(myDiff.toString(), myDiff.hasDifferences());

}
 
Example #20
Source Project: xmlunit   Author: xmlunit   File: DiffBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDiff_withCustomDifferenceEvaluator_shouldNotEvaluateSimilar() {
    // prepare testData
    final String control = "<a><b><![CDATA[abc]]></b></a>";
    final String test = "<a><b>abc</b></a>";

    // run test
    Diff myDiff = DiffBuilder.compare(control).withTest(test)
            .withDifferenceEvaluator(new IgnoreAttributeDifferenceEvaluator("attr"))
            .checkForSimilar()
            .build();

    // validate result
    Assert.assertTrue(myDiff.toString(), myDiff.hasDifferences());
    Assert.assertThat(ComparisonResult.DIFFERENT, is(myDiff.getDifferences().iterator().next().getResult()));

}
 
Example #21
Source Project: xmlunit   Author: xmlunit   File: DiffBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDiff_withIgnoreECW_shouldSucceed() {
    // prepare testData
    String controlXml = "<a><b>Test Value</b></a>";
    String testXml = "<a>\n <b>Test Value</b>\n</a>";

    // run test
    Diff myDiff = DiffBuilder.compare(Input.fromString(controlXml).build())
                  .withTest(Input.fromString(testXml).build())
                  .ignoreElementContentWhitespace()
                  .build();

    // validate result
    Assert.assertFalse("XML similar " + myDiff.toString(), myDiff.hasDifferences());

}
 
Example #22
Source Project: pom-manipulation-ext   Author: release-engineering   File: XMLManipulatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void alterFile() throws Exception
{
    String replacementGA = "com.rebuild:servlet-api";
    String tomcatPath = "//include[starts-with(.,'org.apache.tomcat')]";

    File target = tf.newFile();
    FileUtils.copyFile( xmlFile, target );
    Project project = new Project( target, TestUtils.getDummyModel() );

    xmlManipulator.internalApplyChanges( project, new XMLState.XMLOperation( target.getName(), tomcatPath, replacementGA) );

    Diff diff = DiffBuilder.compare( fromFile( xmlFile ) ).withTest( fromFile( target ) ).build();
    assertTrue (diff.toString(), diff.hasDifferences());

    String xpathForHamcrest = "/*/*/*/*/*[starts-with(.,'com.rebuild') and local-name() = 'include']";
    Iterable<Node> i = new JAXPXPathEngine( ).selectNodes( xpathForHamcrest, fromFile( target ).build() );
    int count = 0;
    for ( Node anI : i )
    {
        count++;
        assertTrue( anI.getTextContent().startsWith( "com.rebuild:servlet-api" ) );
    }
    assertEquals(1, count);

}
 
Example #23
Source Project: camunda-bpm-platform   Author: camunda   File: DmnModelTest.java    License: Apache License 2.0 6 votes vote down vote up
protected void assertModelEqualsFile(String expectedPath) throws Exception {
  File actualFile = tmpFolder.newFile();
  Dmn.writeModelToFile(actualFile, modelInstance);

  File expectedFile = ReflectUtil.getResourceAsFile(expectedPath);

  DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
  Document actualDocument = docBuilder.parse(actualFile);
  Document expectedDocument = docBuilder.parse(expectedFile);

  Diff diff = DiffBuilder.compare(expectedDocument).withTest(actualDocument)
    .withNodeFilter(new Java9CDataWhitespaceFilter())
    .checkForSimilar()
    .build();

  if (diff.hasDifferences()) {

    String failMsg = "XML differs:\n" + diff.getDifferences() +
        "\n\nActual XML:\n" + Dmn.convertToString(modelInstance);
    fail(failMsg);
  }
}
 
Example #24
Source Project: AuTe-Framework   Author: BSC-RUS   File: CompareUtils.java    License: Apache License 2.0 5 votes vote down vote up
static ComparisonResult compareRequestAsXml(String expectedRequestBody, String actualRequestBody, Set<String> ignoredTags) {
    Diff diff = DiffBuilder.compare(StringUtils.defaultString(expectedRequestBody))
                           .withTest(StringUtils.defaultString(actualRequestBody))
                           .checkForIdentical()
                           .ignoreComments()
                           .ignoreWhitespace()
                           .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName))
                           .withDifferenceEvaluator(new IgnoreTagsDifferenceEvaluator(ignoredTags))
                           .build();

    return new ComparisonResult(diff.hasDifferences(), diff.toString(), expectedRequestBody, actualRequestBody);
}
 
Example #25
Source Project: AuTe-Framework   Author: BSC-RUS   File: ComparisonException.java    License: Apache License 2.0 5 votes vote down vote up
public ComparisonException(Diff diff, String expectedRequest, String actualRequest) {
    super(String.format(
            "Service request error (request differences):%s%n\tExpected: %s%n\tActual: %s%n",
            diff,
            expectedRequest,
            actualRequest
    ));
}
 
Example #26
Source Project: powsybl-core   Author: powsybl   File: AbstractConverterTest.java    License: Mozilla Public License 2.0 5 votes vote down vote up
protected static void compareXml(InputStream expected, InputStream actual) {
    Source control = Input.fromStream(expected).build();
    Source test = Input.fromStream(actual).build();
    Diff myDiff = DiffBuilder.compare(control).withTest(test).ignoreWhitespace().ignoreComments().build();
    boolean hasDiff = myDiff.hasDifferences();
    if (hasDiff) {
        System.err.println(myDiff.toString());
    }
    assertFalse(hasDiff);
}
 
Example #27
Source Project: powsybl-core   Author: powsybl   File: PowsyblWriterSequenceFixTest.java    License: Mozilla Public License 2.0 5 votes vote down vote up
private static void compareXml(InputStream expected, InputStream actual) {
    Source sexpected = Input.fromStream(expected).build();
    Source sactual = Input.fromStream(actual).build();
    Diff myDiff = DiffBuilder
        .compare(sexpected)
        .withTest(sactual)
        .ignoreWhitespace()
        .ignoreComments()
        .build();
    boolean hasDiff = myDiff.hasDifferences();
    if (hasDiff) {
        LOG.error(myDiff.toString());
    }
    assertFalse(hasDiff);
}
 
Example #28
Source Project: staedi   Author: xlate   File: StaEDIXMLStreamReaderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testReadXml_WithOptionalInterchangeServiceRequests_TransactionOnly() throws Exception {
    EDIInputFactory ediFactory = EDIInputFactory.newFactory();
    XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
    InputStream stream = getClass().getResourceAsStream("/x12/optionalInterchangeServices.edi");
    ediFactory.setProperty(EDIInputFactory.XML_DECLARE_TRANSACTION_XMLNS, Boolean.TRUE);
    EDIStreamReader reader = ediFactory.createEDIStreamReader(stream);
    EDIStreamReader filtered = ediFactory.createFilteredReader(reader, r -> true);
    XMLStreamReader xmlReader = ediFactory.createXMLStreamReader(filtered);
    xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state
    XMLStreamReader xmlCursor = xmlFactory.createFilteredReader(xmlReader, r -> {
        boolean startTx = (r.getEventType() == XMLStreamConstants.START_ELEMENT && r.getName().getLocalPart().equals("TRANSACTION"));

        if (!startTx) {
            Logger.getGlobal().info("Skipping event: " + r.getEventType() + "; "
                    + (r.getEventType() == XMLStreamConstants.START_ELEMENT || r.getEventType() == XMLStreamConstants.END_ELEMENT
                            ? r.getName()
                            : ""));
        }

        return startTx;
    });

    xmlCursor.hasNext();

    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StringWriter result = new StringWriter();
    transformer.transform(new StAXSource(xmlReader), new StreamResult(result));
    String resultString = result.toString();
    System.out.println(resultString);
    Diff d = DiffBuilder.compare(Input.fromFile("src/test/resources/x12/optionalInterchangeServices_transactionOnly.xml"))
                        .withTest(resultString).build();
    assertTrue(!d.hasDifferences(), () -> "XML unexpectedly different:\n" + d.toString(new DefaultComparisonFormatter()));
}
 
Example #29
Source Project: thorntail   Author: thorntail   File: MavenPluginMigrationTest.java    License: Apache License 2.0 5 votes vote down vote up
private void verifyMigratedPomXml() {
    Path projectDir = Paths.get(verifier.getBasedir());
    Diff diff = DiffBuilder.compare(Input.fromFile(projectDir.resolve("expected-pom.xml").toFile()))
            .withTest(Input.fromFile(projectDir.resolve("pom.xml").toFile()))
            .checkForIdentical()
            .build();
    assertThat(diff.hasDifferences())
            .as(diff.getDifferences().toString())
            .isFalse();
}
 
Example #30
Source Project: jaxb2-maven-plugin   Author: mojohaus   File: XsdAnnotationProcessorAndEnumsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void validateGeneratedXmlForEnums() throws Exception
{

    // Assemble
    final String expected = PropertyResources.readFully(
            "testdata/schemageneration/javadoc/expectedRawExampleEnumHolder.xml" );
    final ExampleEnumHolder exampleEnumHolder = new ExampleEnumHolder();
    exampleEnumHolder.getCoins().addAll( Arrays.asList( AmericanCoin.values() ) );
    exampleEnumHolder.getFoodPreferences().addAll( Arrays.asList( FoodPreference.values() ) );

    final StringWriter out = new StringWriter();

    // Act
    final JAXBContext context = JAXBContext.newInstance( FoodPreference.class, ExampleEnumHolder.class );
    final Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
    marshaller.setProperty( Marshaller.JAXB_ENCODING, "UTF-8" );
    marshaller.marshal( exampleEnumHolder, out );
    out.close();

    // Assert
    final Diff diff = DiffBuilder.compare( expected ).withTest(
            out.toString() ).ignoreWhitespace().ignoreComments().build();
    Assert.assertFalse( diff.hasDifferences() );
    // XmlTestUtils.compareXmlIgnoringWhitespace( expected, out.toString() );
}