Package net.exoego.queen.xml

Source Code of net.exoego.queen.xml.XElementTest

package net.exoego.queen.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.util.List;

import net.exoego.function.Func1;
import net.exoego.function.helper.OnString;
import org.hamcrest.CoreMatchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.w3c.dom.UserDataHandler;

import static net.exoego.util.Make.array;
import static net.exoego.util.Make.list;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;

// some case from http://msdn.microsoft.com/ja-jp/library/vstudio/bb341343.aspx
public class XElementTest {
    private final XNamespace aw = XNamespace.namespace("", "http://www.adventure-works.com");
    private final XNamespace fc = XNamespace.namespace("fc", "www.fourthcoffee.com");
    private XElement x;
    private XElement xns;
    private XElement prefixed;
    private TemporaryFolder folder;

    @Before
    public void setUp() throws IOException {
        x = new XElement(new XDocument(new XElement("tag",
                                                    new XElement("child"),
                                                    "text",
                                                    new XElement("child"))).getDocumentElement());
        xns = new XElement(XNamespace.namespace("http://example.com"),
                           "tag",
                           "text",
                           new XElement(XNamespace.namespace("http://example.com"), "child"));
        prefixed = new XElement(XNamespace.namespace("aa", "http://example.com"), "child");

        folder = new TemporaryFolder();
        folder.create();
    }

    @After
    public void tearDown() {
        folder.delete();
    }

    @Test
    public void testXElementIsAElement() throws Exception {
        assertThat(new XElement("node"), isA(Element.class));
    }

    @Test
    public void testCreateEmptyElement() throws Exception {
        final XElement e = new XElement("root");
        assertThat(e.toString(), is("<root/>"));
    }

    @Test
    public void testCreateStringContent() throws Exception {
        final XElement e = new XElement("root", "Some Text");
        assertThat(e.toString(), is("<root>Some Text</root>"));
    }

    @Test
    public void testCreateOtherObjectContent() throws Exception {
        // Any object other than a XElement or a XAttr object is converted to string.
        final XElement e = new XElement("root", true);
        assertThat(e.toString(), is("<root>true</root>"));
    }

    @Test
    public void testCreateOtherArrayContent() throws Exception {
        // Any collection other than a collection of XElement or XAttr objects
        // are converted to strings. The strings are concatenated and added.
        final XElement e = new XElement("root", "abc", "def", "ghi");
        assertThat(e.toString(), is("<root>abcdefghi</root>"));
    }

    @Test
    public void testCreateOtherIterableContent() throws Exception {
        // Any collection other than a collection of XElement or XAttr objects
        // are converted to strings. The strings are concatenated and added.
        final XElement e = new XElement("root", list("abc", "def", "ghi"));
        assertThat(e.toString(), is("<root>abcdefghi</root>"));
    }

    @Test
    public void testCreateXElementContent() throws Exception {
        final XElement tree = new XElement("root", new XElement("child1", 1));
        assertThat(tree.toString(), is("<root><child1>1</child1></root>"));
    }

    @Test
    public void testCreateXElementArrayContent() throws Exception {
        final XElement tree = new XElement("root",
                                           new XElement("child1", 1),
                                           new XElement("child2", "2"),
                                           new XElement("child3", list(1, null, 2)));
        assertThat(tree.toString(), is("<root><child1>1</child1><child2>2</child2><child3>1null2</child3></root>"));
    }

    @Test
    public void testCreateXElementIterableContent() throws Exception {
        final List<XElement> list = list(new XElement("child1", 1),
                                         new XElement("child2", "2"),
                                         new XElement("child3", list(1, null, 2)));
        final XElement tree = new XElement("root", list);
        assertThat(tree.toString(), is("<root><child1>1</child1><child2>2</child2><child3>1null2</child3></root>"));
    }

    @Test
    public void testCreateXElementDeepNested() throws Exception {
        final XElement src = new XElement("Root",
                                          new XElement("Child1", "data1"),
                                          new XElement("Child2", "data2"),
                                          list(new XElement("Child3", "data3"),
                                               new XElement("Child2", "data4"),
                                               array(1, 2, 3)));
        assertThat(src.toString(), is("<Root>" +
                                      "<Child1>data1</Child1>" +
                                      "<Child2>data2</Child2>" +
                                      "<Child3>data3</Child3>" +
                                      "<Child2>data4</Child2>123</Root>"));
    }

    @Test
    public void testCreateXAttributeContent() throws Exception {
        final XElement e = new XElement("root", new XAttr("attr", "value"));
        assertThat(e.toString(), is("<root attr=\"value\"/>"));
    }

