private void assertXMLFilesMatch(String label, IFile testFile, String expectedFileLocation) throws Exception { Reader testReader = null; Reader expectedReader = null; try { testReader = new InputStreamReader(testFile.getContents()); expectedReader = new InputStreamReader( CreateSwitchYardProjectTest.class .getClassLoader() .getResourceAsStream(expectedFileLocation)); Diff diff = XMLUnit.compareXML(testReader, expectedReader); assertTrue(label + ": " + diff.toString(), diff.identical()); } finally { if (testReader != null) { try { testReader.close(); } catch (Exception e) { // for codestyle check e.fillInStackTrace(); } testReader = null; } if (expectedReader != null) { try { expectedReader.close(); } catch (Exception e) { // for codestyle check e.fillInStackTrace(); } expectedReader = null; } } }
private boolean updateExistingItem(AbstractItem item, String config) { boolean created; // Leverage XMLUnit to perform diffs Diff diff; try { String oldJob = item.getConfigFile().asString(); diff = XMLUnit.compareXML(oldJob, config); if (diff.similar()) { LOGGER.log(Level.FINE, format("Item %s is identical", item.getName())); return false; } } catch (Exception e) { // It's not a big deal if we can't diff, we'll just move on LOGGER.warning(e.getMessage()); } LOGGER.log(Level.FINE, format("Updating item %s as %s", item.getName(), config)); Source streamSource = new StreamSource(new StringReader(config)); try { item.updateByXml(streamSource); created = true; } catch (IOException e) { LOGGER.log(Level.WARNING, format("Error writing updated item to file."), e); created = false; } return created; }
private boolean updateExistingJob(AbstractProject<?, ?> project, String config) { boolean created; // Leverage XMLUnit to perform diffs Diff diff; try { String oldJob = project.getConfigFile().asString(); diff = XMLUnit.compareXML(oldJob, config); if (diff.similar()) { LOGGER.log(Level.FINE, String.format("Project %s is identical", project.getName())); return false; } } catch (Exception e) { // It's not a big deal if we can't diff, we'll just move on LOGGER.warning(e.getMessage()); } // TODO Perform comparison between old and new, and print to console // TODO Print out, for posterity, what the user might have changed, in the format of the DSL LOGGER.log(Level.FINE, String.format("Updating project %s as %s", project.getName(), config)); StreamSource streamSource = new StreamSource(new StringReader(config)); // TODO use real xmlReader try { project.updateByXml(streamSource); created = true; } catch (IOException ioex) { LOGGER.log(Level.WARNING, String.format("Error writing updated project to file."), ioex); created = false; } return created; }
public void testCarToXml() throws Exception { String xml = beanXmlConverter.convertToXml(car); XMLUnit.setIgnoreWhitespace(true); Diff diff; diff = new Diff(TestModel.Car.DEFAULT_XML, xml); diff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier()); XMLAssert.assertXMLEqual(diff, true); }
public static void assertAsExpected(String documentString, String expectedFileLocation) throws IOException, SAXException { File expectedReponseFile = new File(expectedFileLocation); String expectedResponseAsString = FileUtils.readFileToString(expectedReponseFile); // Use XML Unit to compare these files Diff myDiff = new Diff(documentString, expectedResponseAsString); Assert.assertTrue("XML identical " + myDiff.toString(), myDiff.identical()); }
@Test public void testWriteComplete() throws Exception { String old_xml = new StringPuller().pull(COMPLETE_XML, getClass()); SwitchYardModel switchyard = _puller.pull(new StringReader(old_xml)); String new_xml = switchyard.toString(); XMLUnit.setIgnoreWhitespace(true); Diff diff = XMLUnit.compareXML(old_xml, new_xml); Assert.assertTrue(diff.toString(), diff.identical()); }
public void assertXMLEqual(String expectedXml, String resultXml) { try { Diff diff = new Diff(expectedXml, resultXml); diff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier()); XMLAssert.assertXMLEqual(diff, true); } catch (Exception e) { throw new RuntimeException("XML Assertion failure", e); } }
/** * Check is the source document is equal to the one produced by the method under test. * * @param message A message to print in case of failure. * @param expected The expected (source) document. * @param actual The actual (output) document. */ private void assertEqual(String message, Document expected, Document actual) { expected.getDocumentElement().normalize(); actual.getDocumentElement().normalize(); // DIRTY HACK WARNING: we add the "xmlns:wi" attribute reported // by DOM, as expected, but not generated by the method under test, // otherwise the comparison would fail. actual.getDocumentElement().setAttribute(Constants.WI_PREFIX, Constants.WI_NS); Diff diff = new Diff(expected, actual); assertTrue(message + ", " + diff.toString(), diff.similar()); }
public void testEncode_WithAllAttributes() throws Exception { TViewRoot root = new TViewRoot(); root.addScript(THtmlInputCommaText.class.getName(), new JavaScriptContext()); htmlInputCommaText.getAttributes().put("accesskey", "a"); htmlInputCommaText.getAttributes().put("alt", "b"); htmlInputCommaText.getAttributes().put("dir", "c"); htmlInputCommaText.getAttributes().put("disabled", Boolean.TRUE); htmlInputCommaText.getAttributes().put("lang", "e"); htmlInputCommaText.getAttributes().put("maxlength", new Integer(5)); htmlInputCommaText.getAttributes().put("onblur", "g"); htmlInputCommaText.getAttributes().put("onchange", "h"); htmlInputCommaText.getAttributes().put("onclick", "i"); htmlInputCommaText.getAttributes().put("ondblclick", "j"); htmlInputCommaText.getAttributes().put("onfocus", "k"); htmlInputCommaText.getAttributes().put("onkeydown", "l"); htmlInputCommaText.getAttributes().put("onkeypress", "m"); htmlInputCommaText.getAttributes().put("onkeyup", "n"); htmlInputCommaText.getAttributes().put("onmousedown", "o"); htmlInputCommaText.getAttributes().put("onmousemove", "p"); htmlInputCommaText.getAttributes().put("onmouseout", "q"); htmlInputCommaText.getAttributes().put("onmouseover", "r"); htmlInputCommaText.getAttributes().put("onmouseup", "s"); htmlInputCommaText.getAttributes().put("onselect", "t"); htmlInputCommaText.getAttributes().put("readonly", Boolean.TRUE); htmlInputCommaText.getAttributes().put("size", new Integer(2)); htmlInputCommaText.getAttributes().put("style", "w"); htmlInputCommaText.getAttributes().put("styleClass", "u"); htmlInputCommaText.getAttributes().put("tabindex", "x"); htmlInputCommaText.getAttributes().put("title", "y"); htmlInputCommaText.getAttributes().put("id", "A"); htmlInputCommaText.getAttributes().put("value", "123"); htmlInputCommaText.getAttributes().put("fraction", "4"); MockFacesContext context = getFacesContext(); root.setLocale(Locale.JAPAN); context.setViewRoot(root); encodeByRenderer(renderer, context, htmlInputCommaText); Diff diff = new Diff( "<input type=\"text\" id=\"A\" name=\"A\" value=\"123\" disabled=\"disabled\" " + "onfocus=\"k;Teeda.THtmlInputCommaText.removeComma(this, ',');this.select();\" " + "onblur=\"g;Teeda.THtmlInputCommaText.convertByKey(this);Teeda.THtmlInputCommaText.addComma(this, 4, ',', '.');\" " + "onkeydown=\"l;return Teeda.THtmlInputCommaText.keycheckForNumber(event, this, 4, '.');\" " + "onkeypress=\"m;return Teeda.THtmlInputCommaText.keycheckForNumber(event, this, 4, '.');\" onkeyup=\"n;Teeda.THtmlInputCommaText.convertByKey(this);\" " + "style=\"w;ime-mode:disabled;\" title=\"y\" onchange=\"h\" dir=\"c\" readonly=\"readonly\" " + "class=\"u\" accesskey=\"a\" ondblclick=\"j\" size=\"2\" onmouseover=\"r\" " + "tabindex=\"x\" maxlength=\"5\" lang=\"e\" onclick=\"i\" alt=\"b\" " + "onmouseout=\"q\" onmousedown=\"o\" onselect=\"t\" onmouseup=\"s\" " + "onmousemove=\"p\" />", getResponseText()); assertEquals(diff.toString(), true, diff.identical()); }
@Test public void testAudioMD_noMD5() throws Exception { Fits fits = new Fits(); // First generate the FITS output File input = new File("testfiles/test.wav"); FitsOutput fitsOut = fits.examine(input); XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat()); String actualXmlStr = serializer.outputString(fitsOut.getFitsXml()); // Read in the expected XML file Scanner scan = new Scanner(new File("testfiles/output/FITS_test_wav_NO_MD5.xml")); String expectedXmlStr = scan.useDelimiter("\\Z").next(); scan.close(); // Set up XMLUnit XMLUnit.setIgnoreWhitespace(true); XMLUnit.setNormalizeWhitespace(true); Diff diff = new Diff(expectedXmlStr, actualXmlStr); // Initialize attributes or elements to ignore for difference checking diff.overrideDifferenceListener( new IgnoreNamedElementsDifferenceListener( "version", "toolversion", "dateModified", "fslastmodified", "lastmodified", "startDate", "startTime", "timestamp", "fitsExecutionTime", "executionTime", "filepath", "location")); DetailedDiff detailedDiff = new DetailedDiff(diff); // Display any Differences List<Difference> diffs = detailedDiff.getAllDifferences(); if (!diff.identical()) { StringBuffer differenceDescription = new StringBuffer(); differenceDescription.append(diffs.size()).append(" differences"); System.out.println(differenceDescription.toString()); for (Difference difference : diffs) { System.out.println(difference.toString()); } } assertTrue("Differences in XML", diff.identical()); }
@Test public void testReadRecord() throws Exception { XmlRecord xmlRecord = xmlRecordReader.readRecord(); String expectedPayload = getXmlFromFile("/person.xml"); String actualPayload = xmlRecord.getPayload(); XMLUnit.setIgnoreWhitespace(true); Diff diff = new Diff(expectedPayload, actualPayload); assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(1); assertThat(diff.similar()).isTrue(); }
public static void assertSimilarXml(String expectedXml, String xml) { XMLUnit.setIgnoreWhitespace(true); Diff diff; try { diff = XMLUnit.compareXML(xml, expectedXml); } catch (SAXException e) { throw new IllegalArgumentException("Could not run XML comparison", e); } catch (IOException e) { throw new IllegalArgumentException("Could not run XML comparison", e); } String message = "Diff: " + diff.toString() + CharUtils.LF + "XML: " + xml; assertTrue(message, diff.similar()); }
public void test_should_parse_2nd_document() throws IOException, ParserConfigurationException, SAXException { final XMLSerializer xmlSerializer = getXmlSerializer(); String fixture = toString("net/sf/json/xml/idml_document2.idms"); JSON json = xmlSerializer.read(fixture); final String result = xmlSerializer.write(json); final Diff diff = compareXML(stripWhiteSpace(fixture), stripWhiteSpace(result)); assertTrue("Found difference: " + diff.toString(), diff.identical()); }
@Override public final boolean equals(Object other) { if (other == null) return false; if (other == this) return true; if (!(other instanceof LolStatus)) return false; final LolStatus otherStatus = (LolStatus) other; Diff diff; try { diff = new Diff(otherStatus.toString(), toString()); return diff.similar(); } catch (SAXException | IOException e) { e.printStackTrace(); } return false; }
@Test public void testEquality() throws Exception { // convert FitsOutput xml doms to strings for the diff StringWriter sw = new StringWriter(); Document expectedDom = expected.getFitsXml(); Document actualDom = actual.getFitsXml(); serializer.output(actualDom, sw); String actualStr = sw.toString(); sw = new StringWriter(); serializer.output(expectedDom, sw); String expectedStr = sw.toString(); // get the file name in case of a failure FitsMetadataElement item = actual.getMetadataElement("filename"); DifferenceListener myDifferenceListener = new IgnoreAttributeValuesDifferenceListener(); Diff diff = new Diff(expectedStr, actualStr); diff.overrideDifferenceListener(myDifferenceListener); assertXMLIdentical("Error comparing: " + item.getValue(), diff, true); }
public static void assertExportedTmxFilesEqual(File testFile, InputStream goalStream) throws IOException, SAXException { try (Reader testReader = Files.newReader(testFile, StandardCharsets.UTF_8); Reader goldReader = new InputStreamReader(goalStream, StandardCharsets.UTF_8)) { Diff diff = new Diff(goldReader, testReader); diff.overrideDifferenceListener( new DifferenceListener() { @Override public void skippedComparison(Node arg0, Node arg1) {} @Override public int differenceFound(Difference d) { Node node = d.getControlNodeDetail().getNode(); if (node.getNodeType() == Node.ATTRIBUTE_NODE && "creationtoolversion".equals(node.getNodeName())) { return RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR; } return 0; } }); assertTrue(diff.similar()); } }
protected void testXsltUpgrade( final Resource xslResource, final PortalDataKey dataKey, final Resource inputResource, final Resource expectedResultResource, final Resource xsdResource) throws Exception { final XmlUtilities xmlUtilities = new XmlUtilitiesImpl() { @Override public Templates getTemplates(Resource stylesheet) throws TransformerConfigurationException, IOException { final TransformerFactory transformerFactory = TransformerFactory.newInstance(); return transformerFactory.newTemplates(new StreamSource(stylesheet.getInputStream())); } }; final XsltDataUpgrader xsltDataUpgrader = new XsltDataUpgrader(); xsltDataUpgrader.setPortalDataKey(dataKey); xsltDataUpgrader.setXslResource(xslResource); xsltDataUpgrader.setXmlUtilities(xmlUtilities); xsltDataUpgrader.afterPropertiesSet(); // Create XmlEventReader (what the JaxbPortalDataHandlerService has) final XMLInputFactory xmlInputFactory = xmlUtilities.getXmlInputFactory(); final XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(inputResource.getInputStream()); final Node sourceNode = xmlUtilities.convertToDom(xmlEventReader); final DOMSource source = new DOMSource(sourceNode); final DOMResult result = new DOMResult(); xsltDataUpgrader.upgradeData(source, result); // XSD Validation final String resultString = XmlUtilitiesImpl.toString(result.getNode()); if (xsdResource != null) { final Schema schema = this.loadSchema(new Resource[] {xsdResource}, XMLConstants.W3C_XML_SCHEMA_NS_URI); final Validator validator = schema.newValidator(); try { validator.validate(new StreamSource(new StringReader(resultString))); } catch (Exception e) { throw new XmlTestException( "Failed to validate XSLT output against provided XSD", resultString, e); } } XMLUnit.setIgnoreWhitespace(true); try { Diff d = new Diff( new InputStreamReader(expectedResultResource.getInputStream()), new StringReader(resultString)); assertTrue("Upgraded data doesn't match expected data: " + d, d.similar()); } catch (Exception e) { throw new XmlTestException( "Failed to assert similar between XSLT output and expected XML", resultString, e); } catch (Error e) { throw new XmlTestException( "Failed to assert similar between XSLT output and expected XML", resultString, e); } }
private void runProjectTest(String projectName, boolean isWeb) throws Exception { ResolverConfiguration configuration = new ResolverConfiguration(); IProject project = importProject("test-data/projects/" + projectName + "/pom.xml", configuration); waitForJobs(); project.build(IncrementalProjectBuilder.FULL_BUILD, monitor); waitForJobs(); assertNoErrors(project); // make sure we get through an incremental build (SWITCHYARD-1108) project.touch(new NullProgressMonitor()); project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, monitor); waitForJobs(); assertNoErrors(project); assertTrue( project .getFile("target/classes/META-INF/switchyard.xml") .isSynchronized(IResource.DEPTH_ZERO)); assertTrue(project.getFile("target/classes/META-INF/switchyard.xml").isAccessible()); assertTrue(!project.getFile("src/main/java/META-INF/MANIFEST.MF").exists()); Reader sourceReader = null; Reader testReader = null; try { sourceReader = new InputStreamReader( project.getFile("target/classes/META-INF/switchyard.xml").getContents()); testReader = new InputStreamReader( SwitchYardConfigurationTest.class .getClassLoader() .getResourceAsStream( "test-data/validation/" + projectName + (isWeb ? "/WEB-INF/switchyard.xml" : "/META-INF/switchyard.xml"))); XMLUnit.setIgnoreComments(true); XMLUnit.setIgnoreWhitespace(true); Diff diff = XMLUnit.compareXML(sourceReader, testReader); diff.overrideElementQualifier(new ElementNameAndAttributeQualifier()); assertTrue(diff.toString(), diff.similar()); } finally { if (sourceReader != null) { try { sourceReader.close(); } catch (Exception e) { // for codestyle check e.fillInStackTrace(); } } if (testReader != null) { try { testReader.close(); } catch (Exception e) { // for codestyle check e.fillInStackTrace(); } } } }
/** * Compare two documents and check if they are the same or not. * * @param controlDoc * @param testDoc * @return true if the documents have the same elements and attributes, reguardless of order */ public static boolean compareDocuments(final Document controlDoc, final Document testDoc) { final Diff xmldiff = new Diff(controlDoc, testDoc); return xmldiff.similar(); }
/* * (non-Javadoc) * * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], * org.exist.xquery.value.Sequence) */ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException { if (context.getProfiler().isEnabled()) { context.getProfiler().start(this); context .getProfiler() .message( this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies())); if (contextSequence != null) context .getProfiler() .message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence); if (contextItem != null) context .getProfiler() .message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence()); } Expression arg1 = getArgument(0); Sequence s1 = arg1.eval(contextSequence, contextItem); Expression arg2 = getArgument(1); context.pushDocumentContext(); Sequence s2 = arg2.eval(contextSequence, contextItem); context.popDocumentContext(); if (s1.isEmpty()) { return BooleanValue.valueOf(s2.isEmpty()); } else if (s2.isEmpty()) { return BooleanValue.valueOf(s1.isEmpty()); } Sequence result = null; StringBuffer v1 = new StringBuffer(); StringBuffer v2 = new StringBuffer(); try { if (s1.hasMany()) { for (int i = 0; i < s1.getItemCount(); i++) { v1.append(serialize((NodeValue) s1.itemAt(i))); } } else { v1.append(serialize((NodeValue) s1.itemAt(0))); } if (s2.hasMany()) { for (int i = 0; i < s2.getItemCount(); i++) { v2.append(serialize((NodeValue) s2.itemAt(i))); } } else { v2.append(serialize((NodeValue) s2.itemAt(0))); } Diff d = new Diff(v1.toString(), v2.toString()); boolean identical = d.identical(); if (!identical) { logger.warn("Diff result: " + d.toString()); } result = new BooleanValue(identical); } catch (Exception e) { throw new XPathException( this, "An exception occurred while serializing node " + "for comparison: " + e.getMessage(), e); } if (context.getProfiler().isEnabled()) context.getProfiler().end(this, "", result); return result; }
public static void assertSimilarXml(String expectedXml, String xml) throws Exception { Diff diff = isSimilarXml(expectedXml, xml); String message = "Diff: " + diff.toString() + CharUtils.LF + "XML: " + xml; assertTrue(message, diff.similar()); }