+/*
+ * Copyright 2005-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wamblee.xml;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import static junit.framework.TestCase.*;
+import static org.wamblee.xml.XMLDocument.*;
+import static org.wamblee.xml.XPathContext.*;
+import static org.wamblee.xml.SimpleNamespaceContext.*;
+
+public class XPathExpressionTest {
+
+ private XPathContext context;
+ private XMLDocument doc;
+
+ @Before
+ public void setUp() throws XMLException, URISyntaxException, IOException {
+ context = xpathcontext(namespaces().addPrefix("n", "http://example.com/1").addPrefix("m", "http://example.com/2"));
+ doc = xmldocument(getClass().getResource("xpathexample.xml").toURI());
+ }
+
+ @Test(expected = XMLException.class)
+ public void testInvalidXpath() throws XMLException {
+ context.createExpression("a[");
+ }
+
+ @Test
+ public void testStringVal() throws XMLException {
+ String value = context.createExpression("/n:root/m:x").stringEval(doc);
+ assertEquals("hallo", value.trim());
+ }
+
+ @Test
+ public void testBooleanVal() throws XMLException {
+ assertTrue(context.createExpression("/n:root/m:x").booleanEval(doc));
+ assertFalse(context.createExpression("unknownelement").booleanEval(doc));
+ }
+
+ @Test
+ public void testNummberVal() throws XMLException {
+ assertEquals(1.0d, context.createExpression("count(/n:root/m:x)").numberEval(doc));
+ assertEquals(11.0d, context.createExpression("//n:elem").numberEval(doc));
+ }
+
+ @Test
+ public void testNodeVal() throws XMLException {
+ Node node = context.createExpression("/n:root/n:elem").nodeEval(doc);
+ assertTrue(node instanceof Element);
+ assertEquals("11", node.getTextContent().trim());
+ assertEquals("elem", node.getLocalName());
+ assertEquals("http://example.com/1", node.getNamespaceURI());
+ }
+
+ @Test
+ public void testNodeSetVal() throws XMLException {
+ NodeList nodelist = context.createExpression("/n:root/n:elem").nodelistEval(doc);
+ assertEquals(2, nodelist.getLength());
+ assertEquals("11", nodelist.item(0).getTextContent().trim());
+ assertEquals("22", nodelist.item(1).getTextContent().trim());
+ }
+}