Search in sources :

Example 6 with MockResponse

use of com.google.mockwebserver.MockResponse in project android_frameworks_base by ParanoidAndroid.

the class CookiesTest method testCookiesAreNotLogged.

/**
     * Test that we don't log potentially sensitive cookie values.
     * http://b/3095990
     */
public void testCookiesAreNotLogged() throws IOException, URISyntaxException {
    // enqueue an HTTP response with a cookie that will be rejected
    server.enqueue(new MockResponse().addHeader("Set-Cookie: password=secret; Domain=fake.domain"));
    server.play();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Logger logger = Logger.getLogger("org.apache.http");
    StreamHandler handler = new StreamHandler(out, new SimpleFormatter());
    logger.addHandler(handler);
    try {
        HttpClient client = new DefaultHttpClient();
        client.execute(new HttpGet(server.getUrl("/").toURI()));
        handler.close();
        String log = out.toString("UTF-8");
        assertTrue(log, log.contains("password"));
        assertTrue(log, log.contains("fake.domain"));
        assertFalse(log, log.contains("secret"));
    } finally {
        logger.removeHandler(handler);
    }
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) StreamHandler(java.util.logging.StreamHandler) SimpleFormatter(java.util.logging.SimpleFormatter) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Logger(java.util.logging.Logger) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 7 with MockResponse

use of com.google.mockwebserver.MockResponse in project android_frameworks_base by ParanoidAndroid.

the class DefaultHttpClientTest method testServerClosesOutput.

private void testServerClosesOutput(SocketPolicy socketPolicy) throws Exception {
    server.enqueue(new MockResponse().setBody("This connection won't pool properly").setSocketPolicy(socketPolicy));
    server.enqueue(new MockResponse().setBody("This comes after a busted connection"));
    server.play();
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse a = client.execute(new HttpGet(server.getUrl("/a").toURI()));
    assertEquals("This connection won't pool properly", contentToString(a));
    assertEquals(0, server.takeRequest().getSequenceNumber());
    HttpResponse b = client.execute(new HttpGet(server.getUrl("/b").toURI()));
    assertEquals("This comes after a busted connection", contentToString(b));
    // sequence number 0 means the HTTP socket connection was not reused
    assertEquals(0, server.takeRequest().getSequenceNumber());
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 8 with MockResponse

use of com.google.mockwebserver.MockResponse in project android_frameworks_base by ParanoidAndroid.

the class HttpResponseCacheTest method testStatisticsTracking.

/**
     * Make sure that statistics tracking are wired all the way through the
     * wrapper class. http://code.google.com/p/android/issues/detail?id=25418
     */
public void testStatisticsTracking() throws Exception {
    HttpResponseCache cache = HttpResponseCache.install(cacheDir, 10 * 1024 * 1024);
    server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60").setBody("A"));
    server.play();
    URLConnection c1 = server.getUrl("/").openConnection();
    assertEquals('A', c1.getInputStream().read());
    assertEquals(1, cache.getRequestCount());
    assertEquals(1, cache.getNetworkCount());
    assertEquals(0, cache.getHitCount());
    URLConnection c2 = server.getUrl("/").openConnection();
    assertEquals('A', c2.getInputStream().read());
    URLConnection c3 = server.getUrl("/").openConnection();
    assertEquals('A', c3.getInputStream().read());
    assertEquals(3, cache.getRequestCount());
    assertEquals(1, cache.getNetworkCount());
    assertEquals(2, cache.getHitCount());
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) URLConnection(java.net.URLConnection)

Example 9 with MockResponse

use of com.google.mockwebserver.MockResponse in project ribbon by Netflix.

the class ListenerTest method testSuccessExecutionOnAbosoluteURI.

@Test
public void testSuccessExecutionOnAbosoluteURI() throws IOException {
    MockWebServer server = new MockWebServer();
    String content = "OK";
    server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "application/json").setBody(content));
    server.play();
    IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "2000").withProperty(CommonClientConfigKey.MaxAutoRetries, 1).withProperty(CommonClientConfigKey.MaxAutoRetriesNextServer, 1);
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("http://localhost:" + server.getPort() + "/testAsync/person");
    Server badServer = new Server("localhost:12345");
    Server goodServer = new Server("localhost:" + server.getPort());
    List<Server> servers = Lists.newArrayList(goodServer, badServer);
    BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder().withRule(new AvailabilityFilteringRule()).withPing(new DummyPing()).buildFixedServerListLoadBalancer(servers);
    IClientConfig overrideConfig = DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.ConnectTimeout, 500);
    TestExecutionListener<ByteBuf, ByteBuf> listener = new TestExecutionListener<ByteBuf, ByteBuf>(request, overrideConfig);
    List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>>newArrayList(listener);
    LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners);
    HttpClientResponse<ByteBuf> response = client.submit(request, null, overrideConfig).toBlocking().last();
    assertEquals(200, response.getStatus().code());
    assertEquals(1, listener.executionStartCounter.get());
    assertEquals(1, listener.startWithServerCounter.get());
    assertEquals(0, listener.exceptionWithServerCounter.get());
    assertEquals(0, listener.executionFailedCounter.get());
    assertEquals(1, listener.executionSuccessCounter.get());
    assertEquals(500, listener.getContext().getClientProperty(CommonClientConfigKey.ConnectTimeout).intValue());
    assertTrue(listener.isContextChecked());
    assertTrue(listener.isCheckExecutionInfo());
    assertSame(response, listener.getResponse());
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) Server(com.netflix.loadbalancer.Server) MockWebServer(com.google.mockwebserver.MockWebServer) BaseLoadBalancer(com.netflix.loadbalancer.BaseLoadBalancer) ByteBuf(io.netty.buffer.ByteBuf) ExecutionListener(com.netflix.loadbalancer.reactive.ExecutionListener) DummyPing(com.netflix.loadbalancer.DummyPing) MockWebServer(com.google.mockwebserver.MockWebServer) IClientConfig(com.netflix.client.config.IClientConfig) AvailabilityFilteringRule(com.netflix.loadbalancer.AvailabilityFilteringRule) Test(org.junit.Test)

