okhttp3.mockwebserver.SocketPolicy Java Examples
The following examples show how to use
okhttp3.mockwebserver.SocketPolicy.
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: RibbonClientTest.java From feign with Apache License 2.0 | 6 votes |
@Test public void ribbonRetryConfigurationOnMultipleServers() throws IOException, InterruptedException { server1.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server1.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server2.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server2.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); getConfigInstance().setProperty(serverListKey(), hostAndPort(server1.url("").url()) + "," + hostAndPort(server2.url("").url())); getConfigInstance().setProperty(client() + ".ribbon.MaxAutoRetriesNextServer", 1); TestInterface api = Feign.builder().client(RibbonClient.create()).retryer(Retryer.NEVER_RETRY) .target(TestInterface.class, "http://" + client()); try { api.post(); fail("No exception thrown"); } catch (RetryableException ignored) { } assertThat(server1.getRequestCount()).isGreaterThanOrEqualTo(1); assertThat(server1.getRequestCount()).isGreaterThanOrEqualTo(1); // TODO: verify ribbon stats match // assertEquals(target.lb().getLoadBalancerStats().getSingleServerStat()) }
Example #2
Source File: SimpleRequestTest.java From jus with Apache License 2.0 | 6 votes |
@Test public void transportProblemSync() { server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); Request<String> call = example.getString().setRetryPolicy(new DefaultRetryPolicy(1,0,1)).enqueue(); try { call.getFuture().get(); fail(); } catch (Exception ignored) { // Throwable failure = ignored.getCause(); // assertThat(failure).isInstanceOf(NoConnectionError.class); // assertThat(failure.getCause()).isInstanceOf(ConnectException.class); // assertThat(failure.getCause().getMessage()).isEqualTo("Connection refused"); Response<String> response = call.getRawResponse(); assertThat(response.isSuccess()).isFalse(); assertThat(response.result).isNull(); assertThat(response.error).isNotNull(); // assertThat(response.error).isInstanceOf(NoConnectionError.class); // assertThat(response.error.getCause()).isInstanceOf(ConnectException.class); // assertThat(failure.getCause().getMessage()).isEqualTo("Connection refused"); } }
Example #3
Source File: DesignDocumentsTest.java From java-cloudant with Apache License 2.0 | 6 votes |
/** * Test that a CouchDbException is thrown if an IOException is encountered when trying to get * revision information for a design document removal. * * @throws Exception */ @Test public void couchDbExceptionIfIOExceptionDuringDDocRemove() throws Exception { assertThrows(CouchDbException.class, new Executable() { @Override public void execute() throws Throwable { CloudantClient mockClient = CloudantClientHelper.newMockWebServerClientBuilder (mockWebServer).readTimeout(50, TimeUnit.MILLISECONDS).build(); // Cause a read timeout to generate an IOException mockWebServer.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)); Database database = mockClient.database(dbResource.getDatabaseName(), false); // Try to remove a design document by id only, generates a HEAD request for // revision info database.getDesignDocumentManager().remove("example"); } }); }
Example #4
Source File: CloudantClientTests.java From java-cloudant with Apache License 2.0 | 6 votes |
/** * Checks that the read timeout works. The test sets a read timeout of 0.25 s and the mock * server thread never sends a response. If things are working * correctly then the client should see a SocketTimeoutException for the read. */ @Test public void readTimeout() throws Throwable { assertThrows(SocketTimeoutException.class, new Executable() { @Override public void execute() throws Throwable { // Don't respond so the read will timeout server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)); try { CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(server) .readTimeout(25, TimeUnit.MILLISECONDS).build(); //do a call that expects a response c.getAllDbs(); } catch (CouchDbException e) { //unwrap the CouchDbException if (e.getCause() != null) { throw e.getCause(); } else { throw e; } } } }); }
Example #5
Source File: SimpleRequestTest.java From jus with Apache License 2.0 | 6 votes |
@Test public void responseBodyBuffers() throws IOException, InterruptedException { server.enqueue(new MockResponse() .setBody("1234") .setSocketPolicy(SocketPolicy.DISCONNECT_DURING_RESPONSE_BODY)); Request<NetworkResponse> buffered = example.getBody(); // When buffering we will detect all socket problems before returning the Response. try { buffered.enqueue().getFuture().get(); fail(); } catch (ExecutionException e) { //we have a protocol error from OkHttp as we read the whole body when we got it assertThat(e.getCause()).hasMessage("Response Body not completely received"); assertThat(buffered.getRawResponse().error.networkResponse).isNotNull(); } }
Example #6
Source File: RibbonClientTest.java From feign with Apache License 2.0 | 6 votes |
@Test public void ioExceptionRetry() throws IOException, InterruptedException { server1.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server1.enqueue(new MockResponse().setBody("success!")); getConfigInstance().setProperty(serverListKey(), hostAndPort(server1.url("").url())); TestInterface api = Feign.builder().client(RibbonClient.create()) .target(TestInterface.class, "http://" + client()); api.post(); assertEquals(2, server1.getRequestCount()); // TODO: verify ribbon stats match // assertEquals(target.lb().getLoadBalancerStats().getSingleServerStat()) }
Example #7
Source File: RibbonClientTest.java From feign with Apache License 2.0 | 6 votes |
@Test public void ioExceptionFailsAfterTooManyFailures() throws IOException, InterruptedException { server1.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); getConfigInstance().setProperty(serverListKey(), hostAndPort(server1.url("").url())); TestInterface api = Feign.builder().client(RibbonClient.create()).retryer(Retryer.NEVER_RETRY) .target(TestInterface.class, "http://" + client()); try { api.post(); fail("No exception thrown"); } catch (RetryableException ignored) { } // TODO: why are these retrying? assertThat(server1.getRequestCount()).isGreaterThanOrEqualTo(1); // TODO: verify ribbon stats match // assertEquals(target.lb().getLoadBalancerStats().getSingleServerStat()) }
Example #8
Source File: TraceRestTemplateInterceptorIntegrationTests.java From spring-cloud-sleuth with Apache License 2.0 | 6 votes |
@Test public void spanRemovedFromThreadUponException() throws IOException { this.mockWebServer.enqueue( new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); Span span = this.tracer.nextSpan().name("new trace"); try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span.start())) { this.template.getForEntity( "http://localhost:" + this.mockWebServer.getPort() + "/exception", Map.class).getBody(); fail("should throw an exception"); } catch (RuntimeException e) { BDDAssertions.then(e).hasRootCauseInstanceOf(IOException.class); } finally { span.finish(); } // 1 span "new race", 1 span "rest template" BDDAssertions.then(this.spans).hasSize(2); MutableSpan span1 = this.spans.get(0); BDDAssertions.then(span1.error()).hasMessage("Read timed out"); BDDAssertions.then(span1.kind()).isEqualTo(Span.Kind.CLIENT); }
Example #9
Source File: RibbonClientTest.java From feign with Apache License 2.0 | 6 votes |
@Test public void ribbonRetryConfigurationOnSameServer() throws IOException, InterruptedException { server1.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server1.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server2.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server2.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); getConfigInstance().setProperty(serverListKey(), hostAndPort(server1.url("").url()) + "," + hostAndPort(server2.url("").url())); getConfigInstance().setProperty(client() + ".ribbon.MaxAutoRetries", 1); TestInterface api = Feign.builder().client(RibbonClient.create()).retryer(Retryer.NEVER_RETRY) .target(TestInterface.class, "http://" + client()); try { api.post(); fail("No exception thrown"); } catch (RetryableException ignored) { } assertTrue(server1.getRequestCount() >= 2 || server2.getRequestCount() >= 2); assertThat(server1.getRequestCount() + server2.getRequestCount()).isGreaterThanOrEqualTo(2); // TODO: verify ribbon stats match // assertEquals(target.lb().getLoadBalancerStats().getSingleServerStat()) }
Example #10
Source File: RibbonClientTest.java From feign with Apache License 2.0 | 6 votes |
@Test public void ioExceptionRetryWithBuilder() throws IOException, InterruptedException { server1.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server1.enqueue(new MockResponse().setBody("success!")); getConfigInstance().setProperty(serverListKey(), hostAndPort(server1.url("").url())); TestInterface api = Feign.builder().client(RibbonClient.create()) .target(TestInterface.class, "http://" + client()); api.post(); assertEquals(server1.getRequestCount(), 2); // TODO: verify ribbon stats match // assertEquals(target.lb().getLoadBalancerStats().getSingleServerStat()) }
Example #11
Source File: CachedCallTest.java From retrocache with Apache License 2.0 | 6 votes |
@Test public void transportProblemSync() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(mServer.url("/")) .addConverterFactory(new ToStringConverterFactory()) .addCallAdapterFactory(buildSmartCacheFactory()) .build(); Service example = retrofit.create(Service.class); mServer.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); Cached<String> call = example.getString(); try { call.execute(); fail(); } catch (IOException ignored) { } }
Example #12
Source File: BasePeriodicTimeoutDispatcher.java From adamant-android with GNU General Public License v3.0 | 6 votes |
@Override protected MockResponse route(String path, RecordedRequest request) { AtomicInteger counter = counters.get(path); if (counter == null) { return new MockResponse().setResponseCode(500); } int cntVal = counter.get(); if (cntVal < provideAttempts()) { Logger.getGlobal().warning("PeriodicTimeoutDispatcher: " + (provideAttempts() - cntVal) + " Attempts for path: " + path); counter.incrementAndGet(); return new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE); } return new MockResponse() .setResponseCode(200) .setBody(AssetReaderUtil.asset(context, data.get(path))); }
Example #13
Source File: NetworkDiscoveryTest.java From orion with Apache License 2.0 | 6 votes |
@Test void networkDiscoveryWithUnresponsivePeer() throws Exception { // add peers final FakePeer fakePeer = new FakePeer(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE), Box.KeyPair.random().publicKey()); networkNodes.addNode(Collections.singletonMap(fakePeer.publicKey.bytes(), fakePeer.getURI()).entrySet()); // start network discovery final NetworkDiscovery networkDiscovery = new NetworkDiscovery(networkNodes, config, 50, 10); deployVerticle(networkDiscovery).join(); // assert the discoverer started assertEquals(1, networkDiscovery.discoverers().size()); // ensure the discoverer match our peer URL final NetworkDiscovery.Discoverer discoverer = networkDiscovery.discoverers().get(fakePeer.getURI()); assertNotNull(discoverer); Thread.sleep(3 * (discoverer.currentRefreshDelay + 1000)); // ensure we didn't do any update, and we tried at least 2 times assertEquals(Instant.MIN, discoverer.lastUpdate); assertTrue(discoverer.attempts >= 2, "Tried " + discoverer.attempts + " times"); }
Example #14
Source File: NetworkDiscoveryTest.java From orion with Apache License 2.0 | 6 votes |
@Test void networkDiscoveryWithPeersOverTime() throws Exception { Config config = Config.load("tls=\"off\"\nothernodes=[\"http://127.1.1.1:8080/\",\"http://192.168.1.2:8080/\"]"); // add peers final FakePeer fakePeer = new FakePeer(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE), Box.KeyPair.random().publicKey()); final FakePeer fakePeer2 = new FakePeer(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE), Box.KeyPair.random().publicKey()); networkNodes.addNode(Collections.singletonMap(fakePeer.publicKey.bytes(), fakePeer.getURI()).entrySet()); networkNodes.addNode(Collections.singletonMap(fakePeer2.publicKey.bytes(), fakePeer2.getURI()).entrySet()); networkNodes.addNode(Collections.singletonMap(fakePeer2.publicKey.bytes(), fakePeer.getURI()).entrySet()); // start network discovery final NetworkDiscovery networkDiscovery = new NetworkDiscovery(networkNodes, config); assertEquals(0, networkDiscovery.discoverers().size()); deployVerticle(networkDiscovery).join(); assertEquals(4, networkDiscovery.discoverers().size()); Thread.sleep(10 * (networkDiscovery.discoverers().values().iterator().next().currentRefreshDelay + 1000)); assertEquals(4, networkDiscovery.discoverers().size()); for (NetworkDiscovery.Discoverer discoverer : networkDiscovery.discoverers().values()) { assertTrue(discoverer.attempts >= 3); } }
Example #15
Source File: GraphQLTemplateTest.java From nodes with Apache License 2.0 | 6 votes |
@Test public void timeOutVariables() throws MalformedURLException { graphQLTemplate = new GraphQLTemplate(2000, 2000); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)); HttpUrl serviceUrl = server.url("/serverTimeout"); GraphQLRequestEntity requestEntity = GraphQLRequestEntity.Builder() .url(serviceUrl.toString()) .request(TestModel.class) .build(); GraphQLException exception = null; try { graphQLTemplate.query(requestEntity, TestModel.class); } catch (GraphQLException e) { exception = e; } assertNotNull(exception); assertEquals(exception.getDescription(), "Read timed out"); }
Example #16
Source File: ITHttpClient.java From brave with Apache License 2.0 | 5 votes |
MutableSpan checkReportsSpanOnTransportException(Callable<Void> get) { server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); try { get.call(); } catch (Exception e) { // ok, but the span should include an error! } // We don't know the transport exception return testSpanHandler.takeRemoteSpanWithError(CLIENT); }
Example #17
Source File: FeignUnderAsyncTest.java From feign with Apache License 2.0 | 5 votes |
@Test public void retriesLostConnectionBeforeRead() throws Exception { server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server.enqueue(new MockResponse().setBody("success!")); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); api.post(); assertEquals(2, server.getRequestCount()); }
Example #18
Source File: DefaultClientTest.java From feign with Apache License 2.0 | 5 votes |
@Test public void retriesFailedHandshake() throws IOException, InterruptedException { server.useHttps(TrustingSSLSocketFactory.get("localhost"), false); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)); server.enqueue(new MockResponse()); TestInterface api = newBuilder() .target(TestInterface.class, "https://localhost:" + server.getPort()); api.post("foo"); assertEquals(2, server.getRequestCount()); }
Example #19
Source File: FeignTest.java From feign with Apache License 2.0 | 5 votes |
@Test public void retriesLostConnectionBeforeRead() throws Exception { server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server.enqueue(new MockResponse().setBody("success!")); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); api.post(); assertEquals(2, server.getRequestCount()); }
Example #20
Source File: SimpleRequestTest.java From jus with Apache License 2.0 | 5 votes |
@Test public void cancelRequest() throws InterruptedException { server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)); Request<String> call = example.getString(); final AtomicReference<Marker> markerRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); call .addErrorListener(new RequestListener.ErrorListener() { @Override public void onError(JusError error) { throw new AssertionError(); } }) .addResponseListener(new RequestListener.ResponseListener<String>() { @Override public void onResponse(String response) { throw new AssertionError(); } }) .addMarkerListener(new RequestListener.MarkerListener() { @Override public void onMarker(Marker marker, Object... args) { if (Request.EVENT_CACHE_DISCARD_CANCELED.equals(marker.name) || Request.EVENT_NETWORK_DISCARD_CANCELED.equals(marker.name) || Request.EVENT_CANCELED_AT_DELIVERY.equals(marker.name)) { markerRef.set(marker); latch.countDown(); } } }); call.enqueue().cancel(); assertTrue(latch.await(2, SECONDS)); assertThat(markerRef.get().name).containsIgnoringCase("canceled"); }
Example #21
Source File: KubernetesCrudDispatcher.java From kubernetes-client with Apache License 2.0 | 5 votes |
/** * Watch the resource list on `path` endpoint * * @param path String * @return The {@link MockResponse} */ public MockResponse handleWatch(String path) { MockResponse mockResponse = new MockResponse(); String resourceName = fetchResourceNameFromWatchRequestPath(path); AttributeSet query = attributeExtractor.fromPath(path); if (resourceName != null) { query = query.add(new Attribute("name", resourceName)); } WatchEventsListener watchEventListener = new WatchEventsListener(context, query, watchEventListeners, LOGGER); watchEventListeners.add(watchEventListener); mockResponse.setSocketPolicy(SocketPolicy.KEEP_OPEN); return mockResponse.withWebSocketUpgrade(watchEventListener); }
Example #22
Source File: MockWebServerPlusTest.java From mockwebserverplus with Apache License 2.0 | 5 votes |
@Test public void enqueueSocketPolicy() throws IOException { server.enqueue(SocketPolicy.KEEP_OPEN); QueueDispatcher dispatcher = new QueueDispatcher(); server.setDispatcher(dispatcher); MockResponse mockResponse = dispatcher.peek(); assertThat(mockResponse.getSocketPolicy()).isEqualTo(SocketPolicy.KEEP_OPEN); }
Example #23
Source File: KinesisSenderTest.java From zipkin-aws with Apache License 2.0 | 5 votes |
@Test public void checkFailsWithException() { server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_DURING_REQUEST_BODY)); // 3 retries after initial failure server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_DURING_REQUEST_BODY)); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_DURING_REQUEST_BODY)); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_DURING_REQUEST_BODY)); CheckResult result = sender.check(); assertThat(result.ok()).isFalse(); assertThat(result.error()).isInstanceOf(SdkClientException.class); }
Example #24
Source File: MatcherDispatcher.java From requestmatcher with Apache License 2.0 | 5 votes |
@Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { final int currentOrder = order.incrementAndGet(); int matcherOrder = 0; final NoMatchersForRequestException.Builder builder = new NoMatchersForRequestException.Builder(request); for (ResponseWithMatcher response : responseSet) { final RequestMatchersGroup matcher = response.getMatcher(); if (matcher != null) { try { matcher.doAssert(request, currentOrder); responseSet.remove(response); return response.getResponse(); // return proper response } catch (AssertionError assertionError) { builder.appendAssertionError(++matcherOrder, assertionError, matcher); // continue } catch (Exception e) { this.assertionError = new RequestAssertionException(DEFAULT_MESSAGE, e); logger.log(Level.SEVERE, "Error while doing assert", e); return response.getResponse(); // return response but keep exception } } } // noinspection ThrowableInstanceNeverThrown this.assertionError = new RequestAssertionException(DEFAULT_MESSAGE, builder.build()); return new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_END); }
Example #25
Source File: HttpClientTracingHandlerIntegrationTest.java From xio with Apache License 2.0 | 4 votes |
private MockResponse buildResponse() { return new MockResponse().setBody(expectedResponse).setSocketPolicy(SocketPolicy.KEEP_OPEN); }
Example #26
Source File: ClientChannelInitializerTest.java From xio with Apache License 2.0 | 4 votes |
private MockResponse buildResponse() { return new MockResponse().setBody("hello, world").setSocketPolicy(SocketPolicy.KEEP_OPEN); }
Example #27
Source File: EdgeProxyFunctionalTest.java From xio with Apache License 2.0 | 4 votes |
private MockResponse buildResponse() { return new MockResponse().setBody("hello, world").setSocketPolicy(SocketPolicy.KEEP_OPEN); }
Example #28
Source File: OkHttpSenderTest.java From zipkin-reporter-java with Apache License 2.0 | 4 votes |
@Test public void check_fail() throws Exception { server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); assertThat(sender.check().ok()).isFalse(); }
Example #29
Source File: URLConnectionSenderTest.java From zipkin-reporter-java with Apache License 2.0 | 4 votes |
@Test public void check_fail() throws Exception { server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); assertThat(sender.check().ok()).isFalse(); }
Example #30
Source File: MockWebServerPlus.java From mockwebserverplus with Apache License 2.0 | 4 votes |
/** * Given policy will be enqueued as MockResponse */ public MockResponse enqueue(SocketPolicy socketPolicy) { MockResponse mockResponse = new MockResponse().setSocketPolicy(socketPolicy); mockWebServer.enqueue(mockResponse); return mockResponse; }