    @Test
    public void testCreateXAttributeArrayContent() throws Exception {
        final XElement e = new XElement("root",
                                        new XAttr("attr1", "1"),
                                        new XAttr("attr2", "2"),
                                        new XAttr("attr3", "3"));
        assertThat(e.toString(), is("<root attr1=\"1\" attr2=\"2\" attr3=\"3\"/>"));
    }

    @Test
    public void testCreateElementInNamespace() throws Exception {
        final XElement e1 = new XElement(XNamespace.namespace("http://example.com"), "root");
        assertThat(e1.toString(), is("<root xmlns=\"http://example.com\"/>"));

        // or this way
        final XElement e2 = new XElement("root", new XAttr(XNamespace.XMLNS, "aa", "http://example.com"));
        assertThat(e2.toString(), is("<root xmlns:aa=\"http://example.com\"/>"));
    }

    @Test
    public void testCreateElementInNamespace2() throws Exception {
        final XElement e2 = new XElement(aw, "root", new XElement(aw, "child", "content"));
        assertThat(e2.toString(), is("<root xmlns=\"http://www.adventure-works.com\"><child>content</child></root>"));
    }

    @Test
    public void testCreateElementInNamespace3() throws Exception {
        final XElement e = new XElement(aw, "root", new XElement(aw, "child", "content"));
        assertThat(e.toString(), is("<root xmlns=\"http://www.adventure-works.com\"><child>content</child></root>"));
    }

    @Test
    public void testCreateElementInNestedNamespace() throws Exception {
        final XElement e = new XElement(aw,
                                        "Root",
                                        new XAttr(XNamespace.XMLNS, "fc", "www.fourthcoffee.com"),
                                        new XElement(fc, "Child", new XElement(aw, "DifferentChild", "other content")),
                                        new XElement(aw, "Child2", "c2 content"),
                                        new XElement(fc, "Child3", "c3 content"));

        assertThat(e.toString(),
                   is("<Root xmlns=\"http://www.adventure-works.com\" xmlns:fc=\"www.fourthcoffee.com\">" +
                      "<fc:Child>" +
                      "<DifferentChild>other content</DifferentChild>" +
                      "</fc:Child>" +
                      "<Child2>c2 content</Child2>" +
                      "<fc:Child3>c3 content</fc:Child3>" +
                      "</Root>"));
    }

    @Test
    public void testCreateElementWithMultipleXmlns() throws Exception {
        final XNamespace xsd = XNamespace.namespace("xsd", "http://www.w3.org/2001/XMLSchema");
        final XNamespace sql = XNamespace.namespace("sql", "urn:schemas-microsoft-com:mapping-schema");
        final XElement e = new XElement(xsd,
                                        "schema",
                                        new XAttr(XNamespace.XMLNS, "xsd", "http://www.w3.org/2001/XMLSchema"),
                                        new XAttr(XNamespace.XMLNS, "sql", "urn:schemas-microsoft-com:mapping-schema"),
                                        new XAttr("targetNamespace", "http://www.example.com"),
                                        new XElement(xsd,
                                                     "element",
                                                     new XAttr("name", "root"),
                                                     new XAttr(sql, "is-constant", "1")));
        assertThat(e.toString(), is("<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" +
                                    " xmlns:sql=\"urn:schemas-microsoft-com:mapping-schema\"" +
                                    " targetNamespace=\"http://www.example.com\"><xsd:element name=\"root\" sql:is-constant=\"1\"/></xsd:schema>"));
    }

    @Test
    public void testCreateContentFromIterable() throws Exception {
        final XElement src = new XElement("Root",
                                          new XElement("Child1", "data1"),
                                          new XElement("Child2", "data2"),
                                          new XElement("Child3", "data3"),
                                          new XElement("Child2", "data4"),
                                          new XElement("Info5", "info5"),
                                          new XElement("Info7", "info7"),
                                          new XElement("Info8", "info8"));
        final XElement e = new XElement("Root",
                                        src.getChildNodes()
                                           .filter(((Func1<Node, String>) Node::getTextContent).then(OnString.startsWith(
                                                   "data"))));
        assertThat(e.toString(), is("<Root>" +
                                    "<Child1>data1</Child1>" +
                                    "<Child2>data2</Child2>" +
                                    "<Child3>data3</Child3>" +
                                    "<Child2>data4</Child2></Root>"));
    }

    @Test
    public void testSetAttribute() throws Exception {
        final XElement e = new XElement("Root");
        e.setAttributeNode(new XAttr("attr", "1"));
        assertThat(e.toString(), is("<Root attr=\"1\"/>"));
    }

    @Test
    public void testAdd() throws Exception {
        final XElement e = new XElement("root");
        // appendChild
        e.add(new XElement("child"));
        assertThat(e.toString(), is("<root><child/></root>"));

        // if node is attribute, set it
        e.add(new XAttr("attr", "1"));
        assertThat(e.toString(), is("<root attr=\"1\"><child/></root>"));
    }

