package jp.sf.amateras.functions.utils;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import junit.framework.TestCase;

import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

public class RequestUtilsTest extends TestCase {

	@Mock
	private HttpServletRequest request;
	
	@Override
	protected void setUp() throws Exception {
		super.setUp();
		MockitoAnnotations.initMocks(this);
	}
	
	@Override
	protected void tearDown() throws Exception {
		super.tearDown();
		RequestUtils.removeRequest();
	}
	
	public void testSetRequest() {
		assertNull(RequestUtils.getRequest());
		
		RequestUtils.setRequest(request);
		assertNotNull(RequestUtils.getRequest());
		assertSame(request, RequestUtils.getRequest());
	}

	public void testGetEncoding_01() {
		when(request.getCharacterEncoding()).thenReturn("UTF-8");
		RequestUtils.setRequest(request);
		assertEquals("UTF-8", request.getCharacterEncoding());
	}

	/**
	 * HttpServletRequest#getCharacterEncoding()がnullを返す場合
	 */
	public void testGetEncoding_02() {
		RequestUtils.setRequest(request);
		assertNull(request.getCharacterEncoding());
	}
	
	/**
	 * RequestUtilsにHttpServletRequestがセットされていない場合
	 */
	public void testGetEncoding_03() {
		assertNull(request.getCharacterEncoding());
	}
	
	public void testRemoveRequest() {
		RequestUtils.setRequest(request);
		assertNotNull(RequestUtils.getRequest());
		
		RequestUtils.removeRequest();
		assertNull(RequestUtils.getRequest());
	}

	/**
	 * HttpServletRequestからの属性の取得
	 */
	public void testGetAttribute_01() {
		when(request.getAttribute("name")).thenReturn("takezoe");
		RequestUtils.setRequest(request);

		assertEquals("takezoe", RequestUtils.getAttribute("name"));
		verify(request).getAttribute("name");
	}

	/**
	 * HttpServletRequestの属性に存在しない場合はHttpSessionから取得
	 */
	public void testGetAttribute_02() {
		HttpSession session = mock(HttpSession.class);
		when(session.getAttribute("name")).thenReturn("takezoe");
		when(request.getSession()).thenReturn(session);
		
		RequestUtils.setRequest(request);
		
		assertEquals("takezoe", RequestUtils.getAttribute("name"));
		verify(session).getAttribute("name");
	}
	
	/**
	 * HttpSessionの属性にも存在しない場合はServletContextから取得
	 */
	public void testGetAttribute_03() {
		HttpSession session = mock(HttpSession.class);
		ServletContext context = mock(ServletContext.class);
		when(context.getAttribute("name")).thenReturn("takezoe");
		when(session.getServletContext()).thenReturn(context);
		when(request.getSession()).thenReturn(session);
		
		RequestUtils.setRequest(request);
		
		assertEquals("takezoe", RequestUtils.getAttribute("name"));
		verify(context).getAttribute("name");
	}
}
