Search in sources :

Example 56 with MockLowLevelHttpResponse

use of com.google.api.client.testing.http.MockLowLevelHttpResponse in project beam by apache.

the class RetryHttpRequestInitializerTest method testErrorCodeForbidden.

/**
 * Tests that a non-retriable error is not retried.
 */
@Test
public void testErrorCodeForbidden() throws IOException {
    MockLowLevelHttpResponse[] responses = createMockResponseWithStatusCode(// Non-retryable error.
    403, // Shouldn't happen.
    200);
    when(mockLowLevelRequest.execute()).thenReturn(responses[0], responses[1]);
    try {
        Storage.Buckets.Get result = storage.buckets().get("test");
        HttpResponse response = result.executeUnparsed();
        assertNotNull(response);
    } catch (HttpResponseException e) {
        assertThat(e.getMessage(), Matchers.containsString("403"));
    }
    verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class));
    verify(mockLowLevelRequest, atLeastOnce()).addHeader(anyString(), anyString());
    verify(mockLowLevelRequest).setTimeout(anyInt(), anyInt());
    verify(mockLowLevelRequest).setWriteTimeout(anyInt());
    verify(mockLowLevelRequest).execute();
    verify(responses[0], atLeastOnce()).getStatusCode();
    verify(responses[1], never()).getStatusCode();
    expectedLogs.verifyWarn("Request failed with code 403");
}
Also used : MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) HttpResponse(com.google.api.client.http.HttpResponse) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse) HttpResponseException(com.google.api.client.http.HttpResponseException) Test(org.junit.Test)

Example 57 with MockLowLevelHttpResponse

use of com.google.api.client.testing.http.MockLowLevelHttpResponse in project beam by apache.

the class PackageUtilTest method googleJsonResponseException.

/**
 * Builds a fake GoogleJsonResponseException for testing API error handling.
 */
private static GoogleJsonResponseException googleJsonResponseException(final int status, final String reason, final String message) throws IOException {
    final JsonFactory jsonFactory = new JacksonFactory();
    HttpTransport transport = new MockHttpTransport() {

        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            ErrorInfo errorInfo = new ErrorInfo();
            errorInfo.setReason(reason);
            errorInfo.setMessage(message);
            errorInfo.setFactory(jsonFactory);
            GenericJson error = new GenericJson();
            error.set("code", status);
            error.set("errors", Arrays.asList(errorInfo));
            error.setFactory(jsonFactory);
            GenericJson errorResponse = new GenericJson();
            errorResponse.set("error", error);
            errorResponse.setFactory(jsonFactory);
            return new MockLowLevelHttpRequest().setResponse(new MockLowLevelHttpResponse().setContent(errorResponse.toPrettyString()).setContentType(Json.MEDIA_TYPE).setStatusCode(status));
        }
    };
    HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    return GoogleJsonResponseException.from(jsonFactory, response);
}
Also used : GenericJson(com.google.api.client.json.GenericJson) LowLevelHttpRequest(com.google.api.client.http.LowLevelHttpRequest) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) HttpRequest(com.google.api.client.http.HttpRequest) HttpTransport(com.google.api.client.http.HttpTransport) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) ErrorInfo(com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo) JsonFactory(com.google.api.client.json.JsonFactory) HttpResponse(com.google.api.client.http.HttpResponse) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest)

Example 58 with MockLowLevelHttpResponse

use of com.google.api.client.testing.http.MockLowLevelHttpResponse in project googleads-java-lib by googleads.

the class MockHttpServer method execute.