    @Test
    public void testAddAllIterable() throws Exception {
        final XElement e = new XElement("root");
        e.addAll(new XElement("tree",
                              new XElement("leaf1"),
                              new XElement("leaf2"),
                              new XElement("leaf3")).getChildNodes());
        assertThat(e.toString(), is("<root><leaf1/><leaf2/><leaf3/></root>"));

        // if node is attribute, set it
        e.addAll(new XElement("a", new XAttr("attr1", "one"), new XAttr("attr2", "two")).getAttributes());
        assertThat(e.toString(), is("<root attr1=\"one\" attr2=\"two\"><leaf1/><leaf2/><leaf3/></root>"));
    }

    @Test
    public void testAddAllArray() throws Exception {
        final XElement e = new XElement("root");
        e.addAll(new XElement("leaf1"), new XElement("leaf2"), new XElement("leaf3"));
        assertThat(e.toString(), is("<root><leaf1/><leaf2/><leaf3/></root>"));

        // if node is attribute, set it
        e.addAll(new XAttr("attr1", "one"), new XAttr("attr2", "two"));
        assertThat(e.toString(), is("<root attr1=\"one\" attr2=\"two\"><leaf1/><leaf2/><leaf3/></root>"));
    }

    @Test
    public void testGetNodeType() throws Exception {
        final XElement e = new XElement("root");
        assertThat(e.getType(), CoreMatchers.is(XType.Element));
    }

    @Test
    public void testCloneConstructor() {
        final XElement origin = new XElement("abc",
                                             new XAttr("attr1", 1),
                                             new XAttr("attr2", 2),
                                             new XElement("child", new XElement("grandChild", new XAttr("attr3", 3))));
        final XElement clone = new XElement(origin);
        testEquality(origin, clone);
    }

    @Test
    public void testClone() {
        final XElement origin = new XElement("abc",
                                             new XAttr("attr1", 1),
                                             new XAttr("attr2", 2),
                                             new XElement("child", new XElement("grandChild", new XAttr("attr3", 3))));
        final XElement clone = origin.cloneNode(true);
        testEquality(origin, clone);

        // deep clone (cloned descendants does not equal original descendants)
        final NodeList originChildren = origin.getChildNodes();
        final NodeList cloneChildren = clone.getChildNodes();
        for (int i = 0; i < originChildren.getLength(); i++) {
            assertThat(originChildren.item(i) == cloneChildren.item(i), is(false));
        }
    }

    private void testEquality(final XElement origin, final XElement clone) {
        assertThat(origin == clone, is(false));
        assertThat(origin.isEqualNode(clone), is(true));
        assertThat(origin.isSameNode(clone), is(false));
        assertThat(clone.toString(), is(origin.toString()));
    }

    @Test
    public void testGetTagName() throws Exception {
        assertThat(x.getTagName(), is("tag"));
        assertThat(xns.getTagName(), is("tag"));
    }

    @Test
    public void testGetLocalName() throws Exception {
        assertThat(x.getLocalName(), is("tag"));
        assertThat(xns.getLocalName(), is("tag"));
    }

    @Test
    public void testCloneShallow() {
        final XElement origin = new XElement("abc",
                                             new XAttr("attr1", 1),
                                             new XAttr("attr2", 2),
                                             new XElement("child", new XElement("grandChild", new XAttr("attr3", 3))));
        final XElement clone = origin.cloneNode(false);
        assertThat(origin == clone, is(false));
        assertThat(origin.isSameNode(clone), is(false));
        assertThat(origin.isEqualNode(clone), is(false));
        assertThat(origin.getChildNodes().toList(), is(not(clone.getChildNodes().toList())));
    }

    @Test
    public void testSetAndRemoveAttribute() throws Exception {
        x.setAttribute("key", "value");
        assertThat(x.getAttribute("key"), is("value"));
        assertThat(x.hasAttribute("key"), is(true));

        x.removeAttribute("key");
        assertThat(x.getAttribute("key"), is(""));
        assertThat(x.hasAttribute("key"), is(false));
    }

    @Test
    public void testSetAndRemoveAttributeNode() throws Exception {
        final XAttr attr = new XAttr("key", "value");
        x.setAttributeNode(attr);
        assertThat(x.getAttribute("key"), is("value"));
        assertThat(x.hasAttribute("key"), is(true));
        assertThat(x.getAttributeNode("key").isEqualNode(attr), is(true));

        x.removeAttributeNode(attr);
        assertThat(x.getAttribute("key"), is(""));
        assertThat(x.hasAttribute("key"), is(false));
    }

