com.google.mockwebserver.MockWebServer Java Examples

The following examples show how to use com.google.mockwebserver.MockWebServer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FollowRedirectTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
    redirectedServer = new MockWebServer();
    redirectedServer.enqueue(new MockResponse()
        .setResponseCode(200)
        .setHeader("Content-type", "text/plain")
        .setBody("OK"));       
    redirectingServer = new MockWebServer(); 
    redirectedServer.play();
    redirectingServer.enqueue(new MockResponse()
        .setResponseCode(302)
        .setHeader("Location", "http://localhost:" + redirectedServer.getPort()));
    redirectingServer.play();
}
 
Example #2
Source File: ListenerTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #3
Source File: ServerListRefreshTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
/**
 * This test ensures that when server list is refreshed in the load balancer, the set of servers
 * which equals to (oldList - newList) should be removed from the map of cached RxClient. Any server
 * that is not part of oldList should stay in the map.
 *
 * @throws IOException
 */
@Test
public void testServerListRefresh() throws IOException {
    String content = "Hello world";
    MockWebServer server1 = new MockWebServer();
    MockWebServer server2 = new MockWebServer();
    MockWebServer server3 = new MockWebServer();
    MockResponse mockResponse = new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain")
            .setBody(content);
    server1.enqueue(mockResponse);
    server2.enqueue(mockResponse);
    server3.enqueue(mockResponse);
    server1.play();
    server2.play();
    server3.play();
    try {
        BaseLoadBalancer lb = new BaseLoadBalancer();
        List<Server> initialList = Lists.newArrayList(new Server("localhost", server1.getPort()), new Server("localhost", server2.getPort()));
        lb.setServersList(initialList);
        LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb);
        HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/");
        client.submit(request).toBlocking().last();
        client.submit(request).toBlocking().last();
        HttpClientRequest<ByteBuf> request2 = HttpClientRequest.createGet("http://localhost:" + server3.getPort());
        client.submit(request2).toBlocking().last();
        Set<Server> cachedServers = client.getRxClients().keySet();
        assertEquals(Sets.newHashSet(new Server("localhost", server1.getPort()), new Server("localhost", server2.getPort()), new Server("localhost", server3.getPort())), cachedServers);
        List<Server> newList = Lists.newArrayList(new Server("localhost", server1.getPort()), new Server("localhost", 99999));
        lb.setServersList(newList);
        cachedServers = client.getRxClients().keySet();
        assertEquals(Sets.newHashSet(new Server("localhost", server1.getPort()), new Server("localhost", server3.getPort())), cachedServers);
    } finally {
        server1.shutdown();
        server2.shutdown();
        server3.shutdown();
    }
}
 
Example #4
Source File: RibbonTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #5
Source File: RibbonTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testHystrixCache() throws IOException {
    // LogManager.getRootLogger().setLevel((Level)Level.DEBUG);
    MockWebServer server = new MockWebServer();
    String content = "Hello world";
    MockResponse response = new MockResponse()
        .setResponseCode(200)
        .setHeader("Content-type", "text/plain")
        .setBody(content);
    server.enqueue(response);
    
    server.enqueue(response);       
    server.play();
    
    HttpResourceGroup group = Ribbon.createHttpResourceGroupBuilder("myclient").build();
    HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class)
            .withUriTemplate("http://localhost:" + server.getPort())
            .withMethod("GET")
            .withRequestCacheKey("xyz")
            .build();
    RibbonRequest<ByteBuf> request = template
            .requestBuilder().build();
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    try {
        RibbonResponse<ByteBuf> ribbonResponse = request.withMetadata().execute();
        assertFalse(ribbonResponse.getHystrixInfo().isResponseFromCache());
        ribbonResponse = request.withMetadata().execute();
        assertTrue(ribbonResponse.getHystrixInfo().isResponseFromCache());
    } finally {
        context.shutdown();
    }
}
 
Example #6
Source File: RibbonTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testCommand() throws IOException, InterruptedException, ExecutionException {
    MockWebServer server = new MockWebServer();
    String content = "Hello world";
    MockResponse response = new MockResponse()
        .setResponseCode(200)
        .setHeader("Content-type", "text/plain")
        .setBody(content);
    
    server.enqueue(response);        
    server.enqueue(response);       
    server.enqueue(response);       
    server.play();
    
    HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient",
            ClientOptions.create()
            .withMaxAutoRetriesNextServer(3)
            .withReadTimeout(300000)
            .withConfigurationBasedServerList("localhost:12345, localhost:10092, localhost:" + server.getPort()));
    HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class)
            .withUriTemplate("/")
            .withMethod("GET")
            .build();
    
    RibbonRequest<ByteBuf> request = template.requestBuilder().build();
    
    String result = request.execute().toString(Charset.defaultCharset());
    assertEquals(content, result);
    // repeat the same request
    ByteBuf raw = request.execute();
    result = raw.toString(Charset.defaultCharset());
    raw.release();
    assertEquals(content, result);
    
    result = request.queue().get().toString(Charset.defaultCharset());
    assertEquals(content, result);
}
 
