Added XPath utilities and updated the javadocs.
[utils] / support / general / src / test / java / org / wamblee / xml / XmlDocumentTest.java
1 /*
2  * Copyright 2005-2011 the original author or authors.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.wamblee.xml;
17
18 import java.io.ByteArrayInputStream;
19 import java.io.ByteArrayOutputStream;
20 import java.io.File;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.net.URI;
24 import java.net.URISyntaxException;
25
26 import org.junit.Test;
27 import org.w3c.dom.Document;
28 import org.w3c.dom.Element;
29 import org.w3c.dom.Node;
30
31 import static junit.framework.TestCase.*;
32
33 import static org.wamblee.xml.XMLDocument.*;
34
35 public class XmlDocumentTest {
36     
37     private InputStream getResource(String aResource) { 
38         return getClass().getResourceAsStream(aResource);
39     }
40
41     @Test
42     public void testReadWriteFromInputStream() throws Exception { 
43         XMLDocument xmldoc = xmldocument("test.xml", getResource("test.xml"));
44         
45         Document doc = xmldoc.getDocument();
46         Element element = doc.getDocumentElement();
47         assertEquals("http://wamblee.org/test", element.getNamespaceURI());
48         
49         String val = xmldoc.print(false);
50         // parse the written document
51         Document doc2 = xmldocument("val.xml", val).getDocument();
52         XmlUtils.assertEquals("", doc, doc2);
53     }
54     
55     @Test
56     public void testReadWriteFromUri() throws XMLException, URISyntaxException, IOException { 
57         XMLDocument xmldoc = xmldocument( getClass().getResource("test.xml").toURI());
58         Node node = xmldoc.getDocument().getFirstChild();
59         assertEquals("root", node.getLocalName());
60     }
61     
62     @Test
63     public void testReadWriteFromClassPath() throws XMLException { 
64         XMLDocument xmldoc = xmldocument("org/wamblee/xml/test.xml", new ClasspathUriResolver());
65         Node node = xmldoc.getDocument().getFirstChild();
66         assertEquals("root", node.getLocalName());
67     }
68     
69     @Test(expected = XMLException.class)
70     public void testReadNotWellFormed() throws Exception { 
71         xmldocument("testNotWellFormed.xml", getResource("testNotWellFormed.xml"));
72     }
73 }