Java Code Examples for org.xmlunit.diff.Diff#hasDifferences()

The following examples show how to use org.xmlunit.diff.Diff#hasDifferences() . 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: MavenMetadataGeneratorTests.java    From artifactory-resource with 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 2
Source File: MetadataTransferTest.java    From archiva with 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 3
Source File: MetadataToolsTest.java    From archiva with 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 4
Source File: MetadataToolsTest.java    From archiva with 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 5
Source File: DmnModelTest.java    From camunda-bpm-platform with 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 6
Source File: CompareUtils.java    From AuTe-Framework with 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 7
Source File: AbstractConverterTest.java    From powsybl-core with 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 8
Source File: PowsyblWriterSequenceFixTest.java    From powsybl-core with 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 9
Source File: AbstractRepositoryServletProxiedMetadataTestCase.java    From archiva with Apache License 2.0 5 votes vote down vote up
protected void assertExpectedMetadata( String expectedMetadata, String actualMetadata )
    throws Exception
{
    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 );
    }
    // XMLAssert.assertXMLEqual( "Expected Metadata:", expectedMetadata, actualMetadata );
}
 
Example 10
Source File: CimAnonymizerTest.java    From powsybl-core with Mozilla Public License 2.0 4 votes vote down vote up
@Test
public void anonymizeZip() throws Exception {
    String eq = String.join(System.lineSeparator(),
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
            "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\txmlns:cim=\"http://iec.ch/TC57/2009/CIM-schema-cim14#\">",
            "<cim:ACLineSegment rdf:ID=\"L1\">",
            "<cim:Conductor.gch>0</cim:Conductor.gch>",
            "<cim:Conductor.x>0.001</cim:Conductor.x>",
            "<cim:Conductor.bch>0</cim:Conductor.bch>",
            "<cim:Conductor.r>0.0008</cim:Conductor.r>",
            "<cim:ConductingEquipment.BaseVoltage rdf:resource=\"#_BV_10\"/>",
            "<cim:IdentifiedObject.name>Line 1</cim:IdentifiedObject.name>",
            "</cim:ACLineSegment>",
            "<cim:BaseVoltage rdf:ID=\"_BV_10\">",
            "<cim:BaseVoltage.isDC>false</cim:BaseVoltage.isDC>",
            "<cim:BaseVoltage.nominalVoltage>1</cim:BaseVoltage.nominalVoltage>",
            "<cim:IdentifiedObject.name>10</cim:IdentifiedObject.name>",
            "</cim:BaseVoltage>",
            "</rdf:RDF>");
    Path workDir = fileSystem.getPath("work");
    Path cimZipFile = workDir.resolve("sample.zip");
    Path anonymizedCimFileDir = workDir.resolve("result");
    Files.createDirectories(anonymizedCimFileDir);
    Path dictionaryFile = workDir.resolve("dic.csv");
    try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(cimZipFile))) {
        zos.putNextEntry(new ZipEntry("sample_EQ.xml"));
        zos.write(eq.getBytes(StandardCharsets.UTF_8));
    }

    new CimAnonymizer().anonymizeZip(cimZipFile, anonymizedCimFileDir, dictionaryFile, new CimAnonymizer.DefaultLogger(), false);

    Path anonymizedCimZipFile = anonymizedCimFileDir.resolve("sample.zip");
    assertTrue(Files.exists(anonymizedCimZipFile));
    try (ZipFile anonymizedCimZipFileData = new ZipFile(anonymizedCimZipFile)) {
        assertNotNull(anonymizedCimZipFileData.entry("sample_EQ.xml"));
        String anonymizedEq = String.join(System.lineSeparator(),
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
                "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:cim=\"http://iec.ch/TC57/2009/CIM-schema-cim14#\">",
                "<cim:ACLineSegment rdf:ID=\"A\">",
                "<cim:Conductor.gch>0</cim:Conductor.gch>",
                "<cim:Conductor.x>0.001</cim:Conductor.x>",
                "<cim:Conductor.bch>0</cim:Conductor.bch>",
                "<cim:Conductor.r>0.0008</cim:Conductor.r>",
                "<cim:ConductingEquipment.BaseVoltage rdf:resource=\"#B\"></cim:ConductingEquipment.BaseVoltage>",
                "<cim:IdentifiedObject.name>C</cim:IdentifiedObject.name>",
                "</cim:ACLineSegment>",
                "<cim:BaseVoltage rdf:ID=\"B\">",
                "<cim:BaseVoltage.isDC>false</cim:BaseVoltage.isDC>",
                "<cim:BaseVoltage.nominalVoltage>1</cim:BaseVoltage.nominalVoltage>",
                "<cim:IdentifiedObject.name>D</cim:IdentifiedObject.name>",
                "</cim:BaseVoltage>",
                "</rdf:RDF>");
        Source control = Input.fromString(anonymizedEq).build();
        try (InputStream is = anonymizedCimZipFileData.getInputStream("sample_EQ.xml")) {
            Source test = Input.fromStream(is).build();
            Diff myDiff = DiffBuilder.compare(control)
                    .withTest(test)
                    .ignoreWhitespace()
                    .ignoreComments()
                    .build();
            boolean hasDiff = myDiff.hasDifferences();
            if (hasDiff) {
                System.err.println(myDiff.toString());
            }
            assertFalse(hasDiff);
        }
    }

    String dictionaryCsv = String.join(System.lineSeparator(),
            "L1;A",
            "_BV_10;B",
            "Line 1;C",
            "10;D") + System.lineSeparator();
    assertEquals(dictionaryCsv, new String(Files.readAllBytes(dictionaryFile), StandardCharsets.UTF_8));
}
 
Example 11
Source File: CompareAssert.java    From xmlunit with Apache License 2.0 4 votes vote down vote up
private void compare(ComparisonContext context) {

        if (customComparisonController != null) {
            diffBuilder.withComparisonController(customComparisonController);
        } else if (ComparisonContext.IDENTICAL == context
                || ComparisonContext.NOT_IDENTICAL == context) {
            diffBuilder.withComparisonController(ComparisonControllers.StopWhenSimilar);
        } else if (ComparisonContext.SIMILAR == context
                || ComparisonContext.NOT_SIMILAR == context) {
            diffBuilder.withComparisonController(ComparisonControllers.StopWhenDifferent);
        }

        Diff diff;

        try {

            diff = diffBuilder.build();
        } catch (Exception e) {
            throwAssertionError(shouldNotHaveThrown(e));
            return; //fix compile issue
        }

        String controlSystemId = diff.getControlSource().getSystemId();
        String testSystemId = diff.getTestSource().getSystemId();

        if (diff.hasDifferences()) {
            Comparison firstDifferenceComparison = diff.getDifferences().iterator().next().getComparison();
            if (ComparisonContext.IDENTICAL == context) {
                throwAssertionError(shouldBeIdentical(controlSystemId, testSystemId, firstDifferenceComparison, formatter, formatXml));
            } else if (ComparisonContext.SIMILAR == context) {
                throwAssertionError(shouldBeSimilar(controlSystemId, testSystemId, firstDifferenceComparison, formatter, formatXml));
            }
        } else {

            if (ComparisonContext.NOT_IDENTICAL == context) {
                throwAssertionError(shouldBeNotIdentical(controlSystemId, testSystemId));
            } else if (ComparisonContext.NOT_SIMILAR == context) {
                throwAssertionError(shouldBeNotSimilar(controlSystemId, testSystemId));
            }
        }
    }