Example #7
Source File: DiscoveryEnabledServerListTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void init() throws IOException {
    server = new MockWebServer();
    String content = "Hello world";
    MockResponse response = new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain")
            .setBody(content);
    server.enqueue(response);
    server.play();
}
 
Example #8
Source File: ManyShortLivedRequestsSurvivorTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void survive() throws IOException, ClientException, URISyntaxException, InterruptedException {

    String clientName = "RibbonClientTest-loadBalancingDefaultPolicyRoundRobin";
    String serverListKey = clientName + ".ribbon.listOfServers";
    int nbHitsPerServer = 60;
    MockWebServer server1 = new MockWebServer();
    MockWebServer server2 = new MockWebServer();

    for (int i = 0; i < nbHitsPerServer; i++) {
        server1.enqueue(new MockResponse().setResponseCode(200).setBody("server1 success <" + i + ">!"));
        server2.enqueue(new MockResponse().setResponseCode(200).setBody("server2 success <" + i + ">!"));
    }

    server1.play();
    server2.play();

    getConfigInstance().setProperty(serverListKey, hostAndPort(server1.getUrl("")) + "," + hostAndPort(server2.getUrl("")));

    RestClient client = (RestClient) ClientFactory.getNamedClient(clientName);
    HttpRequest request;
    for (int i = 0; i < nbHitsPerServer * 2; i++) {
        request = HttpRequest.newBuilder().uri(new URI("/")).build();
        HttpResponse response = client.executeWithLoadBalancer(request);
        response.close();
    }
}
 
Example #9
Source File: AbstractCookiesTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Override public void setUp() throws Exception {
    super.setUp();
    server = new MockWebServer();
    defaultHandler = CookieHandler.getDefault();
    cookieManager = new CookieManager(createCookieStore(), null);
    cookieStore = cookieManager.getCookieStore();
}
 
Example #10
Source File: URLConnectionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testRedirectToAnotherOriginServer() throws Exception {
    MockWebServer server2 = new MockWebServer();
    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()); // JVM failure

    server2.shutdown();
}
 
Example #11
Source File: AbstractCookiesTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
private Map<String,List<String>> get(MockWebServer server, String path) throws Exception {
    URLConnection connection = server.getUrl(path).openConnection();
    Map<String, List<String>> headers = connection.getHeaderFields();
    connection.getInputStream().close();
    return headers;
}
 
Example #12
Source File: RobospiceTestCase.java    From android-atleap with Apache License 2.0 4 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    spiceManager = new SpiceManager(TestRobospiceService.class);
    mockWebServer = new MockWebServer();
}
 
Example #13
Source File: OldCookieHandlerTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();
    server = new MockWebServer();
}
 
Example #14
Source File: URLConnectionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Override public HttpURLConnection connect(MockWebServer server, URL url)
        throws IOException {
    System.setProperty("https.proxyHost", "localhost");
    System.setProperty("https.proxyPort", Integer.toString(server.getPort()));
    return (HttpURLConnection) url.openConnection();
}
 
Example #15
Source File: URLConnectionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Override public HttpURLConnection connect(MockWebServer server, URL url)
        throws IOException {
    System.setProperty("http.proxyHost", "localhost");
    System.setProperty("http.proxyPort", Integer.toString(server.getPort()));
    return (HttpURLConnection) url.openConnection();
}
 
Example #16
Source File: URLConnectionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Override public HttpURLConnection connect(MockWebServer server, URL url)
        throws IOException {
    System.setProperty("proxyHost", "localhost");
    System.setProperty("proxyPort", Integer.toString(server.getPort()));
    return (HttpURLConnection) url.openConnection();
}
 
Example #17
Source File: URLConnectionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Override public HttpURLConnection connect(MockWebServer server, URL url)
        throws IOException {
    return (HttpURLConnection) url.openConnection(server.toProxyAddress());
}
 
