package com.eviware.soapui.impl.wsdl.support.http;

import java.io.IOException;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.impl.client.RequestWrapper;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import static org.mockito.Mockito.*;

import com.eviware.soapui.impl.wsdl.submit.transports.http.ExtendedHttpMethod;
import com.eviware.soapui.impl.wsdl.submit.transports.http.support.metrics.SoapUIMetrics;
import com.eviware.soapui.impl.wsdl.submit.transports.http.support.metrics.Stopwatch;
import com.eviware.soapui.impl.wsdl.support.http.HttpClientSupport.SoapUIHttpRequestExecutor;

import junit.framework.JUnit4TestAdapter;

@RunWith(org.mockito.runners.MockitoJUnitRunner.class)
public class HttpClientSupportSoapUIHttpRequestExecutorTest {
	public static junit.framework.Test suite()
	{
		return new JUnit4TestAdapter( ProxyUtilsTestCase.class );
	}

	@Mock
	HttpProcessor processor;
	
	@Mock
	HttpContext context;
	
	@Mock
	RequestWrapper wrappedRequest;
	
	@Mock
	ExtendedHttpMethod extendedHttpMethod;

	@Mock
	SoapUIMetrics metrics;

	@Mock
	Stopwatch stopWatch;

	@Mock
	Stopwatch startWatch;
	
	@Test
	public void aWrappedRequestShouldDelegateToOriginalRequest() throws Exception
	{
		when(wrappedRequest.getOriginal()).thenReturn(extendedHttpMethod);
		when(extendedHttpMethod.getMetrics()).thenReturn(metrics);
		when(metrics.getConnectTimer()).thenReturn(stopWatch);
		when(metrics.getTimeToFirstByteTimer()).thenReturn(startWatch);

		SoapUIHttpRequestExecutor executor = new SoapUIHttpRequestExecutor();
		executor.preProcess(wrappedRequest, processor, context);
		
		verify(wrappedRequest,times(1)).getOriginal();
		verify(extendedHttpMethod,times(1)).getMetrics();
		verify(startWatch,times(1)).start();
		verify(stopWatch,times(1)).stop();
	}
	
	@Test
	public void aNonWrappedRequestShouldNotDelegateToOriginalRequest() throws Exception
	{
		HttpRequest req = mock(ExtendedHttpMethod.class);
		
		when(((ExtendedHttpMethod)req).getMetrics()).thenReturn(metrics);
		when(metrics.getConnectTimer()).thenReturn(stopWatch);
		when(metrics.getTimeToFirstByteTimer()).thenReturn(startWatch);

		SoapUIHttpRequestExecutor executor = new SoapUIHttpRequestExecutor();
		executor.preProcess(req, processor, context);

		verify(((ExtendedHttpMethod)req),times(1)).getMetrics();
		verify(startWatch,times(1)).start();
		verify(stopWatch,times(1)).stop();
	}
}
