use of com.google.api.client.testing.http.MockHttpTransport 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.MockHttpTransport in project beam by apache.
the class RetryHttpRequestInitializerTest method testIOExceptionHandlerIsInvokedOnTimeout.
/**
* Tests that when RPCs fail with {@link SocketTimeoutException}, the IO exception handler
* is invoked.
*/
@Test
public void testIOExceptionHandlerIsInvokedOnTimeout() throws Exception {
// Counts the number of calls to execute the HTTP request.
final AtomicLong executeCount = new AtomicLong();
// 10 is a private internal constant in the Google API Client library. See
// com.google.api.client.http.HttpRequest#setNumberOfRetries
// TODO: update this test once the private internal constant is public.
final int defaultNumberOfRetries = 10;
// A mock HTTP request that always throws SocketTimeoutException.
MockHttpTransport transport = new MockHttpTransport.Builder().setLowLevelHttpRequest(new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
executeCount.incrementAndGet();
throw new SocketTimeoutException("Fake forced timeout exception");
}
}).build();
// A sample HTTP request to Google Cloud Storage that uses both default Transport and default
// RetryHttpInitializer.
Storage storage = new Storage.Builder(transport, Transport.getJsonFactory(), new RetryHttpRequestInitializer()).build();
Get getRequest = storage.objects().get("gs://fake", "file");
try {
getRequest.execute();
fail();
} catch (Throwable e) {
assertThat(e, Matchers.<Throwable>instanceOf(SocketTimeoutException.class));
assertEquals(1 + defaultNumberOfRetries, executeCount.get());
}
}
use of com.google.api.client.testing.http.MockHttpTransport 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.MockHttpTransport in project copybara by google.
the class GerritApiTest method setUp.
@Before
public void setUp() throws Exception {
OptionsBuilder options = new OptionsBuilder().setWorkdirToRealTempDir().setEnvironment(GitTestUtil.getGitEnv()).setOutputRootToTmpDir();
credentialsFile = Files.createTempFile("credentials", "test");
Files.write(credentialsFile, "https://user:SECRET@copybara-not-real.com".getBytes(UTF_8));
GitRepository repo = newBareRepo(Files.createTempDirectory("test_repo"), getGitEnv(), /*verbose=*/
true).init().withCredentialHelper("store --file=" + credentialsFile);
httpTransport = new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
String requestString = method + " " + url;
MockLowLevelHttpRequest request = new MockLowLevelHttpRequest();
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
request.setResponse(response);
for (Entry<Predicate<String>, byte[]> entry : requestToResponse.entrySet()) {
if (entry.getKey().test(requestString)) {
byte[] content = entry.getValue();
assertWithMessage("'" + method + " " + url + "'").that(content).isNotNull();
response.setContent(content);
return request;
}
}
response.setStatusCode(404);
response.setContent(("NO URL MATCHED! (Returning 404) REQUEST: " + requestString));
return request;
}
};
GerritOptions gerritOptions = new GerritOptions(() -> options.general, options.git) {
@Override
protected HttpTransport getHttpTransport() {
return httpTransport;
}
@Override
protected GitRepository getCredentialsRepo() throws RepoException {
return repo;
}
};
gerritApi = gerritOptions.newGerritApi(getHost() + "/foo/bar/baz");
}
use of com.google.api.client.testing.http.MockHttpTransport in project copybara by google.
the class GithubApiTest method getTransport.
@Override
public GitHubApiTransport getTransport() throws Exception {
credentialsFile = Files.createTempFile("credentials", "test");
Files.write(credentialsFile, "https://user:SECRET@github.com".getBytes(UTF_8));
GitRepository repo = newBareRepo(Files.createTempDirectory("test_repo"), getGitEnv(), /*verbose=*/
true).init().withCredentialHelper("store --file=" + credentialsFile);
requestToResponse = new HashMap<>();
requestValidators = new HashMap<>();
httpTransport = new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
String requestString = method + " " + url;
MockLowLevelHttpRequest request = new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
Predicate<String> validator = requestValidators.get(method + " " + url);
if (validator != null) {
assertWithMessage("Request content did not match expected values.").that(validator.test(getContentAsString())).isTrue();
}
return super.execute();
}
};
byte[] content = requestToResponse.get(requestString);
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
if (content == null) {
response.setContent(String.format("{ 'message' : 'This is not the repo you are looking for! %s %s'," + " 'documentation_url' : 'http://github.com/some_url'}", method, url));
response.setStatusCode(404);
} else {
response.setContent(content);
}
request.setResponse(response);
return request;
}
};
return new GitHubApiTransportImpl(repo, httpTransport, "some_storage_file", new TestingConsole());
}
Aggregations