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