    @Test
    public void testSetAndRemoveAttributeNS() throws Exception {
        final String uri = "http://example.com";
        final String wrongUri = "http://example.com/wrong";
        x.setAttributeNS(uri, "key", "value");
        assertThat(x.getAttribute("key"), is("value"));
        assertThat(x.hasAttribute("key"), is(true));

        assertThat(x.getAttributeNS(uri, "key"), is("value"));
        assertThat(x.hasAttributeNS(uri, "key"), is(true));
        assertThat(x.hasAttributeNS(uri, "keyWrong"), is(false));
        assertThat(x.hasAttributeNS(wrongUri, "key"), is(false));

        x.removeAttributeNS(uri, "key");
        assertThat(x.getAttribute("key"), is(""));
        assertThat(x.hasAttribute("key"), is(false));
        assertThat(x.hasAttributeNS(uri, "key"), is(false));
        assertThat(x.hasAttributeNS(uri, "keyWrong"), is(false));
        assertThat(x.hasAttributeNS(wrongUri, "key"), is(false));
    }

    @Test
    public void testSetAndRemoveAttributeNodeNS() throws Exception {
        final String uri = "http://example.com";
        final String wrongUri = "http://example.com/wrong";
        final Attr attr = new XAttr(XNamespace.namespace(uri), "key", "value");

        x.setAttributeNodeNS(attr);
        assertThat(x.getAttribute("key"), is("value"));
        assertThat(x.hasAttribute("key"), is(true));

        assertThat(x.getAttributeNS(uri, "key"), is("value"));
        assertThat(x.hasAttributeNS(uri, "key"), is(true));
        assertThat(x.hasAttributeNS(uri, "keyWrong"), is(false));
        assertThat(x.hasAttributeNS(wrongUri, "key"), is(false));
        assertThat(x.getAttributeNodeNS(uri, "key").isEqualNode(attr), is(true));

        x.removeAttributeNode(attr);
        assertThat(x.getAttribute("key"), is(""));
        assertThat(x.hasAttribute("key"), is(false));
        assertThat(x.hasAttributeNS(uri, "key"), is(false));
        assertThat(x.hasAttributeNS(uri, "keyWrong"), is(false));
        assertThat(x.hasAttributeNS(wrongUri, "key"), is(false));
    }

    @Test
    public void testSetIdAttribute() throws Exception {
        final Attr attr = new XAttr("myId", 123456);
        assertThat(attr.isId(), is(false));

        x.setAttributeNode(attr);
        x.setIdAttribute("myId", true);
        assertThat(x.getAttribute("myId"), is("123456"));
        assertThat(attr.isId(), is(true));

        x.setIdAttribute("myId", false);
        assertThat(x.getAttribute("myId"), is("123456"));
        assertThat(attr.isId(), is(false));
    }

    @Test
    public void testSetIdAttributeNode() throws Exception {
        final Attr attr = new XAttr("myId", 123456);
        assertThat(attr.isId(), is(false));

        x.setIdAttributeNode(attr, true);
        assertThat(x.getAttribute("myId"), is("123456"));
        assertThat(attr.isId(), is(true));

        x.setIdAttributeNode(attr, false);
        assertThat(x.getAttribute("myId"), is("123456"));
        assertThat(attr.isId(), is(false));
    }

    @Test
    public void testSetIdAttributeNs() throws Exception {
        final Attr attr = new XAttr("myId", 123456);
        assertThat(attr.isId(), is(false));

        x.setAttributeNode(attr);
        x.setIdAttributeNS(attr.getNamespaceURI(), attr.getLocalName(), true);
        x.setIdAttribute("myId", true);
        assertThat(x.getAttribute("myId"), is("123456"));
        assertThat(attr.isId(), is(true));

        x.setIdAttributeNS(attr.getNamespaceURI(), attr.getLocalName(), false);
        assertThat(x.getAttribute("myId"), is("123456"));
        assertThat(attr.isId(), is(false));
    }

    @Test
    public void testAppendChild() throws Exception {
        final XElement e = new XElement("Root", new XElement("Child1", "data1"), new XElement("Child2", "data2"));
        final XElement last = new XElement("last");
        e.appendChild(last);
        assertThat(last.isEqualNode(e.getLastChild()), is(true));
        assertThat(last.isSameNode(e.getLastChild()), is(false));
        assertThat(e.toString(), is("<Root>" +
                                    "<Child1>data1</Child1>" +
                                    "<Child2>data2</Child2>" +
                                    "<last/>" +
                                    "</Root>"));
    }

    @Test
    public void testAppendChildFromDifferentDocument() throws Exception {
        final XElement e = new XElement("Root", new XElement("Child1", "data1"), new XElement("Child2", "data2"));
        e.appendChild(x);
        assertThat(e.toString(), is("<Root>" +
                                    "<Child1>data1</Child1>" +
                                    "<Child2>data2</Child2>" +
                                    "<tag><child/>text<child/></tag>" +
                                    "</Root>"));
    }

