private void expectRequestCount(int count) { assertEquals(count, this.server.getRequestCount()); }
@Test public void getWhenMultipleRequestThenCached() { when(this.matcher.matches(any())).thenReturn(true); this.source.get(this.selector).block(); this.source.get(this.selector).block(); assertThat(this.server.getRequestCount()).isEqualTo(1); }
@Test public void get_jar_from_cache_if_present() throws Exception { FileAndMd5 jar = createFileInCache("foo"); File result = underTest.get(newInstalledPlugin("foo", jar.md5)).get(); verifySameContent(result, jar); // no requests to server assertThat(server.getRequestCount()).isEqualTo(0); }
@Test public void testGetServerInfo() throws Exception { ServerInfo expected = new ServerInfo(UNKNOWN, "test", true, false, Optional.of(Duration.valueOf("2m"))); server.enqueue(new MockResponse() .addHeader(CONTENT_TYPE, "application/json") .setBody(SERVER_INFO_CODEC.toJson(expected))); QueryExecutor executor = new QueryExecutor(new OkHttpClient()); ServerInfo actual = executor.getServerInfo(server.url("/v1/info").uri()); assertEquals(actual.getEnvironment(), "test"); assertEquals(actual.getUptime(), Optional.of(Duration.valueOf("2m"))); assertEquals(server.getRequestCount(), 1); assertEquals(server.takeRequest().getPath(), "/v1/info"); } }
@Test public void download_and_add_jar_to_cache_if_missing() throws Exception { FileAndMd5 tempJar = new FileAndMd5(); enqueueDownload(tempJar); InstalledPlugin plugin = newInstalledPlugin("foo", tempJar.md5); File result = underTest.get(plugin).get(); verifySameContent(result, tempJar); HttpUrl requestedUrl = server.takeRequest().getRequestUrl(); assertThat(requestedUrl.encodedPath()).isEqualTo("/api/plugins/download"); assertThat(requestedUrl.encodedQuery()).isEqualTo("plugin=foo&acceptCompressions=pack200"); // get from cache on second call result = underTest.get(plugin).get(); verifySameContent(result, tempJar); assertThat(server.getRequestCount()).isEqualTo(1); }
@Test public void download_a_new_version_of_plugin_during_blue_green_switch() throws IOException { FileAndMd5 tempJar = new FileAndMd5(); enqueueDownload(tempJar); // expecting to download plugin foo with checksum "abc" InstalledPlugin pluginV1 = newInstalledPlugin("foo", "abc"); File result = underTest.get(pluginV1).get(); verifySameContent(result, tempJar); // new version of downloaded jar is put in cache with the new md5 InstalledPlugin pluginV2 = newInstalledPlugin("foo", tempJar.md5); result = underTest.get(pluginV2).get(); verifySameContent(result, tempJar); assertThat(server.getRequestCount()).isEqualTo(1); // v1 still requests server and downloads v2 enqueueDownload(tempJar); result = underTest.get(pluginV1).get(); verifySameContent(result, tempJar); assertThat(server.getRequestCount()).isEqualTo(2); }
@Test public void download_compressed_and_add_uncompressed_to_cache_if_missing() throws Exception { FileAndMd5 jar = new FileAndMd5(); enqueueCompressedDownload(jar, true); InstalledPlugin plugin = newInstalledPlugin("foo", jar.md5); File result = underTest.get(plugin).get(); verifySameContentAfterCompression(jar.file, result); RecordedRequest recordedRequest = server.takeRequest(); assertThat(recordedRequest.getRequestUrl().queryParameter("acceptCompressions")).isEqualTo("pack200"); // get from cache on second call result = underTest.get(plugin).get(); verifySameContentAfterCompression(jar.file, result); assertThat(server.getRequestCount()).isEqualTo(1); }
@Test // SPR-17482 public void bodyToMonoVoidWithoutContentType() { this.server.enqueue(new MockResponse() .setResponseCode(HttpStatus.ACCEPTED.value()) .setChunkedBody("{\"foo\" : \"123\", \"baz\" : \"456\", \"baz\" : \"456\"}", 5)); Mono<Map<String, String>> mono = this.webClient.get() .uri("/sample").accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(new ParameterizedTypeReference<Map<String, String>>() {}); StepVerifier.create(mono).expectError(UnsupportedMediaTypeException.class).verify(Duration.ofSeconds(3)); assertEquals(1, this.server.getRequestCount()); }
@Test public void bodyToMonoVoid() { this.server.enqueue(new MockResponse() .setResponseCode(201) .setHeader("Content-Type", "application/json") .setChunkedBody("{\"foo\" : {\"bar\" : \"123\", \"baz\" : \"456\"}}", 5)); Mono<Void> mono = this.webClient.get() .uri("/json").accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(Void.class); StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3)); assertEquals(1, this.server.getRequestCount()); }
private void testOnStatus(Throwable expected, Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) { HttpStatus errorStatus = HttpStatus.BAD_GATEWAY; this.server.enqueue(new MockResponse() .setResponseCode(errorStatus.value()) .setHeader("Content-Type", "application/json") .setChunkedBody("{\"error\" : {\"status\" : 502, \"message\" : \"Bad gateway.\"}}", 5)); Mono<String> mono = this.webClient.get() .uri("/json").accept(MediaType.APPLICATION_JSON) .retrieve() .onStatus(status -> status.equals(errorStatus), exceptionFunction) .bodyToMono(String.class); StepVerifier.create(mono).expectErrorSatisfies(actual -> assertSame(expected, actual)).verify(DELAY); assertEquals(1, this.server.getRequestCount()); }
@Test public void use_proxy_authentication_wrong_crendentials() throws Exception { try (MockWebServer proxy = new MockWebServer()) { proxy.start(); underTest = HttpConnector.newBuilder() .url(serverUrl) .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy.getHostName(), proxy.getPort()))) .proxyCredentials("theProxyLogin", "wrongPassword") .build(); GetRequest request = new GetRequest("api/issues/search"); proxy.enqueue(new MockResponse().setResponseCode(407)); proxy.enqueue(new MockResponse().setResponseCode(407)); proxy.enqueue(new MockResponse().setResponseCode(407)); underTest.call(request); RecordedRequest recordedRequest = proxy.takeRequest(); assertThat(recordedRequest.getHeader("Proxy-Authorization")).isNull(); recordedRequest = proxy.takeRequest(); assertThat(recordedRequest.getHeader("Proxy-Authorization")).isEqualTo(basic("theProxyLogin", "wrongPassword")); assertThat(proxy.getRequestCount()).isEqualTo(2); } }
@Test public void testToggleIfExceptionIsAllowedToRetry() throws Exception { // Enqueue some error responses, although only the first should be used because the response's // exception is not allowed to be retried. MockResponse overQueryLimitResponse = new MockResponse(); overQueryLimitResponse.setStatus("HTTP/1.1 400 Internal server error"); overQueryLimitResponse.setBody(TestUtils.retrieveBody("OverQueryLimitResponse.json")); server.enqueue(overQueryLimitResponse); server.enqueue(overQueryLimitResponse); server.enqueue(overQueryLimitResponse); server.start(); builder.retryTimeout(1, TimeUnit.MILLISECONDS); builder.maxRetries(10); builder.setIfExceptionIsAllowedToRetry(OverQueryLimitException.class, false); setMockBaseUrl(); try { builder .build() .get(new ApiConfig("/"), GeocodingApi.Response.class, "any-key", "any-value") .await(); } catch (OverQueryLimitException e) { assertEquals(1, server.getRequestCount()); return; } fail("OverQueryLimitException was expected but not observed."); }
public static RecordedRequest[] takeN(MockWebServer server, int n) throws Exception { assertEquals(n, server.getRequestCount(), String.format(Locale.ENGLISH, "The server should have " + "%d received requests", n)); RecordedRequest[] recordedRequests = new RecordedRequest[n]; for (int i = 0; i < n; i++) { recordedRequests[i] = MockWebServerResources.takeRequestWithTimeout(server); } return recordedRequests; }
@Test public void handlesThrottle_obeysMaxNumRetriesEvenWhenRetryAfterHeaderIsGiven() throws Exception { server.enqueue(new MockResponse().setResponseCode(429).addHeader(HttpHeaders.RETRY_AFTER, "0")); server.enqueue(new MockResponse().setResponseCode(429).addHeader(HttpHeaders.RETRY_AFTER, "0")); server.enqueue(new MockResponse().setResponseCode(429).addHeader(HttpHeaders.RETRY_AFTER, "0")); Call call = createRetryingClient(2).newCall(new Request.Builder().url(url).build()); assertThatThrownBy(call::execute) .isInstanceOf(IOException.class) .hasMessage("Failed to reschedule call since the number of configured backoffs are exhausted"); assertThat(server.getRequestCount()).isEqualTo(3 /* original plus two retries */); }
@Test public void testHttp1toHttp2ServerGet() throws Exception { setupClient(1, false); setupFrontBack(false, true); get(proxyPort(), HTTP_1_1, "/foo/", "/ifoo/", backEnd1); assertEquals(1, backEnd1.getRequestCount()); assertProxiedRequests(1); }
@Test public void sanityCheckHttp1Post() throws Exception { setupClient(1, false); setupBack(false); post(backEnd1.getPort(), HTTP_1_1, "/ifoo/", "/ifoo/", backEnd1); assertEquals(1, backEnd1.getRequestCount()); assertProxiedRequests(0); }
@Test public void sanityCheckHttp2Post() throws Exception { setupClient(1, true); setupBack(true); post(backEnd1.getPort(), HTTP_2, "/ifoo/", "/ifoo/", backEnd1); assertEquals(1, backEnd1.getRequestCount()); assertProxiedRequests(0); }
@Test public void testHttp2toHttp1ServerGet() throws Exception { setupClient(1, true); setupFrontBack(true, false); get(proxyPort(), HTTP_2, "/foo/", "/ifoo/", backEnd1); assertEquals(1, backEnd1.getRequestCount()); assertProxiedRequests(1); }
@Test public void testHttp2toHttp2ServerGetMany() throws Exception { setupClient(NUM_REQUESTS, true); setupFrontBack(true, true); verify(multipleAsyncRequests(false).blockingIterable()); assertEquals(20, backEnd1.getRequestCount()); assertProxiedRequests(20); }
@Test public void testHttp2toHttp2ServerPostMany() throws Exception { setupClient(NUM_REQUESTS, true); setupFrontBack(true, true); verify(multipleAsyncRequests(true).blockingIterable()); assertEquals(NUM_REQUESTS * 2, backEnd1.getRequestCount()); assertProxiedRequests(NUM_REQUESTS * 2); }