private LowLevelHttpResponse execute(MockLowLevelHttpRequest request) throws IOException {
    ActualResponse actualResponse = new ActualResponse(request.getHeaders());
    actualResponses.add(actualResponse);
    MockResponse mockResponse;
    if (mockResponses.isEmpty()) {
        mockResponse = new MockResponse("No mock response body set", 500);
    } else {
        mockResponse = mockResponses.pop();
    }
    // Read the raw bytes from the request.
    ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
    request.getStreamingContent().writeTo(byteOutStream);
    final byte[] rawRequestBytes = byteOutStream.toByteArray();
    // Inflate the raw bytes if they are in gzip format.
    boolean isGzipFormat = false;
    List<String> contentEncodingValues = request.getHeaders().get("Content-Encoding");
    if (contentEncodingValues != null && !contentEncodingValues.isEmpty()) {
        isGzipFormat = "gzip".equals(contentEncodingValues.get(0));
    }
    byte[] requestBytes;
    if (isGzipFormat) {
        requestBytes = new ByteSource() {

            @Override
            public InputStream openStream() throws IOException {
                return new GZIPInputStream(ByteSource.wrap(rawRequestBytes).openStream());
            }
        }.read();
    } else {
        requestBytes = rawRequestBytes;
    }
    // Convert the (possibly inflated) request bytes to a string.
    String requestBody = ByteSource.wrap(requestBytes).asCharSource(StandardCharsets.UTF_8).read();
    actualResponse.setRequestBody(requestBody);
    if (mockResponse.isValidateUrlMatches() && !getServerUrl().equals(request.getUrl())) {
        throw new ConnectException(String.format("Request URL does not match.%n  Expected: %s%n  Actual: %s%n", getServerUrl(), request.getUrl()));
    }
    MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
    // Add the Location response header, which is required by some tests such as
    // BatchJobUploaderTest.
    response.addHeader("Location", getServerUrl());
    response.setStatusCode(mockResponse.getHttpStatus());
    response.setContentType(mockResponse.getContentType());
    response.setContent(mockResponse.getBody());
    return response;
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) ByteSource(com.google.common.io.ByteSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ConnectException(java.net.ConnectException)

Example 59 with MockLowLevelHttpResponse

use of com.google.api.client.testing.http.MockLowLevelHttpResponse in project googleads-java-lib by googleads.

the class HttpHandlerTest method testInvokeSetsTimeout.

/**
 * Tests that the timeout set on the message context is passed to the underlying request.
 */
@Test
public void testInvokeSetsTimeout() {
    MessageContext messageContext = new MessageContext(axisEngine);
    messageContext.setRequestMessage(requestMessage);
    messageContext.setProperty(MessageContext.TRANS_URL, "https://www.example.com");
    // Do not care about XML parsing for this test, so set the response's status code to 302
    // to trigger an AxisFault.
    MockLowLevelHttpResponse lowLevelHttpResponse = new MockLowLevelHttpResponse();
    lowLevelHttpResponse.setContent("Intentional failure");
    lowLevelHttpResponse.setStatusCode(302);
    /*
     * Set timeout on the message context, then create a custom mock transport that will capture
     * invocations of LowLevelHttpRequest.setTimeout(int, int) and record the arguments passed.
     */
    int timeout = 1234567;
    messageContext.setTimeout(timeout);
    final int[] actualTimeouts = new int[] { Integer.MIN_VALUE, Integer.MIN_VALUE };
    MockLowLevelHttpRequest lowLevelHttpRequest = new MockLowLevelHttpRequest() {

        @Override
        public void setTimeout(int connectTimeout, int readTimeout) throws IOException {
            actualTimeouts[0] = connectTimeout;
            actualTimeouts[1] = readTimeout;
            super.setTimeout(connectTimeout, readTimeout);
        }
    };
    lowLevelHttpRequest.setResponse(lowLevelHttpResponse);
    MockHttpTransport mockTransport = new MockHttpTransport.Builder().setLowLevelHttpRequest(lowLevelHttpRequest).build();
    httpHandler = new HttpHandler(mockTransport, streamListener);
    try {
        httpHandler.invoke(messageContext);
        fail("Expected an AxisFault");
    } catch (AxisFault e) {
        assertThat(e.getFaultString(), Matchers.containsString("302"));
    }
    assertArrayEquals("Timeouts not set to expected values", new int[] { timeout, timeout }, actualTimeouts);
}
Also used : AxisFault(org.apache.axis.AxisFault) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MessageContext(org.apache.axis.MessageContext) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Test(org.junit.Test)

Example 60 with MockLowLevelHttpResponse

use of com.google.api.client.testing.http.MockLowLevelHttpResponse in project copybara by google.

the class GitHubApiTest method trainMockDelete.

@Override
public void trainMockDelete(String apiPath, Predicate<String> requestValidator, int statusCode) {
    String path = String.format("DELETE https://api.github.com%s", apiPath);
    MockLowLevelHttpResponse response = new MockLowLevelHttpResponse().setStatusCode(statusCode);
    if (statusCode >= 400) {
        response.setContent("{ message: 'Error on delete' }");
    }
    requestToResponse.put(path, response);
    requestValidators.put(path, requestValidator);
}
Also used : MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse)

Aggregations

MockLowLevelHttpResponse (com.google.api.client.testing.http.MockLowLevelHttpResponse)63 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)40 MockLowLevelHttpRequest (com.google.api.client.testing.http.MockLowLevelHttpRequest)38 Test (org.junit.Test)31 LowLevelHttpResponse (com.google.api.client.http.LowLevelHttpResponse)24 LowLevelHttpRequest (com.google.api.client.http.LowLevelHttpRequest)22 IOException (java.io.IOException)21 HttpTransport (com.google.api.client.http.HttpTransport)10 GenericJson (com.google.api.client.json.GenericJson)9 HttpResponse (com.google.api.client.http.HttpResponse)8 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)8 JsonFactory (com.google.api.client.json.JsonFactory)7 HttpRequest (com.google.api.client.http.HttpRequest)6 GenericUrl (com.google.api.client.http.GenericUrl)5 Objectify (com.googlecode.objectify.Objectify)5 Storage (com.google.api.services.storage.Storage)4 TestingConsole (com.google.copybara.util.console.testing.TestingConsole)4 ErrorInfo (com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo)3 MockGoogleClient (com.google.api.client.googleapis.testing.services.MockGoogleClient)3 MockGoogleClientRequest (com.google.api.client.googleapis.testing.services.MockGoogleClientRequest)3