    @Test
    public void testAppendChildFirst() throws Exception {
        final XElement e = new XElement("Root", new XElement("Child1", "data1"), new XElement("Child2", "data2"));
        final XElement first = new XElement("first");
        e.appendChildFirst(first);
        assertThat(first.isEqualNode(e.getFirstChild()), is(true));
        assertThat(first.isSameNode(e.getFirstChild()), is(false));
        assertThat(e.toString(), is("<Root>" +
                                    "<first/>" +
                                    "<Child1>data1</Child1>" +
                                    "<Child2>data2</Child2>" +
                                    "</Root>"));
    }

    @Test
    public void testAppendChildFirstFromDifferentDocument() throws Exception {
        final XElement e = new XElement("Root", new XElement("Child1", "data1"), new XElement("Child2", "data2"));
        e.appendChildFirst(x);
        assertThat(e.toString(), is("<Root>" +
                                    "<tag><child/>text<child/></tag>" +
                                    "<Child1>data1</Child1>" +
                                    "<Child2>data2</Child2>" +
                                    "</Root>"));
    }

    @Test
    public void testAppendMultiple() throws Exception {
        final XElement e = new XElement("Root", new XElement("Child1", "data1"), new XElement("Child2", "data2"));
        e.appendChild(new XElement("footer",
                                   new XElement("foot1"),
                                   new XElement("foot2"),
                                   new XElement("foot3")).getChildNodes());
        e.appendChildFirst(new XElement("header",
                                        new XElement("head1"),
                                        new XElement("head2"),
                                        new XElement("head3")).getChildNodes());
        assertThat(e.toString(), is("<Root>" +
                                    "<head1/><head2/><head3/>" +
                                    "<Child1>data1</Child1>" +
                                    "<Child2>data2</Child2>" +
                                    "<foot1/><foot2/><foot3/>" +
                                    "</Root>"));
    }

    @Test
    public void testAppendMultipleFromOtherDocument() throws Exception {
        final XElement e = new XElement("Root", new XElement("Child1", "data1"), new XElement("Child2", "data2"));
        e.appendChild(new XElement("footer", new XElement("foot1"), new XElement("foot2"), x).getChildNodes());
        e.appendChildFirst(new XElement("header", new XElement("head1"), new XElement("head2"), xns).getChildNodes());
        assertThat(e.toString(), is("<Root>" +
                                    "<head1/><head2/><tag xmlns=\"http://example.com\">text<child/></tag>" +
                                    "<Child1>data1</Child1>" +
                                    "<Child2>data2</Child2>" +
                                    "<foot1/><foot2/><tag><child/>text<child/></tag>" +
                                    "</Root>"));
    }

    @Test
    public void testGetSchemaTypeInfo() throws Exception {
        assertThat(x.getSchemaTypeInfo(), is(notNullValue()));
    }

    @Test
    public void testGetNodeName() throws Exception {
        assertThat(x.getNodeName(), is("tag"));
        assertThat(xns.getNodeName(), is("tag"));
    }

    @Test
    public void testGetNodeValue() throws Exception {
        assertThat(x.getNodeValue(), is(nullValue()));
        assertThat(xns.getNodeValue(), is(nullValue()));
    }

    @Test
    public void testSetNodeValue() throws Exception {
        x.setNodeValue("not set");
        xns.setNodeValue("not set");
        assertThat(x.getNodeValue(), is(nullValue()));
        assertThat(xns.getNodeValue(), is(nullValue()));
    }

    @Test
    public void testGetParentNode() throws Exception {
        assertThat(x.getParentNode(), is(not(nullValue())));
        assertThat(xns.getParentNode(), is(nullValue()));
    }

    @Test
    public void testGetOwnerDocument() throws Exception {
        assertThat(x.getOwnerDocument(), is(not(nullValue())));
        assertThat(xns.getOwnerDocument(), is(not(nullValue())));
    }

    @Test
    public void testGetFirstChild() throws Exception {
        final Node first = x.getFirstChild();
        assertThat(first.isEqualNode(new XElement("child")), is(true));
    }

    @Test
    public void testGetLastChild() throws Exception {
        final Node last = x.getLastChild();
        assertThat(last.isEqualNode(new XElement("child")), is(true));
    }

    @Test
    public void testGetPreviousSibling() throws Exception {
        assertThat(x.getPreviousSibling(), is(nullValue()));
        final Element rawLastChild = (Element) x.getLastChild();
        assertThat(new XElement(rawLastChild).getPreviousSibling(), is(not(nullValue())));
        assertThat(new XElement(rawLastChild).getPreviousSibling(), is(rawLastChild.getPreviousSibling()));

        final Element rawFirstChild = (Element) x.getFirstChild();
        assertThat(new XElement(rawFirstChild).getPreviousSibling(), is(nullValue()));
        assertThat(new XElement(rawFirstChild).getPreviousSibling(), is(rawFirstChild.getPreviousSibling()));
    }

