1+ package org .biojava .nbio .core .util ;
2+
3+ import static org .junit .jupiter .api .Assertions .assertNotNull ;
4+ import static org .junit .jupiter .api .Assertions .assertEquals ;
5+ import static org .junit .jupiter .api .Assertions .assertFalse ;
6+ import static org .junit .jupiter .api .Assertions .assertNull ;
7+
8+ import java .io .ByteArrayInputStream ;
9+ import java .io .File ;
10+ import java .io .IOException ;
11+ import java .nio .file .Files ;
12+ import java .nio .file .Path ;
13+
14+ import javax .xml .parsers .ParserConfigurationException ;
15+
16+ import org .junit .jupiter .api .DisplayName ;
17+ import org .junit .jupiter .api .Test ;
18+ import org .w3c .dom .DOMException ;
19+ import org .w3c .dom .Document ;
20+ import org .w3c .dom .Element ;
21+ import org .xml .sax .SAXException ;
22+
23+ class XMLHelperTest {
24+
25+ final String TEST_XML = "<root><list><a id='1'/> <a id='2'/> </list></root>" ;
26+
27+ @ Test
28+ @ DisplayName ("Create empty w3dom Document" )
29+ void getNewDocument () throws ParserConfigurationException {
30+ Document d = XMLHelper .getNewDocument ();
31+ assertNotNull (d );
32+ assertFalse (d .hasChildNodes ());
33+ assertNull (d .getInputEncoding ());
34+ }
35+
36+
37+ @ Test
38+ @ DisplayName ("Create empty w3dom Document" )
39+ void addChildDocument () throws ParserConfigurationException , DOMException {
40+
41+ Document d = createDocumentWithRootElement ();
42+ Element root = (Element )d .getChildNodes ().item (0 );
43+
44+ Element added = XMLHelper .addChildElement (root , "myelement" );
45+ assertNotNull (added );
46+ assertEquals (root , added .getParentNode ());
47+ assertEquals (added , root .getChildNodes ().item (0 ));
48+ }
49+
50+ @ Test
51+ void inputStreamToDocument () throws SAXException , IOException , ParserConfigurationException {
52+ ByteArrayInputStream bArrayInputStream = new ByteArrayInputStream (TEST_XML .getBytes ());
53+ Document doc = XMLHelper .inputStreamToDocument (bArrayInputStream );
54+ assertParsedDocument (doc );
55+
56+ }
57+
58+ @ Test
59+ void fileToDocument () throws IOException , SAXException , ParserConfigurationException {
60+ File tmpFile = File .createTempFile ("xml" , ".xml" );
61+ Files .write (Path .of (tmpFile .getAbsolutePath ()), TEST_XML .getBytes ());
62+ Document doc = XMLHelper .loadXML (tmpFile .getAbsolutePath ());
63+ assertParsedDocument (doc );
64+
65+ }
66+ void assertParsedDocument (Document doc ){
67+ assertNotNull (doc );
68+ assertEquals (2 , doc .getElementsByTagName ("a" ).getLength ());
69+ assertEquals (1 , doc .getElementsByTagName ("list" ).getLength ());
70+ }
71+
72+ Document createDocumentWithRootElement () throws ParserConfigurationException {
73+ Document d = XMLHelper .getNewDocument ();
74+ Element root = d .createElement ("root" );
75+ d .appendChild (root );
76+ return d ;
77+ }
78+ }
0 commit comments