Search in sources :

Example 6 with Diff

use of org.xmlunit.diff.Diff in project kernel by cristal-ise.

the class CastorXMLTest method compareXML.

/**
 * Compares 2 XML string
 *
 * @param expected the reference XML
 * @param actual the xml under test
 * @return whether the two XMLs are identical or not
 */
public static boolean compareXML(String expected, String actual) {
    Diff diffIdentical = DiffBuilder.compare(expected).withTest(actual).withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndAllAttributes)).ignoreComments().ignoreWhitespace().checkForSimilar().build();
    if (diffIdentical.hasDifferences()) {
        Logger.msg(0, actual);
        Logger.warning(diffIdentical.toString());
    }
    return !diffIdentical.hasDifferences();
}
Also used : Diff(org.xmlunit.diff.Diff) DefaultNodeMatcher(org.xmlunit.diff.DefaultNodeMatcher)

Example 7 with Diff

use of org.xmlunit.diff.Diff in project zm-mailbox by Zimbra.

the class XMLDiffChecker method assertXMLEquals.

public static void assertXMLEquals(String expected, String actual) {
    Diff myDiff = DiffBuilder.compare(Input.fromString(expected)).withTest(Input.fromString(actual)).ignoreWhitespace().build();
    Assert.assertFalse(myDiff.toString(), myDiff.hasDifferences());
}
Also used : Diff(org.xmlunit.diff.Diff)

Example 8 with Diff

use of org.xmlunit.diff.Diff in project drools by kiegroup.

the class UnmarshalMarshalTest method testRoundTrip.