    @Test
    public void testGetNextSibling() throws Exception {
        assertThat(x.getPreviousSibling(), is(nullValue()));
        final Element rawLastChild = (Element) x.getLastChild();
        assertThat(new XElement(rawLastChild).getNextSibling(), is(nullValue()));
        assertThat(new XElement(rawLastChild).getNextSibling(), is(rawLastChild.getNextSibling()));

        final Element rawFirstChild = (Element) x.getFirstChild();
        assertThat(new XElement(rawFirstChild).getNextSibling(), is(not(nullValue())));
        assertThat(new XElement(rawFirstChild).getNextSibling(), is(rawFirstChild.getNextSibling()));
    }

    @Test
    public void testHasChildNodes() throws Exception {
        assertThat(new XElement("empty").hasChildNodes(), is(false));
        assertThat(new XElement("empty", new XAttr("key", 1)).hasChildNodes(), is(false));
        assertThat(new XElement("empty", new XElement("child")).hasChildNodes(), is(true));
    }

    @Test
    public void testHasAttributes() throws Exception {
        assertThat(new XElement("empty").hasAttributes(), is(false));
        assertThat(new XElement("empty", new XAttr("key", 1)).hasAttributes(), is(true));
        assertThat(new XElement("empty", new XElement("child"), new XAttr("key", 1)).hasAttributes(), is(true));
    }

    @Test
    public void testInsertBefore() throws Exception {
        final Text textNode = (Text) x.getChildNodes().item(1);
        final XElement newNode = new XElement("new");
        x.insertBefore(newNode, textNode);
        assertThat(x.getChildNodes().item(1).isEqualNode(newNode), is(true));
        assertThat(x.getChildNodes().item(2).isEqualNode(textNode), is(true));
        assertThat(x.toString(), is("<tag><child/><new/>text<child/></tag>"));
    }

    @Test
    public void testReplaceChild() throws Exception {
        final Text textNode = (Text) x.getChildNodes().item(1);
        final XElement newNode = new XElement("new");
        x.replaceChild(newNode, textNode);
        assertThat(x.getChildNodes().item(1).isEqualNode(newNode), is(true));
        assertThat(x.getChildNodes().item(2).isEqualNode(textNode), is(false));
        assertThat(x.toString(), is("<tag><child/><new/><child/></tag>"));
    }

    @Test
    public void testRemoveChild() throws Exception {
        final Text textNode = (Text) x.getChildNodes().item(1);
        x.removeChild(textNode);
        assertThat(x.toString(), is("<tag><child/><child/></tag>"));
    }

    @Test
    public void testGetElementsByTagName() throws Exception {
        assertThat(x.getElementsByTagName("child").count(), is(2));
    }

    @Test
    public void testGetElementsByTagNameNS() throws Exception {
        assertThat(x.getElementsByTagNameNS(null, "child").count(), is(2));
        assertThat(x.getElementsByTagNameNS("", "child").count(), is(2));
        assertThat(x.getElementsByTagNameNS("http://example.com", "child").count(), is(0));

        assertThat(xns.getElementsByTagNameNS(null, "child").count(), is(0));
        assertThat(xns.getElementsByTagNameNS("", "child").count(), is(0));
        assertThat(xns.getElementsByTagNameNS("http://example.com", "child").count(), is(1));
    }

    @Test
    public void testGetChildNodes() throws Exception {
        final NodeList childNodes = x.getChildNodes();
        assertThat(childNodes.getLength(), is(3));

        final Node newNode = x.appendChild(new XElement("newNode"));
        assertThat(childNodes.getLength(), is(4));
        assertThat(childNodes.item(3), is(newNode));
    }

    @Test
    public void testGetAttributes() throws Exception {
        final NamedNodeSeq live = x.getAttributes();
        assertThat(live.getLength(), is(0));
        x.add(new XAttr("attr1", 1));
        x.add(new XAttr("attr2", 1));
        assertThat(live.getLength(), is(2));
        x.removeAttribute("attr2");
        assertThat(live.getLength(), is(1));
    }

    @Test
    public void testIsSupported() throws Exception {
        assertThat(x.isSupported("XML", null), is(true));
        assertThat(x.isSupported("XML", "1.0"), is(true));
        assertThat(x.isSupported("HTML", null), is(false));
    }

    @Test
    public void testGetPrefix() throws Exception {
        assertThat(x.getPrefix(), is(nullValue()));
        x.add(prefixed);
        assertThat(prefixed.getPrefix(), is("aa"));
        assertThat(x.getLastChild().getPrefix(), is("aa"));
    }

