private BasicHttpResponse createOkSearchResponse() throws UnsupportedEncodingException { BasicHttpResponse okSearchResponse = createOkResponse(); HttpEntity searchResponseEntity = new StringEntity("" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + " <D:multistatus xmlns:D=\"DAV:\"\n" + " xmlns:R=\"http://example.org/propschema\">\n" + " <D:response>" + " <D:propstat>\n" + " <uid>Inbox</uid>" + " <href>http://example.org/Exchange/user/Inbox</href>\n" + " </D:propstat></D:response>\n" + " <D:response>" + " <D:propstat>\n" + " <uid>Drafts</uid>" + " <href>http://example.org/Exchange/user/Drafts</href>\n" + " </D:propstat></D:response>\n" + " <D:response>" + " <D:propstat>\n" + " <uid>Folder2</uid>" + " <href>http://example.org/Exchange/user/Folder2</href>\n" + " </D:propstat></D:response>\n" + " </D:multistatus>"); okSearchResponse.setEntity(searchResponseEntity); return okSearchResponse; }
private static HttpResponse transformResponse(Response response) { int code = response.code(); String message = response.message(); BasicHttpResponse httpResponse = new BasicHttpResponse(HTTP_1_1, code, message); ResponseBody body = response.body(); InputStreamEntity entity = new InputStreamEntity(body.byteStream(), body.contentLength()); httpResponse.setEntity(entity); Headers headers = response.headers(); for (int i = 0, size = headers.size(); i < size; i++) { String name = headers.name(i); String value = headers.value(i); httpResponse.addHeader(name, value); if ("Content-Type".equalsIgnoreCase(name)) { entity.setContentType(value); } else if ("Content-Encoding".equalsIgnoreCase(name)) { entity.setContentEncoding(value); } } return httpResponse; }
@Test public void testOAuthStepTwo() throws IOException { //Create the mock response HttpResponse postResponse = new BasicHttpResponse(new ProtocolVersion("TEST", 0, 0), 200, "TEST"); postResponse.setEntity(new StringEntity(oauthStepTwoTestJSON)); //Set the call providers mock response callProvider.setPostResponse(postResponse); //Perform mock oauth step 2 Credentials credentials = client.oauthStepTwo(null, null); //Check null is not returned assertNotNull(credentials); //Check the info is what it should be assertEquals("access_token", credentials.getAccessToken()); assertEquals("refresh_token", credentials.getRefreshToken()); assertEquals("1234567890", credentials.getDateGenerated()); }
/** * Checks to make sure that tokens and dates are refreshed given a valid response from google * Gives a mock response from google with "new" access code * @throws IOException */ @Test public void checkRefreshToken() throws IOException { long dateGenerated = Instant.now().getEpochSecond() - (3600*2); credentials = new Credentials(jsonWithoutDate, dateGenerated); //Create mock response MockCall callProvider = new MockCall(); HttpResponse postResponse = new BasicHttpResponse(new ProtocolVersion("TEST", 0, 0), 200, "TEST"); postResponse.setEntity(new StringEntity("{ \"access_token\":\"new_access_token\", \"expires_in\":3920, \"token_type\":\"Bearer\" }")); callProvider.setPostResponse(postResponse); //Make assertions assertTrue(credentials.refreshToken(null, null, callProvider)); assertEquals("new_access_token", credentials.getAccessToken()); assertNotEquals(String.valueOf(dateGenerated), credentials.getDateGenerated()); }
public void testPerformRequestOnSuccess() throws IOException { MainRequest mainRequest = new MainRequest(); CheckedFunction<MainRequest, Request, IOException> requestConverter = request -> new Request("GET", "/", Collections.emptyMap(), null); RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class), anyObject(), anyVararg())).thenReturn(mockResponse); { Integer result = restHighLevelClient.performRequest(mainRequest, requestConverter, response -> response.getStatusLine().getStatusCode(), Collections.emptySet()); assertEquals(restStatus.getStatus(), result.intValue()); } { IOException ioe = expectThrows(IOException.class, () -> restHighLevelClient.performRequest(mainRequest, requestConverter, response -> {throw new IllegalStateException();}, Collections.emptySet())); assertEquals("Unable to parse response body for Response{requestLine=GET / http/1.1, host=http://localhost:9200, " + "response=http/1.1 " + restStatus.getStatus() + " " + restStatus.name() + "}", ioe.getMessage()); } }
public void testPerformRequestOnResponseExceptionWithoutEntity() throws IOException { MainRequest mainRequest = new MainRequest(); CheckedFunction<MainRequest, Request, IOException> requestConverter = request -> new Request("GET", "/", Collections.emptyMap(), null); RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(mockResponse); when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class), anyObject(), anyVararg())).thenThrow(responseException); ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class, () -> restHighLevelClient.performRequest(mainRequest, requestConverter, response -> response.getStatusLine().getStatusCode(), Collections.emptySet())); assertEquals(responseException.getMessage(), elasticsearchException.getMessage()); assertEquals(restStatus, elasticsearchException.status()); assertSame(responseException, elasticsearchException.getCause()); }
public void testPerformRequestOnResponseExceptionWithEntity() throws IOException { MainRequest mainRequest = new MainRequest(); CheckedFunction<MainRequest, Request, IOException> requestConverter = request -> new Request("GET", "/", Collections.emptyMap(), null); RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); httpResponse.setEntity(new StringEntity("{\"error\":\"test error message\",\"status\":" + restStatus.getStatus() + "}", ContentType.APPLICATION_JSON)); Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(mockResponse); when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class), anyObject(), anyVararg())).thenThrow(responseException); ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class, () -> restHighLevelClient.performRequest(mainRequest, requestConverter, response -> response.getStatusLine().getStatusCode(), Collections.emptySet())); assertEquals("Elasticsearch exception [type=exception, reason=test error message]", elasticsearchException.getMessage()); assertEquals(restStatus, elasticsearchException.status()); assertSame(responseException, elasticsearchException.getSuppressed()[0]); }
public void testPerformRequestOnResponseExceptionWithBrokenEntity() throws IOException { MainRequest mainRequest = new MainRequest(); CheckedFunction<MainRequest, Request, IOException> requestConverter = request -> new Request("GET", "/", Collections.emptyMap(), null); RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); httpResponse.setEntity(new StringEntity("{\"error\":", ContentType.APPLICATION_JSON)); Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(mockResponse); when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class), anyObject(), anyVararg())).thenThrow(responseException); ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class, () -> restHighLevelClient.performRequest(mainRequest, requestConverter, response -> response.getStatusLine().getStatusCode(), Collections.emptySet())); assertEquals("Unable to parse response body", elasticsearchException.getMessage()); assertEquals(restStatus, elasticsearchException.status()); assertSame(responseException, elasticsearchException.getCause()); assertThat(elasticsearchException.getSuppressed()[0], instanceOf(JsonParseException.class)); }
public void testPerformRequestOnResponseExceptionWithBrokenEntity2() throws IOException { MainRequest mainRequest = new MainRequest(); CheckedFunction<MainRequest, Request, IOException> requestConverter = request -> new Request("GET", "/", Collections.emptyMap(), null); RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); httpResponse.setEntity(new StringEntity("{\"status\":" + restStatus.getStatus() + "}", ContentType.APPLICATION_JSON)); Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(mockResponse); when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class), anyObject(), anyVararg())).thenThrow(responseException); ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class, () -> restHighLevelClient.performRequest(mainRequest, requestConverter, response -> response.getStatusLine().getStatusCode(), Collections.emptySet())); assertEquals("Unable to parse response body", elasticsearchException.getMessage()); assertEquals(restStatus, elasticsearchException.status()); assertSame(responseException, elasticsearchException.getCause()); assertThat(elasticsearchException.getSuppressed()[0], instanceOf(IllegalStateException.class)); }
public void testPerformRequestOnResponseExceptionWithIgnoresErrorNoBody() throws IOException { MainRequest mainRequest = new MainRequest(); CheckedFunction<MainRequest, Request, IOException> requestConverter = request -> new Request("GET", "/", Collections.emptyMap(), null); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(RestStatus.NOT_FOUND)); Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(mockResponse); when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class), anyObject(), anyVararg())).thenThrow(responseException); ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class, () -> restHighLevelClient.performRequest(mainRequest, requestConverter, response -> {throw new IllegalStateException();}, Collections.singleton(404))); assertEquals(RestStatus.NOT_FOUND, elasticsearchException.status()); assertSame(responseException, elasticsearchException.getCause()); assertEquals(responseException.getMessage(), elasticsearchException.getMessage()); }
public void testPerformRequestOnResponseExceptionWithIgnoresErrorValidBody() throws IOException { MainRequest mainRequest = new MainRequest(); CheckedFunction<MainRequest, Request, IOException> requestConverter = request -> new Request("GET", "/", Collections.emptyMap(), null); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(RestStatus.NOT_FOUND)); httpResponse.setEntity(new StringEntity("{\"error\":\"test error message\",\"status\":404}", ContentType.APPLICATION_JSON)); Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(mockResponse); when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class), anyObject(), anyVararg())).thenThrow(responseException); ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class, () -> restHighLevelClient.performRequest(mainRequest, requestConverter, response -> {throw new IllegalStateException();}, Collections.singleton(404))); assertEquals(RestStatus.NOT_FOUND, elasticsearchException.status()); assertSame(responseException, elasticsearchException.getSuppressed()[0]); assertEquals("Elasticsearch exception [type=exception, reason=test error message]", elasticsearchException.getMessage()); }
public void testResponseProcessing() throws Exception { ContentDecoder contentDecoder = mock(ContentDecoder.class); IOControl ioControl = mock(IOControl.class); HttpContext httpContext = mock(HttpContext.class); HeapBufferedAsyncResponseConsumer consumer = spy(new HeapBufferedAsyncResponseConsumer(TEST_BUFFER_LIMIT)); ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK"); HttpResponse httpResponse = new BasicHttpResponse(statusLine); httpResponse.setEntity(new StringEntity("test", ContentType.TEXT_PLAIN)); //everything goes well consumer.responseReceived(httpResponse); consumer.consumeContent(contentDecoder, ioControl); consumer.responseCompleted(httpContext); verify(consumer).releaseResources(); verify(consumer).buildResult(httpContext); assertTrue(consumer.isDone()); assertSame(httpResponse, consumer.getResult()); consumer.responseCompleted(httpContext); verify(consumer, times(1)).releaseResources(); verify(consumer, times(1)).buildResult(httpContext); }
private static void bufferLimitTest(HeapBufferedAsyncResponseConsumer consumer, int bufferLimit) throws Exception { ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK"); consumer.onResponseReceived(new BasicHttpResponse(statusLine)); final AtomicReference<Long> contentLength = new AtomicReference<>(); HttpEntity entity = new StringEntity("", ContentType.APPLICATION_JSON) { @Override public long getContentLength() { return contentLength.get(); } }; contentLength.set(randomLong(bufferLimit)); consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON); contentLength.set(randomLongBetween(bufferLimit + 1, MAX_TEST_BUFFER_SIZE)); try { consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON); } catch(ContentTooLongException e) { assertEquals("entity content is too long [" + entity.getContentLength() + "] for the configured buffer limit [" + bufferLimit + "]", e.getMessage()); } }
@Before @SuppressWarnings("unchecked") public void createRestClient() throws IOException { CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class); when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class))).thenAnswer(new Answer<Future<HttpResponse>>() { @Override public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable { HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0]; HttpUriRequest request = (HttpUriRequest)requestProducer.generateRequest(); HttpHost httpHost = requestProducer.getTarget(); HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2]; assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class)); FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock.getArguments()[3]; //return the desired status code or exception depending on the path if (request.getURI().getPath().equals("/soe")) { futureCallback.failed(new SocketTimeoutException(httpHost.toString())); } else if (request.getURI().getPath().equals("/coe")) { futureCallback.failed(new ConnectTimeoutException(httpHost.toString())); } else if (request.getURI().getPath().equals("/ioe")) { futureCallback.failed(new IOException(httpHost.toString())); } else { int statusCode = Integer.parseInt(request.getURI().getPath().substring(1)); StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), statusCode, ""); futureCallback.completed(new BasicHttpResponse(statusLine)); } return null; } }); int numHosts = RandomNumbers.randomIntBetween(getRandom(), 2, 5); httpHosts = new HttpHost[numHosts]; for (int i = 0; i < numHosts; i++) { httpHosts[i] = new HttpHost("localhost", 9200 + i); } failureListener = new HostsTrackingFailureListener(); restClient = new RestClient(httpClient, 10000, new Header[0], httpHosts, null, failureListener); }
@Test public void testExecute_non2xx_exception() throws IOException { HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "Not found")); BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream("{\"message\" : \"error payload\"}".getBytes())); resp.setEntity(entity); Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class)); Map<String, String> headers = new HashMap<>(); headers.put("Account-Id", "fubar"); headers.put("Content-Type", "application/json"); try { client.execute( new GenericApiGatewayRequestBuilder() .withBody(new ByteArrayInputStream("test request".getBytes())) .withHttpMethod(HttpMethodName.POST) .withHeaders(headers) .withResourcePath("/test/orders").build()); Assert.fail("Expected exception"); } catch (GenericApiGatewayException e) { assertEquals("Wrong status code", 404, e.getStatusCode()); assertEquals("Wrong exception message", "{\"message\":\"error payload\"}", e.getErrorMessage()); } }
private Segment segmentInResponseToCode(int code) { NoOpResponseHandler responseHandler = new NoOpResponseHandler(); TracedResponseHandler<String> tracedResponseHandler = new TracedResponseHandler<>(responseHandler); HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, code, "")); Segment segment = AWSXRay.beginSegment("test"); AWSXRay.beginSubsegment("someHttpCall"); try { tracedResponseHandler.handleResponse(httpResponse); } catch (IOException e) { throw new RuntimeException(e); } AWSXRay.endSubsegment(); AWSXRay.endSegment(); return segment; }
@Test public void post_whenResponseIsFailure_logsException() throws IOException { ArgumentCaptor<HttpPost> requestCaptor = ArgumentCaptor.forClass(HttpPost.class); HttpClient httpClient = mock(HttpClient.class); BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("http", 1, 1), 400, "")); response.setEntity(new StringEntity("failure reason here")); when(httpClient.execute(requestCaptor.capture())).thenReturn(response); MsTeamsNotification w = factory.getMsTeamsNotification(httpClient); MsTeamsNotificationPayloadContent content = new MsTeamsNotificationPayloadContent(); content.setBuildDescriptionWithLinkSyntax("http://foo"); content.setCommits(new ArrayList<Commit>()); w.setPayload(content); w.setEnabled(true); w.post(); assertNotNull(w.getResponse()); assertFalse(w.getResponse().getOk()); }
@Test public void logsRequestAndResponseFields() { HttpContext context = new BasicHttpContext(); context.setAttribute(HTTP_TARGET_HOST, "http://www.google.com"); OutboundRequestLoggingInterceptor interceptor = new OutboundRequestLoggingInterceptor(new FakeClock(20)); interceptor.process(new BasicHttpRequest("GET", "/something"), context); interceptor.process(new BasicHttpResponse(new BasicStatusLine(ANY_PROTOCOL, 200, "any")), context); Map<String, Object> fields = new ConcurrentHashMap<>(); fields.put("requestMethod", "GET"); fields.put("requestURI", "http://www.google.com/something"); testAppender.assertEvent(0, INFO, "Outbound request start", appendEntries(fields)); fields.put("responseTime", 20L); fields.put("responseCode", 200); testAppender.assertEvent(1, INFO, "Outbound request finish", appendEntries(fields)); }
@Test public void allowEmptyConstructorToBuildDefaultClock() { testAppender.clearEvents(); HttpContext context = new BasicHttpContext(); context.setAttribute(HTTP_TARGET_HOST, "http://www.google.com"); OutboundRequestLoggingInterceptor interceptor = new OutboundRequestLoggingInterceptor(); interceptor.process(new BasicHttpRequest("GET", "/something"), context); interceptor.process(new BasicHttpResponse(new BasicStatusLine(ANY_PROTOCOL, 200, "any")), context); assertThat(testAppender.getEvents()).extracting("message") .contains("Outbound request start", Index.atIndex(0)) .contains("Outbound request finish", Index.atIndex(1)); }
/** * Wait for the server is ready. */ private void waitForServerReady() throws IOException, InterruptedException { final HttpGet httpget = new HttpGet(getPingUri()); HttpResponse response = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, "")); int counter = 0; while (true) { try { response = httpclient.execute(httpget); final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { break; } checkRetries(counter); } catch (final HttpHostConnectException ex) { // NOSONAR - Wait, and check later log.info("Check failed, retrying..."); checkRetries(counter); } finally { EntityUtils.consume(response.getEntity()); } counter++; } }
@Test public void testSetsViaHeaderOnResponseIfRequestServedFromCache() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( "http://foo.example.com/")); final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( "http://foo.example.com/")); final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); resp1.setHeader("ETag", "\"etag\""); resp1.setHeader("Date", DateUtils.formatDate(new Date())); resp1.setHeader("Cache-Control", "public, max-age=3600"); backendExpectsAnyRequestAndReturn(resp1); replayMocks(); impl.execute(route, req1, context, null); final HttpResponse result = impl.execute(route, req2, context, null); verifyMocks(); Assert.assertNotNull(result.getFirstHeader("Via")); }
@Test public void testAuthenticationHandshaking() throws Exception { final HttpHost host = new HttpHost("somehost", 80); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\"")); response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", stale=true, nonce=\"1234\"")); response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "whatever realm=\"realm1\", stuff=\"1234\"")); final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy(); this.authState.setState(AuthProtocolState.CHALLENGED); this.authState.update(new DigestScheme(), this.credentials); Assert.assertTrue(this.httpAuthenticator.handleAuthChallenge(host, response, authStrategy, this.authState, this.context)); Assert.assertEquals(AuthProtocolState.HANDSHAKE, this.authState.getState()); }
@Before public void setUp() throws Exception { requestDate = new Date(System.currentTimeMillis() - 1000); responseDate = new Date(); now = new Date(); oneSecondAgo = new Date(now.getTime() - 1000L); twoSecondsAgo = new Date(now.getTime() - 2000L); eightSecondsAgo = new Date(now.getTime() - 8000L); tenSecondsAgo = new Date(now.getTime() - 10000L); response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not Modified"); impl = new CacheEntryUpdater(); }
@Test public void testCookieRejected() throws Exception { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader(SM.SET_COOKIE2, "name=value; Domain=www.somedomain.com; Version=1"); final HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpClientContext.COOKIE_ORIGIN, this.cookieOrigin); context.setAttribute(HttpClientContext.COOKIE_SPEC, this.cookieSpec); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); final HttpResponseInterceptor interceptor = new ResponseProcessCookies(); interceptor.process(response, context); final List<Cookie> cookies = this.cookieStore.getCookies(); Assert.assertNotNull(cookies); Assert.assertTrue(cookies.isEmpty()); }
@Test public void unauthorized() throws Exception { MockHttpStack mockHttpStack = new MockHttpStack(); BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 401, "Unauthorized"); mockHttpStack.setResponseToReturn(fakeResponse); BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack); Request<String> request = buildRequest(); request.setRetryPolicy(mMockRetryPolicy); doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class)); try { httpNetwork.performRequest(request); } catch (VolleyError e) { // expected } // should retry in case it's an auth failure. verify(mMockRetryPolicy).retry(any(AuthFailureError.class)); }
protected void testUnsafeMethodDoesNotInvalidateCacheForHeaderUri( final HttpRequestWrapper unsafeReq) throws Exception, IOException { final HttpHost otherHost = new HttpHost("bar.example.com", 80); final HttpRoute otherRoute = new HttpRoute(otherHost); final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/content", HttpVersion.HTTP_1_1)); final HttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","public, max-age=3600"); backendExpectsAnyRequestAndReturn(resp1); final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NO_CONTENT, "No Content"); backendExpectsAnyRequestAndReturn(resp2); final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/content", HttpVersion.HTTP_1_1)); replayMocks(); impl.execute(otherRoute, req1, context, null); impl.execute(route, unsafeReq, context, null); impl.execute(otherRoute, req3, context, null); verifyMocks(); }
@Test public void testSocketTimeoutExistingConnection() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); final RequestConfig config = RequestConfig.custom().setSocketTimeout(3000).build(); final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test")); context.setRequestConfig(config); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(managedConn.isOpen()).thenReturn(true); Mockito.when(requestExecutor.execute( Mockito.same(request), Mockito.<HttpClientConnection>any(), Mockito.<HttpClientContext>any())).thenReturn(response); minimalClientExec.execute(route, request, context, execAware); Mockito.verify(managedConn).setSocketTimeout(3000); }
@Test(expected = HttpException.class) public void testEstablishRouteViaProxyTunnelFailure() throws Exception { final AuthState authState = new AuthState(); final HttpRoute route = new HttpRoute(target, null, proxy, true); final HttpClientContext context = new HttpClientContext(); final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test")); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 500, "Boom"); response.setEntity(new StringEntity("Ka-boom")); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); Mockito.when(requestExecutor.execute( Mockito.<HttpRequest>any(), Mockito.<HttpClientConnection>any(), Mockito.<HttpClientContext>any())).thenReturn(response); try { mainClientExec.establishRoute(authState, managedConn, route, request, context); } catch (final TunnelRefusedException ex) { final HttpResponse r = ex.getResponse(); Assert.assertEquals("Ka-boom", EntityUtils.toString(r.getEntity())); Mockito.verify(managedConn).close(); throw ex; } }
@Test public void testAuthenticationRequestedAfterSuccess() throws Exception { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); Mockito.when(this.defltAuthStrategy.isAuthenticationRequested( Mockito.any(HttpHost.class), Mockito.any(HttpResponse.class), Mockito.any(HttpContext.class))).thenReturn(Boolean.TRUE); this.authState.update(this.authScheme, this.credentials); this.authState.setState(AuthProtocolState.SUCCESS); Assert.assertTrue(this.httpAuthenticator.isAuthenticationRequested( this.defaultHost, response, this.defltAuthStrategy, this.authState, this.context)); Mockito.verify(this.defltAuthStrategy).isAuthenticationRequested(this.defaultHost, response, this.context); Mockito.verify(this.defltAuthStrategy).authFailed(this.defaultHost, this.authScheme, this.context); }
@Test public void testReturns304ForIfNoneMatchHeaderIfRequestServedFromCache() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( "http://foo.example.com/")); final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( "http://foo.example.com/")); req2.addHeader("If-None-Match", "*"); final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); resp1.setHeader("ETag", "\"etag\""); resp1.setHeader("Date", DateUtils.formatDate(new Date())); resp1.setHeader("Cache-Control", "public, max-age=3600"); backendExpectsAnyRequestAndReturn(resp1); replayMocks(); impl.execute(route, req1, context, null); final HttpResponse result = impl.execute(route, req2, context, null); verifyMocks(); Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getStatusLine().getStatusCode()); }
@Test public void redirect() throws Exception { for (int i = 300; i <= 399; i++) { MockHttpStack mockHttpStack = new MockHttpStack(); BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, ""); mockHttpStack.setResponseToReturn(fakeResponse); BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack); Request<String> request = buildRequest(); request.setRetryPolicy(mMockRetryPolicy); doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class)); try { httpNetwork.performRequest(request); } catch (VolleyError e) { // expected } // should not retry 300 responses. verify(mMockRetryPolicy, never()).retry(any(VolleyError.class)); reset(mMockRetryPolicy); } }
@Test public void otherClientError() throws Exception { for (int i = 400; i <= 499; i++) { if (i == 401 || i == 403) { // covered above. continue; } MockHttpStack mockHttpStack = new MockHttpStack(); BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, ""); mockHttpStack.setResponseToReturn(fakeResponse); BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack); Request<String> request = buildRequest(); request.setRetryPolicy(mMockRetryPolicy); doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class)); try { httpNetwork.performRequest(request); } catch (VolleyError e) { // expected } // should not retry other 400 errors. verify(mMockRetryPolicy, never()).retry(any(VolleyError.class)); reset(mMockRetryPolicy); } }
@Test public void serverError_enableRetries() throws Exception { for (int i = 500; i <= 599; i++) { MockHttpStack mockHttpStack = new MockHttpStack(); BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, ""); mockHttpStack.setResponseToReturn(fakeResponse); BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack, new ByteArrayPool(4096)); Request<String> request = buildRequest(); request.setRetryPolicy(mMockRetryPolicy); request.setShouldRetryServerErrors(true); doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class)); try { httpNetwork.performRequest(request); } catch (VolleyError e) { // expected } // should retry all 500 errors verify(mMockRetryPolicy).retry(any(ServerError.class)); reset(mMockRetryPolicy); } }
@Test public void serverError_disableRetries() throws Exception { for (int i = 500; i <= 599; i++) { MockHttpStack mockHttpStack = new MockHttpStack(); BasicHttpResponse fakeResponse = new BasicHttpResponse( new ProtocolVersion("HTTP", 1, 1), i, ""); mockHttpStack.setResponseToReturn(fakeResponse); BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack); Request<String> request = buildRequest(); request.setRetryPolicy(mMockRetryPolicy); doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class)); try { httpNetwork.performRequest(request); } catch (VolleyError e) { // expected } // should not retry any 500 error w/ HTTP 500 retries turned off (the default). verify(mMockRetryPolicy, never()).retry(any(VolleyError.class)); reset(mMockRetryPolicy); } }
public void canCreateInstance() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_CREATED, "Created"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/instances/created.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); Instance instance = new Instance() .setName("some_name") .setPackageId(new UUID(12L, 24L)) .setImage(new UUID(8L, 16L)) .setTags(Collections.singletonMap(TEST_TAG_KEY, TEST_TAG)); try (CloudApiConnectionContext context = createMockContext(response)) { final Instance created = instanceApi.create(context, instance); assertNotNull(created); assertNotNull(created.getId()); } }
@Test public void testNoCookieStore() throws Exception { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); response.addHeader(SM.SET_COOKIE, "name1=value1"); final HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpClientContext.COOKIE_ORIGIN, this.cookieOrigin); context.setAttribute(HttpClientContext.COOKIE_SPEC, this.cookieSpec); context.setAttribute(HttpClientContext.COOKIE_STORE, null); final HttpResponseInterceptor interceptor = new ResponseProcessCookies(); interceptor.process(response, context); final List<Cookie> cookies = this.cookieStore.getCookies(); Assert.assertNotNull(cookies); Assert.assertEquals(0, cookies.size()); }
@Test public void testAuthentication() throws Exception { final HttpHost host = new HttpHost("somehost", 80); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\"")); response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\"")); response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "whatever realm=\"realm1\", stuff=\"1234\"")); final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy(); Assert.assertTrue(this.httpAuthenticator.handleAuthChallenge(host, response, authStrategy, this.authState, this.context)); Assert.assertEquals(AuthProtocolState.CHALLENGED, this.authState.getState()); final Queue<AuthOption> options = this.authState.getAuthOptions(); Assert.assertNotNull(options); final AuthOption option1 = options.poll(); Assert.assertNotNull(option1); Assert.assertEquals("digest", option1.getAuthScheme().getSchemeName()); final AuthOption option2 = options.poll(); Assert.assertNotNull(option2); Assert.assertEquals("basic", option2.getAuthScheme().getSchemeName()); Assert.assertNull(options.poll()); }
@Test public void testSelectNoCredentialsProvider() throws Exception { final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy(); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); final HttpHost authhost = new HttpHost("locahost", 80); final HttpClientContext context = HttpClientContext.create(); final Map<String, Header> challenges = new HashMap<String, Header>(); challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\"")); challenges.put("digest", new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\"")); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register("basic", new BasicSchemeFactory()) .register("digest", new DigestSchemeFactory()).build(); context.setAuthSchemeRegistry(authSchemeRegistry); final Queue<AuthOption> options = authStrategy.select(challenges, authhost, response, context); Assert.assertNotNull(options); Assert.assertEquals(0, options.size()); }