Example #18
Source File: URLConnectionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Override public HttpURLConnection connect(MockWebServer server, URL url)
        throws IOException {
    return (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
}
 
Example #19
Source File: NettyClientTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Test
public void testLoadBalancingObservablesWithReadTimeout() throws Exception {
    NettyHttpLoadBalancerErrorHandler errorHandler = new NettyHttpLoadBalancerErrorHandler(1, 3, true);
    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()
            .set(CommonClientConfigKey.ReadTimeout, 100);
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/readTimeout");
    
    BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule());
    LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, errorHandler);
    
    Server goodServer = new Server("localhost:" + server.getPort());
    Server badServer  = new Server("localhost:" + port);
    lb.setServersList(Lists.newArrayList(goodServer, badServer, badServer, goodServer));
    
    Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request));
    ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>();
    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(badServer);
    server.shutdown();
    
    final HttpClientListener listener = lbObservables.getListener();
    waitUntilTrueOrTimeout(1000, new Func0<Boolean>() {
        @Override
        public Boolean call() {
            return listener.getPoolReleases() == 5;
        }
    });
    assertEquals(0, listener.getPoolReuse());
    
    // two requests to bad server because retry same server is set to 1
    assertEquals(4, stats.getTotalRequestsCount());
    assertEquals(0, stats.getActiveRequestsCount());
    assertEquals(4, stats.getSuccessiveConnectionFailureCount());
    
    stats = lbObservables.getServerStats(goodServer);
    assertEquals(1, stats.getTotalRequestsCount());
    assertEquals(0, stats.getActiveRequestsCount());
    assertEquals(0, stats.getSuccessiveConnectionFailureCount());
}
 
Example #20
Source File: NettyClientTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@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());
}
 
Example #21
Source File: NettyClientTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Test
public void testLoadBalancingPostWithReadTimeout() 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()
            .set(CommonClientConfigKey.ReadTimeout, 100);
    
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createPost("/testAsync/postTimeout")
            .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);
    Server goodServer = new Server("localhost:" + server.getPort());
    Server badServer = new Server("localhost:" + port);
    List<Server> servers = Lists.newArrayList(badServer, badServer, badServer, goodServer);
    lb.setServersList(servers);
    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(2, observer.obj.age);
    ServerStats stats = lbObservables.getServerStats(badServer);
    server.shutdown();
    assertEquals(4, stats.getTotalRequestsCount());
    assertEquals(0, stats.getActiveRequestsCount());
    assertEquals(4, stats.getSuccessiveConnectionFailureCount());
    
    stats = lbObservables.getServerStats(goodServer);
    // 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());
}
 
Example #22
Source File: NettyClientTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Test
public void testLoadBalancingPostWithNoRetrySameServer() 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()
            .set(CommonClientConfigKey.ReadTimeout, 100);
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createPost("/testAsync/postTimeout")
            .withContent(SerializationUtils.serializeToBytes(JacksonCodec.getInstance(), EmbeddedResources.defaultPerson, null))
            .withHeader("Content-type", "application/json");
    NettyHttpLoadBalancerErrorHandler errorHandler = new NettyHttpLoadBalancerErrorHandler(0, 3, true);
    BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule());
    LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, errorHandler);
    Server goodServer = new Server("localhost:" + server.getPort());
    Server badServer = new Server("localhost:" + port);
    List<Server> servers = Lists.newArrayList(badServer, badServer, badServer, goodServer);
    lb.setServersList(servers);
    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();
    }
    server.shutdown();
    assertEquals("ribbon", observer.obj.name);
    assertEquals(2, observer.obj.age);
    ServerStats stats = lbObservables.getServerStats(badServer);
    assertEquals(2, stats.getTotalRequestsCount());
    assertEquals(0, stats.getActiveRequestsCount());
    assertEquals(2, stats.getSuccessiveConnectionFailureCount());
    
    stats = lbObservables.getServerStats(goodServer);
    assertEquals(1, stats.getTotalRequestsCount());
    assertEquals(0, stats.getActiveRequestsCount());
    assertEquals(0, stats.getSuccessiveConnectionFailureCount());
}
 
Example #23
Source File: ListenerTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Test
public void testSuccessExecution() 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);

    System.out.println(config);

    HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/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.newBuilder()
            .withRule(new AvailabilityFilteringRule())
            .withPing(new DummyPing())
            .buildFixedServerListLoadBalancer(servers);

    IClientConfig overrideConfig = DefaultClientConfigImpl
            .getEmptyConfig()
            .set(CommonClientConfigKey.ConnectTimeout, 500);

    TestExecutionListener<ByteBuf, ByteBuf> listener = new TestExecutionListener<>(request, overrideConfig);
    List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.newArrayList(listener);
    LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners);
    HttpClientResponse<ByteBuf> response = client.submit(request, null, overrideConfig).toBlocking().last();

    System.out.println(listener);

    assertEquals(200, response.getStatus().code());
    assertEquals(1, listener.executionStartCounter.get());
    assertEquals(3, listener.startWithServerCounter.get());
    assertEquals(2, 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());
}
 
Example #24
Source File: URLConnectionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Override protected void setUp() throws Exception {
    super.setUp();
    savedUrlCache = setNewUrlCache();
    server = new MockWebServer();
    hostName = server.getHostName();
}
 
Example #25
Source File: URLConnectionTest.java    From j2objc with Apache License 2.0 votes vote down vote up
public abstract HttpURLConnection connect(MockWebServer server, URL url) throws IOException;