    @Test
    public void testSetPrefix() throws Exception {
        final XElement e = new XElement(XNamespace.namespace("http://example.com"), "root");
        assertThat(e.getPrefix(), is(nullValue()));
        assertThat(e.toString(), is("<root xmlns=\"http://example.com\"/>"));

        e.setPrefix("xyz");
        assertThat(e.getPrefix(), is("xyz"));
        assertThat(e.toString(), is("<xyz:root xmlns:xyz=\"http://example.com\"/>"));
    }

    @Test
    public void testSetPrefixGivenPrefix() throws Exception {
        final XElement e = new XElement(XNamespace.namespace("abc", "http://example.com"), "root");
        assertThat(e.getPrefix(), is("abc"));
        assertThat(e.toString(), is("<abc:root xmlns:abc=\"http://example.com\"/>"));

        e.setPrefix("xyz");
        assertThat(e.getPrefix(), is("xyz"));
        assertThat(e.toString(), is("<xyz:root xmlns:xyz=\"http://example.com\"/>"));

        e.setPrefix(null);
        assertThat(e.getPrefix(), is(nullValue()));
        assertThat(e.toString(), is("<root xmlns=\"http://example.com\"/>"));
    }

    @Test(expected = DOMException.class)
    public void testSetPrefixNoNamespaceURI() throws Exception {
        x.setPrefix("abc");
    }

    @Test
    public void testLookupPrefix() throws Exception {
        for (final XElement e : array(x, xns)) {
            assertThat(e.lookupPrefix(null), is(nullValue()));
            assertThat(e.lookupPrefix("aa"), is(nullValue()));
            assertThat(e.lookupPrefix("http://example.com"), is(nullValue()));
        }
    }

    @Test
    public void testLookupPrefixGivenPrefix() throws Exception {
        assertThat(prefixed.lookupPrefix(null), is(nullValue()));
        assertThat(prefixed.lookupPrefix("aa"), is(nullValue()));
        assertThat(prefixed.lookupPrefix("http://example.com"), is("aa"));
    }

    @Test
    public void testGetNamespaceURI() throws Exception {
        assertThat(x.getNamespaceURI(), is(nullValue()));
        assertThat(xns.getNamespaceURI(), is("http://example.com"));
    }

    @Test
    public void testIsDefaultNamespace() throws Exception {
        assertThat(x.isDefaultNamespace(null), is(true));
        assertThat(x.isDefaultNamespace("http://example.com"), is(false));
        assertThat(xns.isDefaultNamespace(null), is(false));
        assertThat(xns.isDefaultNamespace("http://example.com"), is(true));
    }

    @Test
    public void testLookupNamespaceURI() throws Exception {
        assertThat(x.lookupNamespaceURI(null), is(nullValue()));
        assertThat(x.lookupNamespaceURI("http://example.com"), is(nullValue()));

        assertThat(xns.lookupNamespaceURI(null), is("http://example.com"));
        assertThat(xns.lookupNamespaceURI("http://example.com"), is(nullValue()));

        assertThat(prefixed.lookupNamespaceURI(null), is(nullValue()));
        assertThat(prefixed.lookupNamespaceURI("aa"), is("http://example.com"));
        assertThat(prefixed.lookupNamespaceURI("http://example.com"), is(nullValue()));
    }

    @Test
    public void testGetBaseURI() throws Exception {
        assertThat(x.getBaseURI(), is(nullValue()));
        assertThat(xns.getBaseURI(), is(nullValue()));

        // TODO; add non null value usage
    }

    @Test
    public void testCompareDocumentPosition() throws Exception {
        assertThat(x.compareDocumentPosition(x), is((short) 0));

        final XElement first = new XElement((Element) x.getFirstChild());
        final XElement last = new XElement((Element) x.getLastChild());
        assertThat(first.compareDocumentPosition(last), is(Node.DOCUMENT_POSITION_FOLLOWING));
        assertThat(last.compareDocumentPosition(first), is(Node.DOCUMENT_POSITION_PRECEDING));

        final short value = Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC |
                            Node.DOCUMENT_POSITION_DISCONNECTED |
                            Node.DOCUMENT_POSITION_PRECEDING;
        assertThat(x.compareDocumentPosition(xns), is(value));
    }

    @Test
    public void testGetTextContent() throws Exception {
        assertThat(x.getTextContent(), is("text"));
    }

    @Test
    public void testSetTextContent() throws Exception {
        x.setTextContent("new text");
        assertThat(x.getTextContent(), is("new text"));
        x.setTextContent(null);
        assertThat(x.getTextContent(), is(""));
    }

    @Test
    public void testGetFeature() throws Exception {
        assertThat(x.isEqualNode((Node) x.getFeature("xml", null)), is(true));
        assertThat(x.getFeature("unknown", null), is(nullValue()));
    }

