Search in sources :

Example 21 with MockLowLevelHttpResponse

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

the class GoogleJsonResponseExceptionFactoryTesting method newMock.

/**
 * Convenience factory method that builds a {@link GoogleJsonResponseException}
 * from its arguments. The method builds a dummy {@link HttpRequest} and
 * {@link HttpResponse}, sets the response's status to a user-specified HTTP
 * error code, suppresses exceptions, and executes the request. This forces
 * the underlying framework to create, but not throw, a
 * {@link GoogleJsonResponseException}, which the method retrieves and returns
 * to the invoker.
 *
 * @param jsonFactory the JSON factory that will create all JSON required
 *        by the underlying framework
 * @param httpCode the desired HTTP error code. Note: do nut specify any codes
 *        that indicate successful completion, e.g. 2XX.
 * @param reasonPhrase the HTTP reason code that explains the error. For example,
 *        if {@code httpCode} is {@code 404}, the reason phrase should be
 *        {@code NOT FOUND}.
 * @return the generated {@link GoogleJsonResponseException}, as specified.
 * @throws IOException if request transport fails.
 */
public static GoogleJsonResponseException newMock(JsonFactory jsonFactory, int httpCode, String reasonPhrase) throws IOException {
    MockLowLevelHttpResponse otherServiceUnavaiableLowLevelResponse = new MockLowLevelHttpResponse().setStatusCode(httpCode).setReasonPhrase(reasonPhrase);
    MockHttpTransport otherTransport = new MockHttpTransport.Builder().setLowLevelHttpResponse(otherServiceUnavaiableLowLevelResponse).build();
    HttpRequest otherRequest = otherTransport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    otherRequest.setThrowExceptionOnExecuteError(false);
    HttpResponse otherServiceUnavailableResponse = otherRequest.execute();
    return GoogleJsonResponseException.from(jsonFactory, otherServiceUnavailableResponse);
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) HttpResponse(com.google.api.client.http.HttpResponse)

Example 22 with MockLowLevelHttpResponse

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

the class GcsUtilTest method testGetSizeBytesWhenFileNotFoundBatch.

@Test
public void testGetSizeBytesWhenFileNotFoundBatch() throws Exception {
    JsonFactory jsonFactory = new JacksonFactory();
    String contentBoundary = "batch_foobarbaz";
    String contentBoundaryLine = "--" + contentBoundary;
    String endOfContentBoundaryLine = "--" + contentBoundary + "--";
    GenericJson error = new GenericJson().set("error", new GenericJson().set("code", 404));
    error.setFactory(jsonFactory);
    String content = contentBoundaryLine + "\n" + "Content-Type: application/http\n" + "\n" + "HTTP/1.1 404 Not Found\n" + "Content-Length: -1\n" + "\n" + error.toString() + "\n" + "\n" + endOfContentBoundaryLine + "\n";
    thrown.expect(FileNotFoundException.class);
    MockLowLevelHttpResponse notFoundResponse = new MockLowLevelHttpResponse().setContentType("multipart/mixed; boundary=" + contentBoundary).setContent(content).setStatusCode(HttpStatusCodes.STATUS_CODE_OK);
    MockHttpTransport mockTransport = new MockHttpTransport.Builder().setLowLevelHttpResponse(notFoundResponse).build();
    GcsUtil gcsUtil = gcsOptionsWithTestCredential().getGcsUtil();
    gcsUtil.setStorageClient(new Storage(mockTransport, Transport.getJsonFactory(), null));
    gcsUtil.fileSizes(ImmutableList.of(GcsPath.fromComponents("testbucket", "testobject")));
}
Also used : GenericJson(com.google.api.client.json.GenericJson) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) Storage(com.google.api.services.storage.Storage) GoogleCloudStorage(com.google.cloud.hadoop.gcsio.GoogleCloudStorage) JsonFactory(com.google.api.client.json.JsonFactory) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) Test(org.junit.Test)

Example 23 with MockLowLevelHttpResponse

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

the class GcsUtilTest 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) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest)

Example 24 with MockLowLevelHttpResponse

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

the class RetryHttpRequestInitializerTest method testRetryableError.

/**
 * Tests that a retriable error is retried.
 */
@Test
public void testRetryableError() throws IOException {
    MockLowLevelHttpResponse[] mockResponses = createMockResponseWithStatusCode(// Retryable
    503, // We also retry on 429 Too Many Requests.
    429, 200);
    when(mockLowLevelRequest.execute()).thenReturn(mockResponses[0], mockResponses[1], mockResponses[2]);
    Storage.Buckets.Get result = storage.buckets().get("test");
    HttpResponse response = result.executeUnparsed();
    assertNotNull(response);
    verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class));
    verify(mockLowLevelRequest, atLeastOnce()).addHeader(anyString(), anyString());
    verify(mockLowLevelRequest, times(3)).setTimeout(anyInt(), anyInt());
    verify(mockLowLevelRequest, times(3)).setWriteTimeout(anyInt());
    verify(mockLowLevelRequest, times(3)).execute();
    // It reads the status code of all responses
    for (MockLowLevelHttpResponse mockResponse : mockResponses) {
        verify(mockResponse, atLeastOnce()).getStatusCode();
    }
    expectedLogs.verifyDebug("Request failed with code 503");
}
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) Test(org.junit.Test)

Example 25 with MockLowLevelHttpResponse

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

the class RetryHttpRequestInitializerTest method testRetryableErrorRetryEnoughTimes.

/**
 * Tests that a retryable error is retried enough times.
 */
@Test
public void testRetryableErrorRetryEnoughTimes() throws IOException {
    List<MockLowLevelHttpResponse> responses = new ArrayList<>();
    final int retries = 10;
    // The underlying http library calls getStatusCode method of a response multiple times. For a
    // response, the method should return the same value. Therefore this test cannot rely on
    // `mockLowLevelResponse` variable that are reused across responses.
    when(mockLowLevelRequest.execute()).thenAnswer(new Answer<MockLowLevelHttpResponse>() {

        int n = 0;

        @Override
        public MockLowLevelHttpResponse answer(InvocationOnMock invocation) throws Throwable {
            MockLowLevelHttpResponse response = mock(MockLowLevelHttpResponse.class);
            responses.add(response);
            when(response.getStatusCode()).thenReturn(n++ < retries ? 503 : 9999);
            return response;
        }
    });
    Storage.Buckets.Get result = storage.buckets().get("test");
    try {
        result.executeUnparsed();
        fail();
    } catch (IOException e) {
    }
    verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class));
    verify(mockLowLevelRequest, atLeastOnce()).addHeader(anyString(), anyString());
    verify(mockLowLevelRequest, times(retries + 1)).setTimeout(anyInt(), anyInt());
    verify(mockLowLevelRequest, times(retries + 1)).setWriteTimeout(anyInt());
    verify(mockLowLevelRequest, times(retries + 1)).execute();
    assertThat(responses, Matchers.hasSize(retries + 1));
    for (MockLowLevelHttpResponse response : responses) {
        verify(response, atLeastOnce()).getStatusCode();
    }
    expectedLogs.verifyWarn("performed 10 retries due to unsuccessful status codes");
}
Also used : MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ArrayList(java.util.ArrayList) HttpResponse(com.google.api.client.http.HttpResponse) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse) IOException(java.io.IOException) Test(org.junit.Test)

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