/*
 * 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.utils;

import java.io.StringReader;

import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPathExpressionException;

import junit.framework.TestCase;

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

public class NodeFindableFactoryImplTest extends TestCase {
	private final NodeFindableFactory factory = new NodeFindableFactoryImpl();
	
	public void testConstructor(){
		try{
			factory.newInstance(null);
			fail();
		}catch(final NullPointerException expected){
		}
		try{
			factory.newInstance("/INPUT[@id=\"hoge");
			fail();
		}catch(final RuntimeException expected){
			assertTrue(expected.getCause() instanceof XPathExpressionException);
		}
	}
	
	private Node generateSampleNode(){
		final DOMResult result = new DOMResult();
		UtilsConstants.TRANSFORMER_FACTORY.newInstance().transform(
				new StreamSource(new StringReader("<HTML><BODY><SPAN id=\"id0\"/><SPAN id=\"id1\"/></BODY></HTML>")),
				result);
		return result.getNode();
	}
	
	public void testEvaluateList(){
		final Node node = generateSampleNode();
		final NodeFindable findable = factory.newInstance("//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 testEvaluateOne(){
		final Node node = generateSampleNode();
		final NodeFindable findable = factory.newInstance("//SPAN/@id");
		final Node result = findable.evaluateOne(node);
		assertTrue(result instanceof Attr);
		assertEquals("id0", result.getNodeValue());
	}
}
