Search in sources :

Example 16 with MockWebServer

use of com.google.mockwebserver.MockWebServer in project j2objc by google.

the class CookiesTest method testQuotedAttributeValues.

public void testQuotedAttributeValues() throws Exception {
    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    CookieHandler.setDefault(cookieManager);
    MockWebServer server = new MockWebServer();
    server.play();
    server.enqueue(new MockResponse().addHeader("Set-Cookie2: a=\"android\"; " + "Comment=\"this cookie is delicious\"; " + "CommentURL=\"http://google.com/\"; " + "Discard; " + "Domain=\"" + server.getCookieDomain() + "\"; " + "Max-Age=\"60\"; " + "Path=\"/path\"; " + "Port=\"80,443," + server.getPort() + "\"; " + "Secure; " + "Version=\"1\""));
    get(server, "/path/foo");
    List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
    assertEquals(1, cookies.size());
    HttpCookie cookie = cookies.get(0);
    assertEquals("a", cookie.getName());
    assertEquals("android", cookie.getValue());
    assertEquals("this cookie is delicious", cookie.getComment());
    assertEquals("http://google.com/", cookie.getCommentURL());
    assertEquals(true, cookie.getDiscard());
    assertEquals(server.getCookieDomain(), cookie.getDomain());
    assertEquals(60, cookie.getMaxAge());
    assertEquals("/path", cookie.getPath());
    assertEquals("80,443," + server.getPort(), cookie.getPortlist());
    assertEquals(true, cookie.getSecure());
    assertEquals(1, cookie.getVersion());
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) MockWebServer(com.google.mockwebserver.MockWebServer) HttpCookie(java.net.HttpCookie) CookieManager(java.net.CookieManager)

Example 17 with MockWebServer

use of com.google.mockwebserver.MockWebServer in project robovm by robovm.

the class URLConnectionTest method testRedirectToAnotherOriginServer.

public void testRedirectToAnotherOriginServer() throws Exception {
    MockWebServer server2 = new MockWebServer();
    try {
        // RoboVM note: Modified to call server2.shutdown() after test finishes regardless of outcome.
        server2.enqueue(new MockResponse().setBody("This is the 2nd server!"));
        server2.play();
        server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP).addHeader("Location: " + server2.getUrl("/").toString()).setBody("This page has moved!"));
        server.enqueue(new MockResponse().setBody("This is the first server again!"));
        server.play();
        URLConnection connection = server.getUrl("/").openConnection();
        assertEquals("This is the 2nd server!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
        assertEquals(server2.getUrl("/"), connection.getURL());
        // make sure the first server was careful to recycle the connection
        assertEquals("This is the first server again!", readAscii(server.getUrl("/").openStream(), Integer.MAX_VALUE));
        RecordedRequest first = server.takeRequest();
        assertContains(first.getHeaders(), "Host: " + hostName + ":" + server.getPort());
        RecordedRequest second = server2.takeRequest();
        assertContains(second.getHeaders(), "Host: " + hostName + ":" + server2.getPort());
        RecordedRequest third = server.takeRequest();
        assertEquals("Expected connection reuse", 1, third.getSequenceNumber());
    } finally {
        server2.shutdown();
    }
}
Also used : RecordedRequest(com.google.mockwebserver.RecordedRequest) MockResponse(com.google.mockwebserver.MockResponse) MockWebServer(com.google.mockwebserver.MockWebServer) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 18 with MockWebServer

use of com.google.mockwebserver.MockWebServer in project android_frameworks_base by crdroidandroid.

the class DownloadManagerBaseTest method setUp.

/**
     * {@inheritDoc}
     */
@Override
public void setUp() throws Exception {
    mContext = getInstrumentation().getContext();
    mDownloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    mServer = new MockWebServer();
    mServer.play();
    mReceiver = registerNewMultipleDownloadsReceiver();
// Note: callers overriding this should call mServer.play() with the desired port #
}
Also used : MockWebServer(com.google.mockwebserver.MockWebServer)

Example 19 with MockWebServer

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

the class NettyClientTest method testLoadBalancingWithTwoServers.

