diff --git a/library/src/main/java/com/flipkart/okhttpstats/handler/PersistentStatsHandler.java b/library/src/main/java/com/flipkart/okhttpstats/handler/PersistentStatsHandler.java index db17f1a..171f6cb 100644 --- a/library/src/main/java/com/flipkart/okhttpstats/handler/PersistentStatsHandler.java +++ b/library/src/main/java/com/flipkart/okhttpstats/handler/PersistentStatsHandler.java @@ -77,6 +77,21 @@ public PersistentStatsHandler(Context context) { this.mCurrentAvgSpeed = mPreferenceManager.getAverageSpeed(getNetworkKey(getActiveNetworkInfo())); } + @VisibleForTesting + public PersistentStatsHandler(Context context, PreferenceManager preferenceManager) { + this.mPreferenceManager = preferenceManager; + this.MAX_SIZE = DEFAULT_MAX_SIZE; + this.mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); + this.mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + this.mNetworkStat = new NetworkStat(); + this.mCurrentAvgSpeed = mPreferenceManager.getAverageSpeed(getNetworkKey(getActiveNetworkInfo())); + } + + @VisibleForTesting + public Set getOnResponseListeners() { + return mOnResponseListeners; + } + /** * Client can call this to get the current network info * diff --git a/library/src/test/java/com/flipkart/okhttpstats/NetworkInterceptorTest.java b/library/src/test/java/com/flipkart/okhttpstats/NetworkInterceptorTest.java index 30b8c5a..013b164 100644 --- a/library/src/test/java/com/flipkart/okhttpstats/NetworkInterceptorTest.java +++ b/library/src/test/java/com/flipkart/okhttpstats/NetworkInterceptorTest.java @@ -6,13 +6,14 @@ import com.flipkart.okhttpstats.interpreter.DefaultInterpreter; import com.flipkart.okhttpstats.interpreter.NetworkInterpreter; import com.flipkart.okhttpstats.reporter.NetworkEventReporter; +import com.flipkart.okhttpstats.toolbox.Utils; + import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.robolectric.RobolectricGradleTestRunner; -import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import java.io.ByteArrayOutputStream; @@ -28,7 +29,6 @@ import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; -import okhttp3.internal.http.OkHeaders; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okio.Buffer; @@ -54,6 +54,19 @@ private static byte[] compress(byte[] data) throws IOException { return buf.toByteArray(); } + /** + * Test to verify that {@link IllegalStateException} is thrown if {@link NetworkInterpreter} is null + * + * @throws Exception + */ + @Test(expected = IllegalStateException.class) + public void testIfExceptionThrownIfInterpreterNull() throws Exception { + new NetworkInterceptor.Builder() + .setEnabled(true) + .setNetworkInterpreter(null) + .build(); + } + /** * Test to verify the response object before and after interception * @@ -67,7 +80,7 @@ public void testInterceptedResponse() throws IOException { NetworkInterceptor networkInterceptor = new NetworkInterceptor.Builder() .setEnabled(true) .setNetworkInterpreter(networkInterpreter) - .build(RuntimeEnvironment.application); + .build(); Uri requestUri = Uri.parse("http://www.flipkart.com"); String requestText = "Test Request"; @@ -105,59 +118,7 @@ public void testInterceptedResponse() throws IOException { } /** - * Test to verify {@link com.flipkart.okhttpstats.interpreter.DefaultInterpreter.ForwardingResponseBody} - * - * @throws IOException - */ - @Test - public void testResponseBody() throws IOException { - NetworkEventReporter networkEventReporter = mock(NetworkEventReporter.class); - NetworkInterpreter networkInterpreter = new DefaultInterpreter(networkEventReporter); - - NetworkInterceptor networkInterceptor = new NetworkInterceptor.Builder() - .setEnabled(true) - .setNetworkInterpreter(networkInterpreter) - .build(RuntimeEnvironment.application); - - Uri requestUri = Uri.parse("http://www.flipkart.com"); - String requestText = "Test Request"; - - //creating request - Request request = new Request.Builder() - .url(requestUri.toString()) - .method("POST", RequestBody.create(MediaType.parse("text/plain"), requestText)) - .build(); - - //creating response - Response response = new Response.Builder() - .request(request) - .protocol(Protocol.HTTP_1_1) - .code(200) - .addHeader("Content-Length", "20") - .body(ResponseBody.create(MediaType.parse("text/plain"), "any text")) - .build(); - - CustomChain customChain = new CustomChain(request, response, null); - networkInterceptor.intercept(customChain); - - //intercepted request object - Response interceptedResponse = customChain.proceed(request); - DefaultInterpreter.ForwardingResponseBody forwardingResponseBody = new DefaultInterpreter.ForwardingResponseBody(interceptedResponse.body(), interceptedResponse.body().byteStream()); - - interceptedResponse = interceptedResponse.newBuilder().body(forwardingResponseBody).build(); - - //assert the response body of response - Assert.assertTrue(interceptedResponse.body() == forwardingResponseBody); - //assert the content type - Assert.assertTrue(interceptedResponse.body().contentType() == forwardingResponseBody.contentType()); - //assert the content length - Assert.assertTrue(interceptedResponse.body().contentLength() == forwardingResponseBody.contentLength()); - //assert the source - Assert.assertTrue(interceptedResponse.body().source() == forwardingResponseBody.source()); - } - - /** - * Test for Response With Content Length + * Test for Response With Content Length in their header * * @throws IOException */ @@ -169,7 +130,7 @@ public void testInterceptedResponseWithContentLength() throws IOException { NetworkInterceptor networkInterceptor = new NetworkInterceptor.Builder() .setEnabled(true) .setNetworkInterpreter(networkInterpreter) - .build(RuntimeEnvironment.application); + .build(); Uri requestUri = Uri.parse("http://www.flipkart.com"); @@ -216,7 +177,7 @@ public void testInterceptedRequest() throws IOException { NetworkInterceptor networkInterceptor = new NetworkInterceptor.Builder() .setEnabled(true) .setNetworkInterpreter(networkInterpreter) - .build(RuntimeEnvironment.application); + .build(); Uri requestUri = Uri.parse("http://www.flipkart.com"); String requestText = "Test Request"; @@ -248,14 +209,15 @@ public void testInterceptedRequest() throws IOException { Assert.assertTrue(interceptedRequest.url().toString().equals(request.url().toString())); //assert request body is same Assert.assertTrue(interceptedRequest.body().equals(request.body())); - } /** * Test the request object using {@link MockWebServer} + * Trying to simulate a real example by mocking server * * @throws IOException */ + @Config(sdk = 23) @Test public void testRequest() throws IOException { NetworkEventReporter networkEventReporter = mock(NetworkEventReporter.class); @@ -264,10 +226,9 @@ public void testRequest() throws IOException { NetworkInterceptor networkInterceptor = new NetworkInterceptor.Builder() .setNetworkInterpreter(networkInterpreter) .setEnabled(true) - .build(RuntimeEnvironment.application); + .build(); - OkHttpClient okHttpClient = new OkHttpClient(); - okHttpClient.networkInterceptors().add(networkInterceptor); + OkHttpClient okHttpClient = new OkHttpClient.Builder().addNetworkInterceptor(networkInterceptor).build(); MockWebServer server = new MockWebServer(); server.start(); @@ -294,6 +255,7 @@ public void testRequest() throws IOException { * * @throws IOException */ + @Config(sdk = 23) @Test public void testResponseWithoutContentLength() throws IOException { NetworkEventReporter networkEventReporter = mock(NetworkEventReporter.class); @@ -302,10 +264,9 @@ public void testResponseWithoutContentLength() throws IOException { NetworkInterceptor networkInterceptor = new NetworkInterceptor.Builder() .setNetworkInterpreter(networkInterpreter) .setEnabled(true) - .build(RuntimeEnvironment.application); + .build(); - OkHttpClient okHttpClient = new OkHttpClient(); - okHttpClient.networkInterceptors().add(networkInterceptor); + OkHttpClient okHttpClient = new OkHttpClient.Builder().addNetworkInterceptor(networkInterceptor).build(); byte[] uncompressedData = "Dummy Value".getBytes(); byte[] compressedData = compress(uncompressedData); @@ -315,7 +276,7 @@ public void testResponseWithoutContentLength() throws IOException { //removing content length from the response header server.enqueue(new MockResponse() - .setChunkedBody(new Buffer().write(compressedData),3)); + .setChunkedBody(new Buffer().write(compressedData), 3)); Request request = new Request.Builder() .url(server.url("/")) @@ -331,7 +292,9 @@ public void testResponseWithoutContentLength() throws IOException { ArgumentCaptor responseArgumentCaptor = ArgumentCaptor.forClass(NetworkEventReporter.InspectorResponse.class); Mockito.verify(networkEventReporter, times(1)) .responseReceived(any(NetworkEventReporter.InspectorRequest.class), responseArgumentCaptor.capture()); - Assert.assertTrue(responseArgumentCaptor.getValue().responseSize()==compressedData.length); + + //assert that the bytes received from callback is same as compressed data + Assert.assertTrue(responseArgumentCaptor.getValue().responseSize() == compressedData.length); server.shutdown(); } @@ -353,14 +316,14 @@ public void testOkHttpInspectorRequest() throws Exception { .addHeader("HOST", "flipkart") .build(); - DefaultInterpreter.OkHttpInspectorRequest okHttpInspectorRequest = new DefaultInterpreter.OkHttpInspectorRequest(1, request.url().url(), request.method(), OkHeaders.contentLength(request), request.header("HOST")); + DefaultInterpreter.OkHttpInspectorRequest okHttpInspectorRequest = new DefaultInterpreter.OkHttpInspectorRequest(1, request.url().url(), request.method(), Utils.contentLength(request), request.header("HOST")); //assert id is same Assert.assertTrue(okHttpInspectorRequest.requestId() == 1); //assert url is same - Assert.assertTrue(okHttpInspectorRequest.url().equals(request.url())); + Assert.assertTrue(okHttpInspectorRequest.url().equals(request.url().url())); //assert content length is same - Assert.assertTrue(okHttpInspectorRequest.requestSize() == OkHeaders.contentLength(request)); + Assert.assertTrue(okHttpInspectorRequest.requestSize() == Utils.contentLength(request)); //assert hostname is same Assert.assertTrue(okHttpInspectorRequest.hostName().equals(request.header("HOST"))); //assert method is same @@ -385,7 +348,10 @@ public void testOkHttpInspectorResponse() throws Exception { Assert.assertTrue(okHttpInspectorResponse.statusCode() == 200); } - private static class CustomChain implements Interceptor.Chain { + /** + * Only for testing purposes. + */ + public static class CustomChain implements Interceptor.Chain { private final Request mRequest; private final Response mResponse; @Nullable diff --git a/library/src/test/java/com/flipkart/okhttpstats/handler/ForwardingResponseTest.java b/library/src/test/java/com/flipkart/okhttpstats/handler/ForwardingResponseTest.java new file mode 100644 index 0000000..92f034a --- /dev/null +++ b/library/src/test/java/com/flipkart/okhttpstats/handler/ForwardingResponseTest.java @@ -0,0 +1,153 @@ +package com.flipkart.okhttpstats.handler; + +import android.net.NetworkInfo; + +import com.flipkart.okhttpstats.model.RequestStats; + +import org.junit.Test; + +import java.io.IOException; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +/** + * Created by anirudh.r on 15/07/16. + * Test for {@link ForwardingResponse} + */ +public class ForwardingResponseTest { + + /** + * Test to verify that {@link OnStatusCodeAwareResponseListener#onResponseServerSuccess(NetworkInfo, RequestStats)} + * gets called for all status code from range 200 to 399. + * + * @throws Exception + */ + @Test + public void testOnResponseServerSuccessCalledFor2XX3XX() throws Exception { + OnStatusCodeAwareResponseListener onStatusCodeAwareResponseListener = mock(OnStatusCodeAwareResponseListener.class); + ForwardingResponse forwardingResponse = new ForwardingResponse(onStatusCodeAwareResponseListener); + + RequestStats requestStats = new RequestStats(1); + requestStats.setStatusCode(200); + requestStats.setHostName("flipkart.com"); + + NetworkInfo info = mock(NetworkInfo.class); + + forwardingResponse.onResponseSuccess(info, requestStats); + + //verify that onResponseServerSuccess gets called once for status 200 + verify(onStatusCodeAwareResponseListener, times(1)).onResponseServerSuccess(info, requestStats); + reset(onStatusCodeAwareResponseListener); + + requestStats = new RequestStats(1); + requestStats.setStatusCode(299); + requestStats.setHostName("flipkart.com"); + + forwardingResponse.onResponseSuccess(info, requestStats); + + //verify that onResponseServerSuccess gets called once for status 299 + verify(onStatusCodeAwareResponseListener, times(1)).onResponseServerSuccess(info, requestStats); + reset(onStatusCodeAwareResponseListener); + + requestStats = new RequestStats(1); + requestStats.setStatusCode(300); + requestStats.setHostName("flipkart.com"); + + forwardingResponse.onResponseSuccess(info, requestStats); + + //verify that onResponseServerSuccess gets called once for status 300 + verify(onStatusCodeAwareResponseListener, times(1)).onResponseServerSuccess(info, requestStats); + reset(onStatusCodeAwareResponseListener); + + requestStats = new RequestStats(1); + requestStats.setStatusCode(399); + requestStats.setHostName("flipkart.com"); + + forwardingResponse.onResponseSuccess(info, requestStats); + + //verify that onResponseServerSuccess gets called once for status 399 + verify(onStatusCodeAwareResponseListener, times(1)).onResponseServerSuccess(info, requestStats); + reset(onStatusCodeAwareResponseListener); + } + + /** + * Test to verify that {@link OnStatusCodeAwareResponseListener#onResponseServerError(NetworkInfo, RequestStats)} + * gets called for all status code from range 400 to 599. + * + * @throws Exception + */ + @Test + public void testOnResponseServerErrorCalledFor4XX5XX() throws Exception { + OnStatusCodeAwareResponseListener onStatusCodeAwareResponseListener = mock(OnStatusCodeAwareResponseListener.class); + ForwardingResponse forwardingResponse = new ForwardingResponse(onStatusCodeAwareResponseListener); + + RequestStats requestStats = new RequestStats(1); + requestStats.setStatusCode(400); + requestStats.setHostName("flipkart.com"); + + NetworkInfo info = mock(NetworkInfo.class); + + forwardingResponse.onResponseSuccess(info, requestStats); + + //verify that onResponseServerError gets called once for status 400 + verify(onStatusCodeAwareResponseListener, times(1)).onResponseServerError(info, requestStats); + reset(onStatusCodeAwareResponseListener); + + requestStats = new RequestStats(1); + requestStats.setStatusCode(499); + requestStats.setHostName("flipkart.com"); + + forwardingResponse.onResponseSuccess(info, requestStats); + + //verify that onResponseServerError gets called once for status 499 + verify(onStatusCodeAwareResponseListener, times(1)).onResponseServerError(info, requestStats); + reset(onStatusCodeAwareResponseListener); + + requestStats = new RequestStats(1); + requestStats.setStatusCode(500); + requestStats.setHostName("flipkart.com"); + + forwardingResponse.onResponseSuccess(info, requestStats); + + //verify that onResponseServerError gets called once for status 500 + verify(onStatusCodeAwareResponseListener, times(1)).onResponseServerError(info, requestStats); + reset(onStatusCodeAwareResponseListener); + + requestStats = new RequestStats(1); + requestStats.setStatusCode(599); + requestStats.setHostName("flipkart.com"); + + forwardingResponse.onResponseSuccess(info, requestStats); + + //verify that onResponseServerError gets called once for status 599 + verify(onStatusCodeAwareResponseListener, times(1)).onResponseServerError(info, requestStats); + reset(onStatusCodeAwareResponseListener); + } + + /** + * Test to verify that {@link OnStatusCodeAwareResponseListener#onResponseNetworkError(NetworkInfo, RequestStats, Exception)} + * gets called for any network related errors. + * + * @throws Exception + */ + @Test + public void testOnResponseNetworkErrorCalledForNetworkErrors() throws Exception { + OnStatusCodeAwareResponseListener onStatusCodeAwareResponseListener = mock(OnStatusCodeAwareResponseListener.class); + ForwardingResponse forwardingResponse = new ForwardingResponse(onStatusCodeAwareResponseListener); + + RequestStats requestStats = new RequestStats(1); + requestStats.setStatusCode(400); + requestStats.setHostName("flipkart.com"); + + NetworkInfo info = mock(NetworkInfo.class); + IOException e = new IOException("Test error"); + + forwardingResponse.onResponseError(info, requestStats, e); + + //verify that onResponseNetworkError gets called once + verify(onStatusCodeAwareResponseListener, times(1)).onResponseNetworkError(info, requestStats, e); + } +} diff --git a/library/src/test/java/com/flipkart/okhttpstats/PersistentStatsHandlerTest.java b/library/src/test/java/com/flipkart/okhttpstats/handler/PersistentStatsHandlerTest.java similarity index 79% rename from library/src/test/java/com/flipkart/okhttpstats/PersistentStatsHandlerTest.java rename to library/src/test/java/com/flipkart/okhttpstats/handler/PersistentStatsHandlerTest.java index b4d7aeb..10cb2ac 100644 --- a/library/src/test/java/com/flipkart/okhttpstats/PersistentStatsHandlerTest.java +++ b/library/src/test/java/com/flipkart/okhttpstats/handler/PersistentStatsHandlerTest.java @@ -1,12 +1,12 @@ -package com.flipkart.okhttpstats; +package com.flipkart.okhttpstats.handler; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; -import com.flipkart.okhttpstats.handler.OnResponseListener; -import com.flipkart.okhttpstats.handler.PersistentStatsHandler; +import com.flipkart.okhttpstats.BuildConfig; import com.flipkart.okhttpstats.model.RequestStats; +import com.flipkart.okhttpstats.toolbox.PreferenceManager; import org.junit.Assert; import org.junit.Test; @@ -22,11 +22,14 @@ import java.net.SocketTimeoutException; import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyFloat; +import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * Created by anirudh.r on 13/05/16 at 12:28 AM. @@ -56,7 +59,7 @@ public void testAddListener() throws Exception { persistentStatsHandler.addListener(onResponseListener); //assert size is 1 - Assert.assertTrue(persistentStatsHandler.getOnResponseReceivedListenerList().size() == 1); + Assert.assertTrue(persistentStatsHandler.getOnResponseListeners().size() == 1); } /** @@ -72,11 +75,11 @@ public void testRemoveListener() throws Exception { persistentStatsHandler.addListener(onResponseListener); //assert size is 1 - Assert.assertTrue(persistentStatsHandler.getOnResponseReceivedListenerList().size() == 1); + Assert.assertTrue(persistentStatsHandler.getOnResponseListeners().size() == 1); persistentStatsHandler.removeListener(onResponseListener); //assert size is 0 - Assert.assertTrue(persistentStatsHandler.getOnResponseReceivedListenerList().size() == 0); + Assert.assertTrue(persistentStatsHandler.getOnResponseListeners().size() == 0); } /** @@ -93,7 +96,7 @@ public void testOnResponseReceived() throws Exception { persistentStatsHandler.addListener(onResponseListener); //assert size is 1 - Assert.assertTrue(persistentStatsHandler.getOnResponseReceivedListenerList().size() == 1); + Assert.assertTrue(persistentStatsHandler.getOnResponseListeners().size() == 1); RequestStats requestStats = new RequestStats(1); persistentStatsHandler.onResponseReceived(requestStats); @@ -106,7 +109,7 @@ public void testOnResponseReceived() throws Exception { persistentStatsHandler.addListener(onResponseListener1); //assert size is 2 - Assert.assertTrue(persistentStatsHandler.getOnResponseReceivedListenerList().size() == 2); + Assert.assertTrue(persistentStatsHandler.getOnResponseListeners().size() == 2); persistentStatsHandler.onResponseReceived(requestStats); //verify onResponseReceived of 1st listener gets called once @@ -129,7 +132,7 @@ public void testOnHttpExchangeError() throws Exception { persistentStatsHandler.addListener(onResponseListener); //assert size is 1 - Assert.assertTrue(persistentStatsHandler.getOnResponseReceivedListenerList().size() == 1); + Assert.assertTrue(persistentStatsHandler.getOnResponseListeners().size() == 1); RequestStats requestStats = new RequestStats(1); persistentStatsHandler.onHttpExchangeError(requestStats, new IOException("")); @@ -142,7 +145,7 @@ public void testOnHttpExchangeError() throws Exception { reset(onResponseListener); //assert size is 2 - Assert.assertTrue(persistentStatsHandler.getOnResponseReceivedListenerList().size() == 2); + Assert.assertTrue(persistentStatsHandler.getOnResponseListeners().size() == 2); persistentStatsHandler.onHttpExchangeError(requestStats, new IOException("")); verify(onResponseListener, times(1)).onResponseError(any(NetworkInfo.class), eq(requestStats), any(IOException.class)); @@ -163,7 +166,7 @@ public void testOnInputStreamError() throws Exception { persistentStatsHandler.addListener(onResponseListener); //assert size is 1 - Assert.assertTrue(persistentStatsHandler.getOnResponseReceivedListenerList().size() == 1); + Assert.assertTrue(persistentStatsHandler.getOnResponseListeners().size() == 1); RequestStats requestStats = new RequestStats(1); persistentStatsHandler.onResponseInputStreamError(requestStats, new SocketTimeoutException()); @@ -175,7 +178,7 @@ public void testOnInputStreamError() throws Exception { persistentStatsHandler.addListener(onResponseListener1); //assert size is 2 - Assert.assertTrue(persistentStatsHandler.getOnResponseReceivedListenerList().size() == 2); + Assert.assertTrue(persistentStatsHandler.getOnResponseListeners().size() == 2); } /** @@ -210,4 +213,33 @@ public void testGetNetworkKey() throws Exception { PersistentStatsHandler persistentStatsHandler = new PersistentStatsHandler(RuntimeEnvironment.application); Assert.assertTrue(persistentStatsHandler.getNetworkKey(shadowConnectivityManager.getActiveNetworkInfo()) != null); } + + /** + * Test to verify that {@link PreferenceManager#setAverageSpeed(String, float)} gets called when number of request sent is greater + * than the max number + * + * @throws Exception + */ + @Test + public void testSaveToSharedPreferenceCalled() throws Exception { + PreferenceManager preferenceManager = mock(PreferenceManager.class); + + PersistentStatsHandler persistentStatsHandler = new PersistentStatsHandler(RuntimeEnvironment.application, preferenceManager); + persistentStatsHandler.setMaxSizeForPersistence(3); + + RequestStats requestStats = new RequestStats(2); + requestStats.setStatusCode(200); + + RequestStats requestStats1 = new RequestStats(2); + requestStats.setStatusCode(200); + + RequestStats requestStats2 = new RequestStats(2); + requestStats.setStatusCode(200); + + persistentStatsHandler.onResponseReceived(requestStats); + persistentStatsHandler.onResponseReceived(requestStats1); + persistentStatsHandler.onResponseReceived(requestStats2); + + verify(preferenceManager, times(1)).setAverageSpeed(anyString(), anyFloat()); + } } diff --git a/library/src/test/java/com/flipkart/okhttpstats/interpreter/DefaultInterpreterTest.java b/library/src/test/java/com/flipkart/okhttpstats/interpreter/DefaultInterpreterTest.java new file mode 100644 index 0000000..a22609a --- /dev/null +++ b/library/src/test/java/com/flipkart/okhttpstats/interpreter/DefaultInterpreterTest.java @@ -0,0 +1,191 @@ +package com.flipkart.okhttpstats.interpreter; + +import android.net.Uri; + +import com.flipkart.okhttpstats.NetworkInterceptor; +import com.flipkart.okhttpstats.NetworkInterceptorTest; +import com.flipkart.okhttpstats.reporter.NetworkEventReporter; +import com.flipkart.okhttpstats.toolbox.Utils; + +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; + +import okhttp3.MediaType; +import okhttp3.Protocol; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +/** + * Created by anirudh.r on 15/07/16. + * Test for {@link DefaultInterpreter} + */ +public class DefaultInterpreterTest { + + /** + * Test to verify that {@link NetworkEventReporter#responseReceived(NetworkEventReporter.InspectorRequest, NetworkEventReporter.InspectorResponse)} gets + * called whenever we receive a response. + * + * @throws Exception + */ + @Test + public void testResponseReceivedCalledForEventReporter() throws Exception { + + NetworkEventReporter networkEventReporter = mock(NetworkEventReporter.class); + DefaultInterpreter defaultInterpreter = new DefaultInterpreter(networkEventReporter); + + NetworkInterceptor.TimeInfo info = new NetworkInterceptor.TimeInfo(); + info.mStartTime = 10; + info.mEndTime = 20; + + Request request = new Request.Builder() + .url("http://www.flipkart.com") + .build(); + + Response response = new Response.Builder() + .code(200) + .request(request) + .protocol(Protocol.HTTP_1_1) + .addHeader("Content-Length", "20") + .build(); + + defaultInterpreter.interpretResponseStream(1, info, request, response); + + //verify that responseReceived gets called once + verify(networkEventReporter, times(1)).responseReceived(any(NetworkEventReporter.InspectorRequest.class), any(NetworkEventReporter.InspectorResponse.class)); + } + + /** + * Test to verify that {@link NetworkEventReporter#httpExchangeError(NetworkEventReporter.InspectorRequest, IOException)} gets called + * whenever any error occurs. + * + * @throws Exception + */ + @Test + public void testOnHttpExchangeErrorGetsCalled() throws Exception { + NetworkEventReporter networkEventReporter = mock(NetworkEventReporter.class); + DefaultInterpreter defaultInterpreter = new DefaultInterpreter(networkEventReporter); + + NetworkInterceptor.TimeInfo info = new NetworkInterceptor.TimeInfo(); + info.mStartTime = 10; + info.mEndTime = 20; + + Request request = new Request.Builder() + .url("http://www.flipkart.com") + .build(); + + IOException exception = new IOException("Test error"); + + defaultInterpreter.interpretError(1, info, request, exception); + + //verify that httpExchangeError gets called once + verify(networkEventReporter, times(1)).httpExchangeError(any(NetworkEventReporter.InspectorRequest.class), eq(exception)); + } + + /** + * Tests setter and getter of {@link com.flipkart.okhttpstats.interpreter.DefaultInterpreter.OkHttpInspectorRequest} + */ + @Test + public void testOkHttpInspectorRequest() throws Exception { + + String requestText = "Test Request"; + + Request request = new Request.Builder() + .url("http://www.flipkart.com") + .method("POST", RequestBody.create(MediaType.parse("text/plain"), requestText)) + .addHeader("Content-Length", "20") + .addHeader("HOST", "flipkart") + .build(); + + DefaultInterpreter.OkHttpInspectorRequest okHttpInspectorRequest = new DefaultInterpreter.OkHttpInspectorRequest(1, request.url().url(), request.method(), Utils.contentLength(request), request.header("HOST")); + + //assert id is same + Assert.assertTrue(okHttpInspectorRequest.requestId() == 1); + //assert url is same + Assert.assertTrue(okHttpInspectorRequest.url().equals(request.url().url())); + //assert content length is same + Assert.assertTrue(okHttpInspectorRequest.requestSize() == Utils.contentLength(request)); + //assert hostname is same + Assert.assertTrue(okHttpInspectorRequest.hostName().equals(request.header("HOST"))); + //assert method is same + Assert.assertTrue(okHttpInspectorRequest.method().equals(request.method())); + } + + /** + * Tests setter and getter of {@link com.flipkart.okhttpstats.interpreter.DefaultInterpreter.OkHttpInspectorResponse} + */ + @Test + public void testOkHttpInspectorResponse() throws Exception { + + DefaultInterpreter.OkHttpInspectorResponse okHttpInspectorResponse = new DefaultInterpreter.OkHttpInspectorResponse(1, 200, 20, 2, 3); + + //assert id is same + Assert.assertTrue(okHttpInspectorResponse.requestId() == 1); + //assert content length is same + Assert.assertTrue(okHttpInspectorResponse.responseSize() == 20); + //assert response time is same + Assert.assertTrue(okHttpInspectorResponse.startTime() == 2); + //assert statuscode is same + Assert.assertTrue(okHttpInspectorResponse.statusCode() == 200); + } + + /** + * Test to verify {@link com.flipkart.okhttpstats.interpreter.DefaultInterpreter.ForwardingResponseBody} + * + * @throws IOException + */ + @Test + public void testResponseBody() throws IOException { + NetworkEventReporter networkEventReporter = mock(NetworkEventReporter.class); + NetworkInterpreter networkInterpreter = new DefaultInterpreter(networkEventReporter); + + NetworkInterceptor networkInterceptor = new NetworkInterceptor.Builder() + .setEnabled(true) + .setNetworkInterpreter(networkInterpreter) + .build(); + + String requestText = "Test Request"; + + //creating request + Request request = new Request.Builder() + .url("http://www.flipkart.com") + .method("POST", RequestBody.create(MediaType.parse("text/plain"), requestText)) + .build(); + + //creating response + Response response = new Response.Builder() + .request(request) + .protocol(Protocol.HTTP_1_1) + .code(200) + .addHeader("Content-Length", "20") + .body(ResponseBody.create(MediaType.parse("text/plain"), "any text")) + .build(); + + NetworkInterceptorTest.CustomChain customChain = new NetworkInterceptorTest.CustomChain(request, response, null); + networkInterceptor.intercept(customChain); + + //intercepted request object + Response interceptedResponse = customChain.proceed(request); + DefaultInterpreter.ForwardingResponseBody forwardingResponseBody = new DefaultInterpreter.ForwardingResponseBody(interceptedResponse.body(), interceptedResponse.body().byteStream()); + + interceptedResponse = interceptedResponse.newBuilder().body(forwardingResponseBody).build(); + + //assert the response body of response + Assert.assertTrue(interceptedResponse.body() == forwardingResponseBody); + //assert the content type + Assert.assertTrue(interceptedResponse.body().contentType() == forwardingResponseBody.contentType()); + //assert the content length + Assert.assertTrue(interceptedResponse.body().contentLength() == forwardingResponseBody.contentLength()); + //assert the source + Assert.assertTrue(interceptedResponse.body().source() == forwardingResponseBody.source()); + } +} diff --git a/library/src/test/java/com/flipkart/okhttpstats/RequestStatsTest.java b/library/src/test/java/com/flipkart/okhttpstats/model/RequestStatsTest.java similarity index 95% rename from library/src/test/java/com/flipkart/okhttpstats/RequestStatsTest.java rename to library/src/test/java/com/flipkart/okhttpstats/model/RequestStatsTest.java index d79c36b..4ce500b 100644 --- a/library/src/test/java/com/flipkart/okhttpstats/RequestStatsTest.java +++ b/library/src/test/java/com/flipkart/okhttpstats/model/RequestStatsTest.java @@ -1,7 +1,8 @@ -package com.flipkart.okhttpstats; +package com.flipkart.okhttpstats.model; import android.net.NetworkInfo; +import com.flipkart.okhttpstats.BuildConfig; import com.flipkart.okhttpstats.model.RequestStats; import org.junit.Assert; diff --git a/library/src/test/java/com/flipkart/okhttpstats/NetworkEventReporterTest.java b/library/src/test/java/com/flipkart/okhttpstats/reporter/NetworkEventReporterTest.java similarity index 98% rename from library/src/test/java/com/flipkart/okhttpstats/NetworkEventReporterTest.java rename to library/src/test/java/com/flipkart/okhttpstats/reporter/NetworkEventReporterTest.java index ce0bc0c..e83ff11 100644 --- a/library/src/test/java/com/flipkart/okhttpstats/NetworkEventReporterTest.java +++ b/library/src/test/java/com/flipkart/okhttpstats/reporter/NetworkEventReporterTest.java @@ -1,9 +1,10 @@ -package com.flipkart.okhttpstats; +package com.flipkart.okhttpstats.reporter; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; +import com.flipkart.okhttpstats.BuildConfig; import com.flipkart.okhttpstats.handler.NetworkRequestStatsHandler; import com.flipkart.okhttpstats.model.RequestStats; import com.flipkart.okhttpstats.reporter.NetworkEventReporter; diff --git a/library/src/test/java/com/flipkart/okhttpstats/CountingInputStreamTest.java b/library/src/test/java/com/flipkart/okhttpstats/response/CountingInputStreamTest.java similarity index 97% rename from library/src/test/java/com/flipkart/okhttpstats/CountingInputStreamTest.java rename to library/src/test/java/com/flipkart/okhttpstats/response/CountingInputStreamTest.java index acf9d3c..a7aee6d 100644 --- a/library/src/test/java/com/flipkart/okhttpstats/CountingInputStreamTest.java +++ b/library/src/test/java/com/flipkart/okhttpstats/response/CountingInputStreamTest.java @@ -1,5 +1,6 @@ -package com.flipkart.okhttpstats; +package com.flipkart.okhttpstats.response; +import com.flipkart.okhttpstats.BuildConfig; import com.flipkart.okhttpstats.response.CountingInputStream; import com.flipkart.okhttpstats.response.ResponseHandler; diff --git a/library/src/test/java/com/flipkart/okhttpstats/DefaultResponseHandlerTest.java b/library/src/test/java/com/flipkart/okhttpstats/response/DefaultResponseHandlerTest.java similarity index 93% rename from library/src/test/java/com/flipkart/okhttpstats/DefaultResponseHandlerTest.java rename to library/src/test/java/com/flipkart/okhttpstats/response/DefaultResponseHandlerTest.java index 91805c3..885f24f 100644 --- a/library/src/test/java/com/flipkart/okhttpstats/DefaultResponseHandlerTest.java +++ b/library/src/test/java/com/flipkart/okhttpstats/response/DefaultResponseHandlerTest.java @@ -1,5 +1,6 @@ -package com.flipkart.okhttpstats; +package com.flipkart.okhttpstats.response; +import com.flipkart.okhttpstats.BuildConfig; import com.flipkart.okhttpstats.response.DefaultResponseHandler; import com.flipkart.okhttpstats.response.ResponseHandler; diff --git a/library/src/test/java/com/flipkart/okhttpstats/NetworkStatTest.java b/library/src/test/java/com/flipkart/okhttpstats/toolbox/NetworkStatTest.java similarity index 92% rename from library/src/test/java/com/flipkart/okhttpstats/NetworkStatTest.java rename to library/src/test/java/com/flipkart/okhttpstats/toolbox/NetworkStatTest.java index 4d58f1e..fa249fa 100644 --- a/library/src/test/java/com/flipkart/okhttpstats/NetworkStatTest.java +++ b/library/src/test/java/com/flipkart/okhttpstats/toolbox/NetworkStatTest.java @@ -1,5 +1,6 @@ -package com.flipkart.okhttpstats; +package com.flipkart.okhttpstats.toolbox; +import com.flipkart.okhttpstats.BuildConfig; import com.flipkart.okhttpstats.model.RequestStats; import com.flipkart.okhttpstats.toolbox.NetworkStat; diff --git a/library/src/test/java/com/flipkart/okhttpstats/PreferenceManagerTest.java b/library/src/test/java/com/flipkart/okhttpstats/toolbox/PreferenceManagerTest.java similarity index 97% rename from library/src/test/java/com/flipkart/okhttpstats/PreferenceManagerTest.java rename to library/src/test/java/com/flipkart/okhttpstats/toolbox/PreferenceManagerTest.java index baeedf1..4e01d50 100644 --- a/library/src/test/java/com/flipkart/okhttpstats/PreferenceManagerTest.java +++ b/library/src/test/java/com/flipkart/okhttpstats/toolbox/PreferenceManagerTest.java @@ -1,9 +1,10 @@ -package com.flipkart.okhttpstats; +package com.flipkart.okhttpstats.toolbox; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; +import com.flipkart.okhttpstats.BuildConfig; import com.flipkart.okhttpstats.handler.PersistentStatsHandler; import com.flipkart.okhttpstats.toolbox.PreferenceManager;