@Test public void setPresenceTypeTest() throws IOException, SAXException, ParserConfigurationException { Presence.Type type = Presence.Type.unavailable; Presence.Type type2 = Presence.Type.subscribe; StringBuilder controlBuilder = new StringBuilder(); controlBuilder .append("<presence") .append(" type=\"") .append(type) .append("\">") .append("</presence>"); String control = controlBuilder.toString(); Presence presenceTypeInConstructor = new Presence(type); presenceTypeInConstructor.setPacketID(Packet.ID_NOT_AVAILABLE); assertEquals(type, presenceTypeInConstructor.getType()); assertXMLEqual(control, presenceTypeInConstructor.toXML()); controlBuilder = new StringBuilder(); controlBuilder .append("<presence") .append(" type=\"") .append(type2) .append("\">") .append("</presence>"); control = controlBuilder.toString(); Presence presenceTypeSet = getNewPresence(); presenceTypeSet.setType(type2); assertEquals(type2, presenceTypeSet.getType()); assertXMLEqual(control, presenceTypeSet.toXML()); }
@Test public void verifyBasicItem() throws Exception { Item simpleItem = new Item(); String simpleCtrl = "<item />"; assertXMLEqual(simpleCtrl, simpleItem.toXML()); Item idItem = new Item("uniqueid"); String idCtrl = "<item id='uniqueid'/>"; assertXMLEqual(idCtrl, idItem.toXML()); Item itemWithNodeId = new Item("testId", "testNode"); String nodeIdCtrl = "<item id='testId' node='testNode' />"; assertXMLEqual(nodeIdCtrl, itemWithNodeId.toXML()); }
@Test public void write() throws IOException, SAXException { Feed feed = new Feed("atom_1.0"); feed.setTitle("title"); Entry entry1 = new Entry(); entry1.setId("id1"); entry1.setTitle("title1"); Entry entry2 = new Entry(); entry2.setId("id2"); entry2.setTitle("title2"); List<Entry> entries = new ArrayList<>(2); entries.add(entry1); entries.add(entry2); feed.setEntries(entries); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(feed, null, outputMessage); assertEquals( "Invalid content-type", new MediaType("application", "atom+xml", StandardCharsets.UTF_8), outputMessage.getHeaders().getContentType()); String expected = "<feed xmlns=\"http://www.w3.org/2005/Atom\">" + "<title>title</title>" + "<entry><id>id1</id><title>title1</title></entry>" + "<entry><id>id2</id><title>title2</title></entry></feed>"; assertXMLEqual(expected, outputMessage.getBodyAsString(StandardCharsets.UTF_8)); }
private void suggestion(HTTPMixIn httpMixIn, int interaction) throws Exception { String actual = httpMixIn.postString( "http://localhost:8080/suggestion/SuggestionService", xml("request", interaction)); String expected = xml("response", interaction); XMLAssert.assertXMLEqual(expected, actual); }
@Test public void verifyExtractionTempGenNoRequired() throws TestEvalException, SAXException, IOException, TransformerException { String entityType = "no-primary-required.json"; DOMHandle res = new DOMHandle(); logger.info("Validating extraction template for:" + entityType); try { res = evalOneResult("fn:doc( '" + entityType + "')=>es:extraction-template-generate()", res); } catch (TestEvalException e) { throw new RuntimeException(e); } // logger.info(docMgr.read(entityType.replaceAll("\\.(xml|json)", ".tdex"), new // StringHandle()).get()); // DOMHandle handle = docMgr.read(entityType.replaceAll("\\.(xml|json)", ".tdex"), new // DOMHandle()); Document template = res.get(); InputStream is = this.getClass() .getResourceAsStream( "/test-extraction-template/" + entityType.replace(".json", ".xml")); Document filesystemXML = builder.parse(is); // debugOutput(template); XMLUnit.setIgnoreWhitespace(true); XMLAssert.assertXMLEqual( "Must be no validation errors for schema " + entityType + ".", filesystemXML, template); }
@Test public void verifyExtractionTemplateGenerate() throws TestEvalException, SAXException, IOException, TransformerException { for (String entityType : entityTypes) { if (entityType.contains(".json") || entityType.contains(".jpg") || entityType.contains("primary-key-as-a-ref")) { continue; } logger.info("Validating extraction template for:" + entityType); // logger.info(docMgr.read(entityType.replaceAll("\\.(xml|json)", ".tdex"), new // StringHandle()).get()); DOMHandle handle = docMgr.read(entityType.replaceAll("\\.(xml|json)", ".tdex"), new DOMHandle()); Document template = handle.get(); InputStream is = this.getClass().getResourceAsStream("/test-extraction-template/" + entityType); Document filesystemXML = builder.parse(is); // debugOutput(template); XMLUnit.setIgnoreWhitespace(true); XMLAssert.assertXMLEqual( "Must be no validation errors for schema " + entityType + ".", filesystemXML, template); } }
protected void handleXmlContent(final byte[] reportOutput, final File goldSample) throws Exception { final byte[] goldData; final InputStream goldInput = new BufferedInputStream(new FileInputStream(goldSample)); final MemoryByteArrayOutputStream goldByteStream = new MemoryByteArrayOutputStream( Math.min(1024 * 1024, (int) goldSample.length()), 1024 * 1024); try { IOUtils.getInstance().copyStreams(goldInput, goldByteStream); goldData = goldByteStream.toByteArray(); if (Arrays.equals(goldData, reportOutput)) { return; } } finally { goldInput.close(); } final Reader reader = new InputStreamReader(new ByteArrayInputStream(goldData), "UTF-8"); final ByteArrayInputStream inputStream = new ByteArrayInputStream(reportOutput); final Reader report = new InputStreamReader(inputStream, "UTF-8"); try { XMLAssert.assertXMLEqual("File " + goldSample + " failed", new Diff(reader, report), true); } catch (AssertionFailedError afe) { debugOutput(reportOutput, goldSample); throw afe; } finally { reader.close(); } }
@Test public void parseEmptyTag() throws Exception { String itemContent = "<foo xmlns='smack:test'><bar/></foo>"; XmlPullParser parser = PacketParserUtils.getParserFor( "<message from='pubsub.myserver.com' to='*****@*****.**' id='foo'>" + "<event xmlns='http://jabber.org/protocol/pubsub#event'>" + "<items node='testNode'>" + "<item id='testid1' >" + itemContent + "</item>" + "</items>" + "</event>" + "</message>"); Stanza message = PacketParserUtils.parseMessage(parser); ExtensionElement eventExt = message.getExtension(PubSubNamespace.EVENT.getXmlns()); assertTrue(eventExt instanceof EventElement); EventElement event = (EventElement) eventExt; assertEquals(EventElementType.items, event.getEventType()); assertEquals(1, event.getExtensions().size()); assertTrue(event.getExtensions().get(0) instanceof ItemsExtension); assertEquals(1, ((ItemsExtension) event.getExtensions().get(0)).items.size()); ExtensionElement itemExt = ((ItemsExtension) event.getExtensions().get(0)).items.get(0); assertTrue(itemExt instanceof PayloadItem<?>); PayloadItem<?> item = (PayloadItem<?>) itemExt; assertEquals("testid1", item.getId()); assertTrue(item.getPayload() instanceof SimplePayload); assertXMLEqual(itemContent, ((SimplePayload) item.getPayload()).toXML().toString()); }
@Test public void testStringAsPayload() throws Exception { Object transformed = transformer.doTransform(buildMessage(docAsString)); assertEquals("Wrong return type for string payload", String.class, transformed.getClass()); String transformedString = (String) transformed; assertXMLEqual("String incorrect after transform", outputAsString, transformedString); }
@Test public void testMergeMap() throws Exception { final File filename = new File(srcDir, "merged.xml"); final KeyrefReader keyrefreader = new KeyrefReader(); keyrefreader.read(filename.toURI(), readMap(filename)); final KeyScope act = keyrefreader.getKeyDefinition(); final Map<String, String> exp = new HashMap<String, String>(); exp.put( "toner-specs", "<keydef class=\"+ map/topicref mapgropup-d/keydef \" keys=\"toner-specs\" href=\"toner-type-a-specs.dita\"/>"); exp.put( "toner-handling", "<keydef class=\"+ map/topicref mapgropup-d/keydef \" keys=\"toner-handling\" href=\"toner-type-b-handling.dita\"/>"); exp.put( "toner-disposal", "<keydef class=\"+ map/topicref mapgropup-d/keydef \" keys=\"toner-disposal\" href=\"toner-type-c-disposal.dita\"/>"); TestUtils.resetXMLUnit(); XMLUnit.setIgnoreWhitespace(true); assertEquals(exp.keySet(), act.keySet()); for (Map.Entry<String, String> e : exp.entrySet()) { final Document ev = keyDefToDoc(e.getValue()); final Document av = act.get(e.getKey()).element.getOwnerDocument(); assertXMLEqual(ev, av); } }
public void testElementConstructor() throws Exception { final SamlCredential samlPrincipal = new SamlCredential(assertionElement); final InputSource actual = new InputSource(new StringReader(samlPrincipal.getAssertionAsString())); XMLAssert.assertXMLEqual(expectedAssertion, actual); }
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); }
@Test public void verifyPayloadItem() throws Exception { SimplePayload payload = new SimplePayload(null, null, "<data>This is the payload</data>"); PayloadItem<SimplePayload> simpleItem = new PayloadItem<SimplePayload>(payload); String simpleCtrl = "<item>" + payload.toXML() + "</item>"; assertXMLEqual(simpleCtrl, simpleItem.toXML()); PayloadItem<SimplePayload> idItem = new PayloadItem<SimplePayload>("uniqueid", payload); String idCtrl = "<item id='uniqueid'>" + payload.toXML() + "</item>"; assertXMLEqual(idCtrl, idItem.toXML()); PayloadItem<SimplePayload> itemWithNodeId = new PayloadItem<SimplePayload>("testId", "testNode", payload); String nodeIdCtrl = "<item id='testId' node='testNode'>" + payload.toXML() + "</item>"; assertXMLEqual(nodeIdCtrl, itemWithNodeId.toXML()); }
@Test public void testExtractMetadata() throws SAXException, IOException { QueryManager queryMgr = Common.client.newQueryManager(); String combined = "<search xmlns=\"http://marklogic.com/appservices/search\">" + "<query>" + "<value-query>" + "<element ns=\"http://marklogic.com/xdmp/json\" name=\"firstKey\"/>" + "<text>first value</text>" + "</value-query>" + "</query>" + "<options>" + "<extract-metadata>" + "<qname elem-ns=\"http://marklogic.com/xdmp/json\" elem-name=\"subKey\"/>" + "</extract-metadata>" + "</options>" + "</search>"; StringHandle rawHandle = new StringHandle(combined); RawCombinedQueryDefinition rawDef = queryMgr.newRawCombinedQueryDefinition(rawHandle); SearchHandle sh = queryMgr.search(rawDef, new SearchHandle()); MatchDocumentSummary[] summaries = sh.getMatchResults(); assertNotNull(summaries); assertEquals("expected 1 result", 1, summaries.length); MatchDocumentSummary matchResult = summaries[0]; Document metadata = matchResult.getMetadata(); Element subKey = (Element) metadata.getElementsByTagNameNS("http://marklogic.com/xdmp/json", "subKey").item(0); assertEquals("string", subKey.getAttribute("type")); assertEquals("sub value", subKey.getTextContent()); String docStr = Common.testDocumentToString(metadata); String handleStr = matchResult.getMetadata(new StringHandle()).get(); assertXMLEqual("Different metadata for handle", docStr, handleStr); Document snippet = matchResult.getSnippets()[0]; docStr = Common.testDocumentToString(snippet); handleStr = matchResult.getSnippetIterator(new StringHandle()).next().get(); assertXMLEqual("Different snippet for handle", docStr, handleStr); }
/** @throws Exception */ @Test public void testWorkspace() throws Exception { AppService appService = new AppService(); appService.getWorkspace().add(new XsdWorkspace("http://example.org")); // $NON-NLS-1$ String actual = marshall(appService); String expected = getExpectedWorkspaceXML("xsd"); // $NON-NLS-1$ XMLAssert.assertXMLEqual(expected, actual); }
@Test public void testGetSource() throws Exception { StringResult result = new StringResult(); transformer.transform(soapHeader.getSource(), result); assertXMLEqual( "Invalid contents of header", "<Header xmlns='http://www.w3.org/2003/05/soap-envelope' />", result.toString()); }
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); } }
@Test public void testDocumentAsPayload() throws Exception { Object transformed = transformer.doTransform(buildMessage(XmlTestUtil.getDocumentForString(docAsString))); assertTrue( "Wrong return type for document payload", Document.class.isAssignableFrom(transformed.getClass())); Document transformedDocument = (Document) transformed; assertXMLEqual(outputAsString, XmlTestUtil.docToString(transformedDocument)); }
private void test(String bodyHtml, String cssClass, String expected) throws Exception { Document document = Jsoup.parseBodyFragment(bodyHtml); Element element = document.getElementsByTag("tag").first(); Moulder moulder = new AddCssClassMoulder(cssClass); List<Node> processed = moulder.process(element); assertXMLEqual( new StringReader("<body>" + expected + "</body>"), new StringReader(html(processed))); }
@Test public void testSourceAsPayload() throws Exception { Object transformed = transformer.doTransform(buildMessage(new StringSource(docAsString))); assertEquals("Wrong return type for source payload", DOMResult.class, transformed.getClass()); DOMResult result = (DOMResult) transformed; assertXMLEqual( "Document incorrect after transformation", XmlTestUtil.getDocumentForString(outputAsString), (Document) result.getNode()); }
@Test public void setPresenceModeTest() throws IOException, SAXException, ParserConfigurationException { Presence.Mode mode1 = Presence.Mode.dnd; final int priority = 10; final String status = "This is a test of the emergency broadcast system."; Presence.Mode mode2 = Presence.Mode.chat; StringBuilder controlBuilder = new StringBuilder(); controlBuilder .append("<presence>") .append("<status>") .append(status) .append("</status>") .append("<priority>") .append(priority) .append("</priority>") .append("<show>") .append(mode1) .append("</show>") .append("</presence>"); String control = controlBuilder.toString(); Presence presenceModeInConstructor = new Presence(Presence.Type.available, status, priority, mode1); presenceModeInConstructor.setPacketID(Packet.ID_NOT_AVAILABLE); assertEquals(mode1, presenceModeInConstructor.getMode()); assertXMLEqual(control, presenceModeInConstructor.toXML()); controlBuilder = new StringBuilder(); controlBuilder .append("<presence>") .append("<show>") .append(mode2) .append("</show>") .append("</presence>"); control = controlBuilder.toString(); Presence presenceModeSet = getNewPresence(); presenceModeSet.setMode(mode2); assertEquals(mode2, presenceModeSet.getMode()); assertXMLEqual(control, presenceModeSet.toXML()); }
@Test public void customizeMarshaller() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MyJaxb2RootElementHttpMessageConverter myConverter = new MyJaxb2RootElementHttpMessageConverter(); myConverter.write(new MyRootElement(new MyCustomElement("a", "b")), null, outputMessage); assertXMLEqual( "Invalid result", "<myRootElement><element>a|||b</element></myRootElement>", outputMessage.getBodyAsString(Charset.forName("UTF-8"))); }
@Test public void testStringAsPayloadUseResultFactoryTrue() throws Exception { transformer.setAlwaysUseResultFactory(true); Object transformed = transformer.doTransform(buildMessage(docAsString)); assertEquals( "Wrong return type for useFactories true", DOMResult.class, transformed.getClass()); DOMResult result = (DOMResult) transformed; assertXMLEqual( "Document incorrect after transformation", XmlTestUtil.getDocumentForString(outputAsString), (Document) result.getNode()); }
@Test public void testGetFlightsXml() throws AirlineException, DatatypeConfigurationException, TransformerException { GetFlightsRequest request = JAXB.unmarshal(getStream("request1.xml"), GetFlightsRequest.class); GetFlightsResponse response = endpoint.getFlights(request); DOMResult domResponse = new DOMResult(); JAXB.marshal(response, domResponse); XMLUnit.setIgnoreWhitespace(true); XMLAssert.assertXMLEqual(getDocument("response1.xml"), (Document) domResponse.getNode()); }
@Test public void writeXmlRootElementSubclass() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(rootElementCglib, null, outputMessage); assertEquals( "Invalid content-type", new MediaType("application", "xml"), outputMessage.getHeaders().getContentType()); assertXMLEqual( "Invalid result", "<rootElement><type s=\"Hello World\"/></rootElement>", outputMessage.getBodyAsString(Charset.forName("UTF-8"))); }
public void testGetEcho() throws Exception { // CXF has built in support for understanding GET requests. They are of the form: // http://host/service/OPERATION/PARAM_NAME/PARAM_VALUE MuleClient client = new MuleClient(); Map<String, String> props = new HashMap<String, String>(); props.put("http.method", "GET"); MuleMessage result = client.send("http://localhost:65082/services/EchoUMO/echo/text/hello", "", props); assertNotNull(result); assertFalse(result.getPayload() instanceof NullPayload); XMLAssert.assertXMLEqual(expectedGetResponse, result.getPayloadAsString()); }
@Test public void testAddNotUnderstood() throws Exception { Soap12Header soap12Header = (Soap12Header) soapHeader; QName headerName = new QName("http://www.springframework.org", "NotUnderstood", "spring-ws"); soap12Header.addNotUnderstoodHeaderElement(headerName); StringResult result = new StringResult(); transformer.transform(soapHeader.getSource(), result); assertXMLEqual( "Invalid contents of header", "<Header xmlns='http://www.w3.org/2003/05/soap-envelope' >" + "<NotUnderstood qname='spring-ws:NotUnderstood' xmlns:spring-ws='http://www.springframework.org' />" + "</Header>", result.toString()); }
@Test public void testKeyrefReader() throws Exception { final File filename = new File(srcDir, "keyrefreader.xml"); // final Set <String> set = new HashSet<String> (); // set.add("blatview"); // set.add("blatfeference"); // set.add("blatintro"); // set.add("keyword"); // set.add("escape"); // set.add("top"); // set.add("nested"); final KeyrefReader keyrefreader = new KeyrefReader(); // keyrefreader.setKeys(set); keyrefreader.read(filename.toURI(), readMap(filename)); final KeyScope act = keyrefreader.getKeyDefinition(); final Map<String, String> exp = new HashMap<String, String>(); exp.put( "blatfeference", "<topicref keys='blatview blatfeference blatintro' href='blatview.dita' navtitle='blatview' locktitle='yes' class='- map/topicref '/>"); exp.put( "blatview", "<topicref keys='blatview blatfeference blatintro' href='blatview.dita' navtitle='blatview' locktitle='yes' class='- map/topicref '/>"); exp.put( "blatintro", "<topicref keys='blatview blatfeference blatintro' href='blatview.dita' navtitle='blatview' locktitle='yes' class='- map/topicref '/>"); exp.put( "keyword", "<topicref keys='keyword' class='- map/topicref '><topicmeta class='- map/topicmeta '><keywords class='- topic/keywords '><keyword class='- topic/keyword '>keyword value</keyword></keywords></topicmeta></topicref>"); exp.put( "escape", "<topicref keys='escape' class='- map/topicref ' navtitle='&<>"''><topicmeta class='- map/topicmeta '><keywords class='- topic/keywords '><keyword class='- topic/keyword '>&<>"'</keyword></keywords></topicmeta></topicref>"); exp.put( "top", "<topicref keys='top' class='- map/topicref ' navtitle='top'><topicmeta class='- map/topicmeta '><keywords class='- topic/keywords '><keyword class='- topic/keyword '>top keyword</keyword></keywords></topicmeta><topicref keys='nested' class='- map/topicref ' navtitle='nested'><topicmeta class='- map/topicmeta '><keywords class='- topic/keywords '><keyword class='- topic/keyword '>nested keyword</keyword></keywords></topicmeta></topicref></topicref>"); exp.put( "nested", "<topicref keys='nested' class='- map/topicref ' navtitle='nested'><topicmeta class='- map/topicmeta '><keywords class='- topic/keywords '><keyword class='- topic/keyword '>nested keyword</keyword></keywords></topicmeta></topicref>"); TestUtils.resetXMLUnit(); XMLUnit.setIgnoreWhitespace(true); assertEquals(exp.keySet(), act.keySet()); for (Map.Entry<String, String> e : exp.entrySet()) { final Document ev = keyDefToDoc(e.getValue()); final Document av = act.get(e.getKey()).element.getOwnerDocument(); assertXMLEqual(ev, av); } }
/** * Test method for {@link * org.ebayopensource.turmeric.eclipse.utils.xml.XMLUtil#convertXMLToString(org.w3c.dom.Node)}. * * @throws ParserConfigurationException * @throws IOException * @throws SAXException * @throws TransformerException * @throws TransformerFactoryConfigurationError */ @Test public void testConvertXMLToString() throws SAXException, IOException, ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException { InputStream input = null; try { input = new ByteArrayInputStream(XML_DATA.getBytes()); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input); String result = XMLUtil.convertXMLToString(doc); XMLAssert.assertXMLEqual("Comparing gold copy with generated xml", XML_DATA, result); // Assert.assertEquals(XML_DATA, result); } finally { IOUtils.closeQuietly(input); } }
@Test public void testEsquemaFamiliarCasoOk() throws IOException, SAXException { // Creo los mocks testKit.replaceService( "TipoGrupoFamiliar", new ExchangeHandler() { @Override public void handleMessage(Exchange exchange) throws HandlerException { String request = exchange.getMessage().getContent(String.class); LOG.info("getEsquemaFamiliar provider:" + request); try { // Verifico que el request que entra al mock sea el esperado XMLAssert.assertXMLEqual( CotizadorPlanesUnitTest.loadFile( "unitTest/providerMockExpectedRequest/getExquemaFamiliarProviderExpectedRequest.xml"), request); // Genero la respuesta mockeada String mockResponse = CotizadorPlanesUnitTest.loadFile( "unitTest/providerMockResponse/getExquemaFamiliarProviderResponse.xml"); LOG.info("mockResponse:" + mockResponse); // Envio la respuesta mockeada exchange.send(exchange.createMessage().setContent(mockResponse)); } catch (AssertionError a) { LOG.error("El request al provider no valida con el esperado", a); throw new HandlerException(a); } catch (Exception e) { LOG.error("Sucedió un error al obtener el archivo", e); throw new HandlerException(e); } } @Override public void handleFault(Exchange exchange) { throw new RuntimeException("Sucedio error inesperado"); } }); // Ejecuto el servicio Message response = getEsquemaFamiliar.sendInOut( CotizadorPlanesUnitTest.loadFile( "unitTest/serviceRequest/getEsquemaFamiliarServiceRequest.xml")); // Verifico los resultados XMLAssert.assertXMLEqual( CotizadorPlanesUnitTest.loadFile( "unitTest/serviceExpectedResponse/getExquemaFamiliarServiceExpectedResponse.xml"), response.getContent(String.class)); }