@Test
public void testLoadBalancingWithTwoServers() throws Exception {
    MockWebServer server = new MockWebServer();
    String content = "{\"name\": \"ribbon\", \"age\": 2}";
    server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "application/json").setBody(content));
    server.play();
    IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues();
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createPost("/testAsync/person").withContent(SerializationUtils.serializeToBytes(JacksonCodec.getInstance(), EmbeddedResources.defaultPerson, null)).withHeader("Content-type", "application/json");
    NettyHttpLoadBalancerErrorHandler errorHandler = new NettyHttpLoadBalancerErrorHandler(1, 3, true);
    BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule());
    LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, errorHandler);
    HttpClientListener externalListener = HttpClientListener.newHttpListener("external");
    lbObservables.subscribe(externalListener);
    Server server1 = new Server("localhost:" + server.getPort());
    Server server2 = new Server("localhost:" + port);
    lb.setServersList(Lists.newArrayList(server1, server2));
    RetryHandler handler = new RequestSpecificRetryHandler(true, true, errorHandler, null) {

        @Override
        public boolean isRetriableException(Throwable e, boolean sameServer) {
            return true;
        }
    };
    Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request, handler, null));
    ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>();
    observableWithRetries.subscribe(observer);
    observer.await();
    if (observer.error != null) {
        observer.error.printStackTrace();
    }
    assertEquals("ribbon", observer.obj.name);
    assertEquals(EmbeddedResources.defaultPerson.age, observer.obj.age);
    observer = new ObserverWithLatch<Person>();
    observableWithRetries = getPersonObservable(lbObservables.submit(request, handler, null));
    observableWithRetries.subscribe(observer);
    observer.await();
    if (observer.error != null) {
        observer.error.printStackTrace();
    }
    assertEquals("ribbon", observer.obj.name);
    assertEquals(2, observer.obj.age);
    ServerStats stats = lbObservables.getServerStats(server1);
    server.shutdown();
    // assertEquals(1, stats.getTotalRequestsCount());
    assertEquals(0, stats.getActiveRequestsCount());
    stats = lbObservables.getServerStats(server2);
    // two requests to bad server because retry same server is set to 1
    assertEquals(1, stats.getTotalRequestsCount());
    assertEquals(0, stats.getActiveRequestsCount());
    assertEquals(0, stats.getSuccessiveConnectionFailureCount());
    final HttpClientListener listener = lbObservables.getListener();
    assertEquals(2, listener.getPoolAcquires());
    waitUntilTrueOrTimeout(1000, new Func0<Boolean>() {

        @Override
        public Boolean call() {
            return listener.getPoolReleases() == 2;
        }
    });
    assertEquals(2, listener.getConnectionCount());
    assertEquals(0, listener.getPoolReuse());
    assertEquals(2, externalListener.getPoolAcquires());
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) HttpServer(com.sun.net.httpserver.HttpServer) Server(com.netflix.loadbalancer.Server) MockWebServer(com.google.mockwebserver.MockWebServer) RequestSpecificRetryHandler(com.netflix.client.RequestSpecificRetryHandler) BaseLoadBalancer(com.netflix.loadbalancer.BaseLoadBalancer) ByteBuf(io.netty.buffer.ByteBuf) HttpClientListener(io.reactivex.netty.servo.http.HttpClientListener) ServerStats(com.netflix.loadbalancer.ServerStats) RequestSpecificRetryHandler(com.netflix.client.RequestSpecificRetryHandler) RetryHandler(com.netflix.client.RetryHandler) DummyPing(com.netflix.loadbalancer.DummyPing) MockWebServer(com.google.mockwebserver.MockWebServer) IClientConfig(com.netflix.client.config.IClientConfig) AvailabilityFilteringRule(com.netflix.loadbalancer.AvailabilityFilteringRule) Person(com.netflix.ribbon.test.resources.EmbeddedResources.Person) Test(org.junit.Test)

Example 20 with MockWebServer

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

the class RibbonTest method testCacheMiss.

@Test
public void testCacheMiss() throws IOException, InterruptedException {
    MockWebServer server = new MockWebServer();
    String content = "Hello world";
    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(1));
    final String cacheKey = "somekey";
    HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test").withCacheProvider(cacheKey, new CacheProvider<ByteBuf>() {

        @Override
        public Observable<ByteBuf> get(String key, Map<String, Object> vars) {
            return Observable.error(new Exception("Cache miss again"));
        }
    }).withMethod("GET").withUriTemplate("/").build();
    RibbonRequest<ByteBuf> request = template.requestBuilder().build();
    String result = toStringBlocking(request);
    assertEquals(content, result);
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) MockWebServer(com.google.mockwebserver.MockWebServer) HttpResourceGroup(com.netflix.ribbon.http.HttpResourceGroup) ByteBuf(io.netty.buffer.ByteBuf) Map(java.util.Map) HystrixBadRequestException(com.netflix.hystrix.exception.HystrixBadRequestException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Test(org.junit.Test)

Aggregations

MockWebServer (com.google.mockwebserver.MockWebServer)56 MockResponse (com.google.mockwebserver.MockResponse)39 CookieManager (java.net.CookieManager)15 RecordedRequest (com.google.mockwebserver.RecordedRequest)14 Test (org.junit.Test)14 ByteBuf (io.netty.buffer.ByteBuf)13 HttpCookie (java.net.HttpCookie)11 BaseLoadBalancer (com.netflix.loadbalancer.BaseLoadBalancer)7 Server (com.netflix.loadbalancer.Server)7 IClientConfig (com.netflix.client.config.IClientConfig)6 AvailabilityFilteringRule (com.netflix.loadbalancer.AvailabilityFilteringRule)6 DummyPing (com.netflix.loadbalancer.DummyPing)6 HttpResourceGroup (com.netflix.ribbon.http.HttpResourceGroup)6 IOException (java.io.IOException)6 HttpHost (org.apache.http.HttpHost)6 HttpResponse (org.apache.http.HttpResponse)6 HttpClient (org.apache.http.client.HttpClient)6 HttpGet (org.apache.http.client.methods.HttpGet)6 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)6 Map (java.util.Map)5