public void testRoundTrip(String subdir, String xmlfile, DMNMarshaller marshaller, Source schemaSource) throws Exception {
    File baseOutputDir = new File("target/test-xmlunit/");
    File testClassesBaseDir = new File("target/test-classes/");
    File inputXMLFile = new File(testClassesBaseDir, subdir + xmlfile);
    FileInputStream fis = new FileInputStream(inputXMLFile);
    Definitions unmarshal = marshaller.unmarshal(new InputStreamReader(fis));
    Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
    v.setSchemaSource(schemaSource);
    ValidationResult validateInputResult = v.validateInstance(new StreamSource(inputXMLFile));
    if (!validateInputResult.isValid()) {
        for (ValidationProblem p : validateInputResult.getProblems()) {
            LOG.error("{}", p);
        }
    }
    assertTrue(validateInputResult.isValid());
    final File subdirFile = new File(baseOutputDir, subdir);
    if (!subdirFile.mkdirs()) {
        LOG.warn("mkdirs() failed for File: ", subdirFile.getAbsolutePath());
    }
    FileOutputStream sourceFos = new FileOutputStream(new File(baseOutputDir, subdir + "a." + xmlfile));
    Files.copy(new File(testClassesBaseDir, subdir + xmlfile).toPath(), sourceFos);
    sourceFos.flush();
    sourceFos.close();
    LOG.debug("{}", marshaller.marshal(unmarshal));
    File outputXMLFile = new File(baseOutputDir, subdir + "b." + xmlfile);
    try (FileWriter targetFos = new FileWriter(outputXMLFile)) {
        marshaller.marshal(unmarshal, targetFos);
    }
    // Should also validate output XML:
    ValidationResult validateOutputResult = v.validateInstance(new StreamSource(outputXMLFile));
    if (!validateOutputResult.isValid()) {
        for (ValidationProblem p : validateOutputResult.getProblems()) {
            LOG.error("{}", p);
        }
    }
    assertTrue(validateOutputResult.isValid());
    LOG.debug("\n---\nDefault XMLUnit comparison:");
    Source control = Input.fromFile(inputXMLFile).build();
    Source test = Input.fromFile(outputXMLFile).build();
    Diff allDiffsSimilarAndDifferent = DiffBuilder.compare(control).withTest(test).build();
    allDiffsSimilarAndDifferent.getDifferences().forEach(m -> LOG.debug("{}", m));
    LOG.info("XMLUnit comparison with customized similarity for defaults:");
    // in the following a manual DifferenceEvaluator is needed until XMLUnit is configured for properly parsing the XSD linked inside the XML,
    // in order to detect the optional+defaultvalue attributes of xml element which might be implicit in source-test, and explicit in test-serialized.
    /*
         * $ grep -Eo "<xsd:attribute name=\\\"([^\\\"]*)\\\" type=\\\"([^\\\"]*)\\\" use=\\\"optional\\\" default=\\\"([^\\\"])*\\\"" dmn.xsd 
<xsd:attribute name="expressionLanguage" type="xsd:anyURI" use="optional" default="http://www.omg.org/spec/FEEL/20140401"
<xsd:attribute name="typeLanguage" type="xsd:anyURI" use="optional" default="http://www.omg.org/spec/FEEL/20140401"
<xsd:attribute name="isCollection" type="xsd:boolean" use="optional" default="false"
<xsd:attribute name="hitPolicy" type="tHitPolicy" use="optional" default="UNIQUE"
<xsd:attribute name="preferredOrientation" type="tDecisionTableOrientation" use="optional" default="Rule-as-Row"
DMNv1.2:
<xsd:attribute name="kind" type="tFunctionKind" default="FEEL"/>
<xsd:attribute name="textFormat" type="xsd:string" default="text/plain"/>
<xsd:attribute name="associationDirection" type="tAssociationDirection" default="None"/>
DMNDIv1.2:
<xsd:attribute name="isCollapsed" type="xsd:boolean" use="optional" default="false"/>
         */
    Set<QName> attrWhichCanDefault = new HashSet<QName>();
    attrWhichCanDefault.addAll(Arrays.asList(new QName[] { new QName("expressionLanguage"), new QName("typeLanguage"), new QName("isCollection"), new QName("hitPolicy"), new QName("preferredOrientation"), new QName("kind"), new QName("textFormat"), new QName("associationDirection"), new QName("isCollapsed") }));
    Set<String> nodeHavingDefaultableAttr = new HashSet<>();
    nodeHavingDefaultableAttr.addAll(Arrays.asList(new String[] { "definitions", "decisionTable", "itemDefinition", "itemComponent", "encapsulatedLogic", "textAnnotation", "association", "DMNShape" }));
    Diff checkSimilar = DiffBuilder.compare(control).withTest(test).withDifferenceEvaluator(DifferenceEvaluators.chain(DifferenceEvaluators.Default, ((comparison, outcome) -> {
        if (outcome == ComparisonResult.DIFFERENT && comparison.getType() == ComparisonType.ELEMENT_NUM_ATTRIBUTES) {
            if (comparison.getControlDetails().getTarget().getNodeName().equals(comparison.getTestDetails().getTarget().getNodeName()) && nodeHavingDefaultableAttr.contains(safeStripDMNPRefix(comparison.getControlDetails().getTarget()))) {
                return ComparisonResult.SIMILAR;
            }
        }
        // DMNDI/DMNDiagram#documentation is actually deserialized escaped with newlines as &#10; by the XML JDK infra.
        if (outcome == ComparisonResult.DIFFERENT && comparison.getType() == ComparisonType.ATTR_VALUE) {
            if (comparison.getControlDetails().getTarget().getNodeName().equals(comparison.getTestDetails().getTarget().getNodeName()) && comparison.getControlDetails().getTarget().getNodeType() == Node.ATTRIBUTE_NODE && comparison.getControlDetails().getTarget().getLocalName().equals("documentation")) {
                return ComparisonResult.SIMILAR;
            }
        }
        if (outcome == ComparisonResult.DIFFERENT && comparison.getType() == ComparisonType.ATTR_NAME_LOOKUP) {
            boolean testIsDefaulableAttribute = false;
            QName whichDefaultableAttr = null;
            if (comparison.getControlDetails().getValue() == null && attrWhichCanDefault.contains(comparison.getTestDetails().getValue())) {
                for (QName a : attrWhichCanDefault) {
                    boolean check = comparison.getTestDetails().getXPath().endsWith("@" + a);
                    if (check) {
                        testIsDefaulableAttribute = true;
                        whichDefaultableAttr = a;
                        continue;
                    }
                }
            }
            if (testIsDefaulableAttribute) {
                if (comparison.getTestDetails().getXPath().equals(comparison.getControlDetails().getXPath() + "/@" + whichDefaultableAttr)) {
                    // TODO missing to check the explicited option attribute has value set to the actual default value.
                    return ComparisonResult.SIMILAR;
                }
            }
        }
        return outcome;
    }))).ignoreWhitespace().checkForSimilar().build();
    checkSimilar.getDifferences().forEach(m -> LOG.error("{}", m));
    if (!checkSimilar.getDifferences().iterator().hasNext()) {
        LOG.info("[ EMPTY - no diffs using customized similarity ]");
    }
    assertFalse("XML are NOT similar: " + checkSimilar.toString(), checkSimilar.hasDifferences());
}
Also used : Arrays(java.util.Arrays) DMNStyle(org.kie.dmn.model.api.dmndi.DMNStyle) Diff(org.xmlunit.diff.Diff) StreamSource(javax.xml.transform.stream.StreamSource) ValidationResult(org.xmlunit.validation.ValidationResult) LoggerFactory(org.slf4j.LoggerFactory) ComparisonResult(org.xmlunit.diff.ComparisonResult) Source(javax.xml.transform.Source) Definitions(org.kie.dmn.model.api.Definitions) HashSet(java.util.HashSet) DMNMarshallerFactory(org.kie.dmn.backend.marshalling.v1x.DMNMarshallerFactory) Node(org.w3c.dom.Node) MyTestRegister(org.kie.dmn.backend.marshalling.v1_2.extensions.MyTestRegister) Logger(org.slf4j.Logger) Files(java.nio.file.Files) DiffBuilder(org.xmlunit.builder.DiffBuilder) DifferenceEvaluators(org.xmlunit.diff.DifferenceEvaluators) FileWriter(java.io.FileWriter) FileOutputStream(java.io.FileOutputStream) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) FileInputStream(java.io.FileInputStream) Input(org.xmlunit.builder.Input) KieDMNModelInstrumentedBase(org.kie.dmn.model.v1_2.KieDMNModelInstrumentedBase) InputStreamReader(java.io.InputStreamReader) File(java.io.File) Languages(org.xmlunit.validation.Languages) DMNShape(org.kie.dmn.model.api.dmndi.DMNShape) ValidationProblem(org.xmlunit.validation.ValidationProblem) Assert.assertFalse(org.junit.Assert.assertFalse) QName(javax.xml.namespace.QName) ComparisonType(org.xmlunit.diff.ComparisonType) Validator(org.xmlunit.validation.Validator) DMNMarshaller(org.kie.dmn.api.marshalling.DMNMarshaller) Assert.assertEquals(org.junit.Assert.assertEquals) InputStreamReader(java.io.InputStreamReader) Diff(org.xmlunit.diff.Diff) QName(javax.xml.namespace.QName) Definitions(org.kie.dmn.model.api.Definitions) StreamSource(javax.xml.transform.stream.StreamSource) FileWriter(java.io.FileWriter) ValidationProblem(org.xmlunit.validation.ValidationProblem) ValidationResult(org.xmlunit.validation.ValidationResult) FileInputStream(java.io.FileInputStream) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) FileOutputStream(java.io.FileOutputStream) File(java.io.File) Validator(org.xmlunit.validation.Validator) HashSet(java.util.HashSet)