    @Test
    public void testGetUserData() throws Exception {
        assertThat(x.getUserData(""), is(nullValue()));
        assertThat(x.getUserData("not set"), is(nullValue()));
    }

    @Test
    public void testSetUserData() throws Exception {
        final UserDataHandler emptyHandler = (operation, key, data, src, dst) -> {
            //do nothing
        };

        x.setUserData("", "1234", emptyHandler);
        assertThat((String) x.getUserData(""), is("1234"));

        x.setUserData("array", new int[]{1, 2, 3}, emptyHandler);
        assertThat((int[]) x.getUserData("array"), is(new int[]{1, 2, 3}));
    }

    @Test
    public void testNormalizeNeighboringText() throws Exception {
        final XElement e = new XElement("node", "text1", "text2");
        assertThat(e.getChildNodes().getLength(), is(2));
        e.normalize();
        assertThat(e.getChildNodes().getLength(), is(1));
    }

    @Test
    public void testNormalizeNoNormalizing() throws Exception {
        final XElement e = new XElement("node", "text1", new XElement("child"), "text2");
        assertThat(e.getChildNodes().getLength(), is(3));
        e.normalize();
        assertThat(e.getChildNodes().getLength(), is(3));
    }

    private final String path = XElement.class.getClassLoader().getResource("simple.xml").getPath();

    @Test
    public void testLoadFromStringPath() throws Exception {
        testPreserveSpace(XElement.load(path));
    }

    @Test
    public void testLoadFromFileStringPathIgnoreWhiteSpace() throws Exception {
        testIgnoreSpace(XElement.load(path, WhiteSpaceOption.Ignore));
    }

    @Test
    public void testLoadFromFile() throws Exception {
        final File file = new File(path);
        testPreserveSpace(XElement.load(file));
    }

    @Test
    public void testLoadFromFileIgnoreWhiteSpace() throws Exception {
        final File file = new File(path);
        testIgnoreSpace(XElement.load(file, WhiteSpaceOption.Ignore));
    }

    @Test
    public void testLoadFromInputStream() throws Exception {
        final InputStream stream = new FileInputStream(path);
        testPreserveSpace(XElement.load(stream));
    }

    @Test
    public void testLoadFromInputStreamIgnoringSpace() throws Exception {
        final InputStream stream = new FileInputStream(path);
        testIgnoreSpace(XElement.load(stream, WhiteSpaceOption.Ignore));
    }

    @Test
    public void testLoadFromReader() throws Exception {
        final Reader reader = new FileReader(path);
        testPreserveSpace(XElement.load(reader));
    }

    @Test
    public void testLoadFromReaderIgnoringSpace() throws Exception {
        final Reader reader = new FileReader(path);
        testIgnoreSpace(XElement.load(reader, WhiteSpaceOption.Ignore));
    }

    private void testIgnoreSpace(final XElement document) {
        final XElement expected = new XElement("root",
                                               new XElement("child1"),
                                               new XElement("child2"),
                                               new XElement("child3"));
        assertThat(document.getChildNodes().getLength(), is(expected.getChildNodes().getLength()));
        assertThat(document.toString(), is(expected.toString()));
    }

    private void testPreserveSpace(final XElement document) {
        final XElement expected = new XElement("root",
                                               new XText("\n    "),
                                               new XElement("child1"),
                                               new XText("\n    "),
                                               new XElement("child2"),
                                               new XText("\n    "),
                                               new XElement("child3"),
                                               new XText("\n"));
        assertThat(document.getChildNodes().getLength(), is(expected.getChildNodes().getLength()));
        assertThat(document.toString(), is(expected.toString()));
    }

    @Test
    public void testSaveFile() throws Exception {
        final XElement original = XElement.load(path);
        final File tempFile = folder.newFile();
        original.save(tempFile);

        final XElement saved = XElement.load(tempFile);
        assertThat(original.isEqualNode(saved), is(true));
    }

    @Test
    public void testSaveFilePath() throws Exception {
        final XElement original = XElement.load(path);
        final File tempFile = folder.newFile("dummy.xml");
        original.save(tempFile.getPath());

        final XElement saved = XElement.load(tempFile);
        assertThat(original.isEqualNode(saved), is(true));
    }

    @Test
    public void testSaveOutputStream() throws Exception {
        final XElement original = XElement.load(path);
        final File tempFile = folder.newFile("dummy.xml");
        final OutputStream stream = new FileOutputStream(tempFile, false);
        original.save(stream);

        final XElement saved = XElement.load(tempFile);
        assertThat(original.isEqualNode(saved), is(true));
    }
}
TOP

Related Classes of net.exoego.queen.xml.XElementTest

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.