Example 10 with MockResponse

use of com.google.mockwebserver.MockResponse in project ribbon by Netflix.

the class RibbonTest method testCommandWithMetaData.

@Test
@Ignore
public void testCommandWithMetaData() throws IOException, InterruptedException, ExecutionException {
    // LogManager.getRootLogger().setLevel((Level)Level.DEBUG);
    MockWebServer server = new MockWebServer();
    String content = "Hello world";
    for (int i = 0; i < 6; i++) {
        server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain").setBody(content));
    }
    server.play();
    HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create().withConfigurationBasedServerList("localhost:" + server.getPort()).withMaxAutoRetriesNextServer(3));
    HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test").withUriTemplate("/").withMethod("GET").withCacheProvider("somekey", new CacheProvider<ByteBuf>() {

        @Override
        public Observable<ByteBuf> get(String key, Map<String, Object> vars) {
            return Observable.error(new Exception("Cache miss"));
        }
    }).build();
    RibbonRequest<ByteBuf> request = template.requestBuilder().build();
    final AtomicBoolean success = new AtomicBoolean(false);
    RequestWithMetaData<ByteBuf> metaRequest = request.withMetadata();
    Observable<String> result = metaRequest.toObservable().flatMap(new Func1<RibbonResponse<Observable<ByteBuf>>, Observable<String>>() {

        @Override
        public Observable<String> call(final RibbonResponse<Observable<ByteBuf>> response) {
            success.set(response.getHystrixInfo().isSuccessfulExecution());
            return response.content().map(new Func1<ByteBuf, String>() {

                @Override
                public String call(ByteBuf t1) {
                    return t1.toString(Charset.defaultCharset());
                }
            });
        }
    });
    String s = result.toBlocking().single();
    assertEquals(content, s);
    assertTrue(success.get());
    Future<RibbonResponse<ByteBuf>> future = metaRequest.queue();
    RibbonResponse<ByteBuf> response = future.get();
    assertTrue(future.isDone());
    assertEquals(content, response.content().toString(Charset.defaultCharset()));
    assertTrue(response.getHystrixInfo().isSuccessfulExecution());
    RibbonResponse<ByteBuf> result1 = metaRequest.execute();
    assertEquals(content, result1.content().toString(Charset.defaultCharset()));
    assertTrue(result1.getHystrixInfo().isSuccessfulExecution());
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) HttpResourceGroup(com.netflix.ribbon.http.HttpResourceGroup) ByteBuf(io.netty.buffer.ByteBuf) HystrixBadRequestException(com.netflix.hystrix.exception.HystrixBadRequestException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Observable(rx.Observable) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MockWebServer(com.google.mockwebserver.MockWebServer) Func1(rx.functions.Func1) Map(java.util.Map) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

MockResponse (com.google.mockwebserver.MockResponse)240 HttpURLConnection (java.net.HttpURLConnection)89 RecordedRequest (com.google.mockwebserver.RecordedRequest)80 HttpGet (org.apache.http.client.methods.HttpGet)54 HttpClient (org.apache.http.client.HttpClient)48 HttpResponse (org.apache.http.HttpResponse)42 MockWebServer (com.google.mockwebserver.MockWebServer)39 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)36 TestSSLContext (libcore.javax.net.ssl.TestSSLContext)32 URLConnection (java.net.URLConnection)29 IOException (java.io.IOException)27 ByteArrayOutputStream (java.io.ByteArrayOutputStream)25 InputStream (java.io.InputStream)23 LargeTest (android.test.suitebuilder.annotation.LargeTest)18 GZIPInputStream (java.util.zip.GZIPInputStream)18 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)18 OutputStream (java.io.OutputStream)17 GZIPOutputStream (java.util.zip.GZIPOutputStream)17 CookieManager (java.net.CookieManager)14 URL (java.net.URL)14