Example 9 with Diff

use of org.xmlunit.diff.Diff in project atlasmap by atlasmap.

the class AtlasMapComponentXmlToXmlTest method testMocksAreValid.

@Test
@DirtiesContext
public void testMocksAreValid() throws Exception {
    result.setExpectedCount(1);
    final ProducerTemplate producerTemplate = camelContext.createProducerTemplate();
    producerTemplate.sendBody("direct:start", new ByteArrayInputStream("<tns:Patient xmlns:tns=\"http://hl7.org/fhir\"><tns:id value=\"101138\"></tns:id></tns:Patient>".getBytes()));
    MockEndpoint.assertIsSatisfied(camelContext);
    final String body = result.getExchanges().get(0).getIn().getBody(String.class);
    Assert.assertNotNull(body);
    Diff d = DiffBuilder.compare(Input.fromString(XML_EXPECTED).build()).withTest(Input.fromString(body).build()).ignoreWhitespace().build();
    Assert.assertFalse(d.toString() + ": " + body, d.hasDifferences());
}
Also used : ProducerTemplate(org.apache.camel.ProducerTemplate) ByteArrayInputStream(java.io.ByteArrayInputStream) Diff(org.xmlunit.diff.Diff) Test(org.junit.Test) DirtiesContext(org.springframework.test.annotation.DirtiesContext)

Example 10 with Diff

use of org.xmlunit.diff.Diff in project atlasmap by atlasmap.

the class AtlasMapComponentXmlToXmlDefaultNsTest method testMocksAreValid.

@Test
@DirtiesContext
public void testMocksAreValid() throws Exception {
    result.setExpectedCount(1);
    final ProducerTemplate producerTemplate = camelContext.createProducerTemplate();
    producerTemplate.sendBody("direct:start", new ByteArrayInputStream("<Patient xmlns=\"http://hl7.org/fhir\"><id value=\"101138\"></id></Patient>".getBytes()));
    MockEndpoint.assertIsSatisfied(camelContext);
    final String body = result.getExchanges().get(0).getIn().getBody(String.class);
    Assert.assertNotNull(body);
    Diff d = DiffBuilder.compare(Input.fromString(XML_EXPECTED).build()).withTest(Input.fromString(body).build()).ignoreWhitespace().build();
    Assert.assertFalse(d.toString() + ": " + body, d.hasDifferences());
}
Also used : ProducerTemplate(org.apache.camel.ProducerTemplate) ByteArrayInputStream(java.io.ByteArrayInputStream) Diff(org.xmlunit.diff.Diff) Test(org.junit.Test) DirtiesContext(org.springframework.test.annotation.DirtiesContext)

Aggregations

Diff (org.xmlunit.diff.Diff)22 Test (org.junit.Test)15 File (java.io.File)13 Node (org.w3c.dom.Node)10 Document (org.w3c.dom.Document)7 Input.fromFile (org.xmlunit.builder.Input.fromFile)6 FileInputStream (java.io.FileInputStream)5 FileOutputStream (java.io.FileOutputStream)5 FileWriter (java.io.FileWriter)5 InputStreamReader (java.io.InputStreamReader)5 Files (java.nio.file.Files)5 Arrays (java.util.Arrays)5 HashSet (java.util.HashSet)5 Set (java.util.Set)5 QName (javax.xml.namespace.QName)5 Source (javax.xml.transform.Source)5 StreamSource (javax.xml.transform.stream.StreamSource)5 Assert.assertFalse (org.junit.Assert.assertFalse)5 Assert.assertTrue (org.junit.Assert.assertTrue)5 DMNMarshaller (org.kie.dmn.api.marshalling.DMNMarshaller)5