2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.netconf.util.xml;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertTrue;
13 import static org.junit.Assert.fail;
15 import com.google.common.base.Optional;
16 import javax.xml.xpath.XPathConstants;
17 import javax.xml.xpath.XPathExpression;
18 import org.custommonkey.xmlunit.Diff;
19 import org.custommonkey.xmlunit.XMLUnit;
20 import org.junit.Test;
21 import org.w3c.dom.Document;
22 import org.w3c.dom.Element;
23 import org.xml.sax.SAXParseException;
25 public class XmlUtilTest {
27 private final String xml = "<top xmlns=\"namespace\">\n" +
28 "<innerText>value</innerText>\n" +
29 "<innerPrefixedText xmlns:pref=\"prefixNamespace\">prefix:value</innerPrefixedText>\n" +
30 "<innerPrefixedText xmlns=\"randomNamespace\" xmlns:pref=\"prefixNamespace\">prefix:value</innerPrefixedText>\n" +
34 public void testCreateElement() throws Exception {
35 final Document document = XmlUtil.newDocument();
36 final Element top = XmlUtil.createElement(document, "top", Optional.of("namespace"));
38 top.appendChild(XmlUtil.createTextElement(document, "innerText", "value", Optional.of("namespace")));
39 top.appendChild(XmlUtil.createTextElementWithNamespacedContent(document, "innerPrefixedText", "pref", "prefixNamespace", "value", Optional.of("namespace")));
40 top.appendChild(XmlUtil.createTextElementWithNamespacedContent(document, "innerPrefixedText", "pref", "prefixNamespace", "value", Optional.of("randomNamespace")));
42 document.appendChild(top);
43 assertEquals("top", XmlUtil.createDocumentCopy(document).getDocumentElement().getTagName());
45 XMLUnit.setIgnoreAttributeOrder(true);
46 XMLUnit.setIgnoreWhitespace(true);
48 final Diff diff = XMLUnit.compareXML(XMLUnit.buildControlDocument(xml), document);
49 assertTrue(diff.toString(), diff.similar());
53 public void testLoadSchema() throws Exception {
56 XmlUtil.loadSchema(getClass().getResourceAsStream("/netconfMessages/commit.xml"));
57 fail("Input stream does not contain xsd");
58 } catch (final IllegalStateException e) {
59 assertTrue(e.getCause() instanceof SAXParseException);
65 public void testXPath() throws Exception {
66 final XPathExpression correctXPath = XMLNetconfUtil.compileXPath("/top/innerText");
68 XMLNetconfUtil.compileXPath("!@(*&$!");
69 fail("Incorrect xpath should fail");
70 } catch (IllegalStateException e) {}
71 final Object value = XmlUtil.evaluateXPath(correctXPath, XmlUtil.readXmlToDocument("<top><innerText>value</innerText></top>"), XPathConstants.NODE);
72 assertEquals("value", ((Element) value).getTextContent());