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

import java.io.StringReader;

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

import org.apache.commons.jxpath.JXPathException;
import org.w3c.dom.Attr;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import woolpack.utils.NodeFindable;
import woolpack.utils.UtilsConstants;

import junit.framework.TestCase;

public class JXPTest extends TestCase {
	
	public void testConstructor(){
		try{
			new JXP(null);
			fail();
		}catch(final NullPointerException expected){
		}
		try{
			new JXP("/INPUT[@id=\"hoge");
			fail();
		}catch(final JXPathException expected){
		}
		try{
			new JXP(null, "a");
			fail();
		}catch(final NullPointerException expected){
		}
		try{
			new JXP("", "a");
			fail();
		}catch(final JXPathException expected){
		}
		try{
			new JXP("a", null);
			fail();
		}catch(final NullPointerException expected){
		}
		new JXP("//BASE");
		new JXP("a", "");
	}
	
	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 = new JXP("//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 = new JXP("//SPAN/@id");
		final Node result = findable.evaluateOne(node);
		assertTrue(result instanceof Attr);
		assertEquals("id0", result.getNodeValue());
	}
	
	public void testFactory(){
		final Node node = generateSampleNode();
		final NodeFindable findable = new JXPFactory().newInstance("//SPAN/@id");
		final Node result = findable.evaluateOne(node);
		assertTrue(result instanceof Attr);
		assertEquals("id0", result.getNodeValue());
	}
}
