/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * 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 woolpack.xml;

import javax.xml.xpath.XPathExpressionException;

import junit.framework.TestCase;

import org.w3c.dom.Attr;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import woolpack.fn.Fn;

public class NodeFindableFactoryImplTest extends TestCase {
	private final Fn<String, NodeFindable> factory = XmlUtils.NODE_FINDABLE_FACTORY;

	public void testIllegalArgument() {
		try {
			factory.exec(null);
			fail();
		} catch (final NullPointerException expected) {
		}
		try {
			factory.exec("/INPUT[@id=\"hoge");
			fail();
		} catch (final IllegalArgumentException expected) {
			assertTrue(expected.getCause() instanceof XPathExpressionException);
		}
	}

	private Node generateSampleNode() {
		return XmlUtils.convert("<HTML><BODY><SPAN id=\"id0\"/><SPAN id=\"id1\"/></BODY></HTML>");
	}

	public void testEvaluateList() {
		final Node node = generateSampleNode();
		final NodeFindable findable = factory.exec("//SPAN/@id");
		final NodeList list = findable.evaluateList(node);
		assertEquals(2, list.getLength());
		assertTrue(list.item(0) instanceof Attr);
		assertEquals("id0", list.item(0).getNodeValue());
		assertTrue(list.item(1) instanceof Attr);
		assertEquals("id1", list.item(1).getNodeValue());
	}

	public void testEvaluateListNotFound() {
		final Node node = generateSampleNode();
		final NodeFindable findable = factory.exec("//SPAN/@ie");
		final NodeList list = findable.evaluateList(node);
		assertEquals(0, list.getLength());
	}

	public void testEvaluateOne() {
		final Node node = generateSampleNode();
		final NodeFindable findable = factory.exec("//SPAN/@id");
		final Node result = findable.evaluateOne(node);
		assertTrue(result instanceof Attr);
		assertEquals("id0", result.getNodeValue());
	}

	public void testEvaluateOneNotFound() {
		final Node node = generateSampleNode();
		final NodeFindable findable = factory.exec("//SPAN/@ie");
		final Node result = findable.evaluateOne(node);
		assertNull(result);
	}
}
