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);
}
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")));
}
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);
}
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");
}
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");
}
Aggregations