use of com.google.api.client.testing.http.MockLowLevelHttpRequest 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.MockLowLevelHttpRequest 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.MockLowLevelHttpRequest in project copybara by google.
the class GithubPrDestinationTest method testCustomTitleAndBody.
@Test
public void testCustomTitleAndBody() throws ValidationException, IOException, RepoException {
options.githubDestination.destinationPrBranch = "feature";
gitApiMockHttpTransport = new GitApiMockHttpTransport() {
@Override
protected byte[] getContent(String method, String url, MockLowLevelHttpRequest request) throws IOException {
boolean isPulls = "https://api.github.com/repos/foo/pulls".equals(url);
if ("GET".equals(method) && isPulls) {
return "[]".getBytes(UTF_8);
} else if ("POST".equals(method) && isPulls) {
assertThat(request.getContentAsString()).isEqualTo("{\"base\":\"master\"," + "\"body\":\"custom body\"," + "\"head\":\"feature\"," + "\"title\":\"custom title\"}");
return ("{\n" + " \"id\": 1,\n" + " \"number\": 12345,\n" + " \"state\": \"open\",\n" + " \"title\": \"custom title\",\n" + " \"body\": \"custom body\"" + "}").getBytes();
}
fail(method + " " + url);
throw new IllegalStateException();
}
};
GithubPrDestination d = skylark.eval("r", "r = git.github_pr_destination(" + " url = 'https://github.com/foo', \n" + " title = 'custom title',\n" + " body = 'custom body',\n" + ")");
Writer<GitRevision> writer = d.newWriter(Glob.ALL_FILES, /*dryRun=*/
false, null, /*oldWriter=*/
null);
GitRepository remote = localHubRepo("foo");
addFiles(remote, null, "first change", ImmutableMap.<String, String>builder().put("foo.txt", "").build());
Files.write(this.workdir.resolve("test.txt"), "some content".getBytes());
writer.write(TransformResults.of(this.workdir, new DummyRevision("one")), console);
}
use of com.google.api.client.testing.http.MockLowLevelHttpRequest in project copybara by google.
the class GerritDestinationTest method reuseChangeId.
@Test
public void reuseChangeId() throws Exception {
fetch = "master";
Files.write(workdir.resolve("file"), "some content".getBytes());
options.setForce(true);
options.gerrit.gerritChangeId = null;
url = "https://localhost:33333/foo/bar";
GitRepository repo = localGerritRepo("localhost:33333/foo/bar");
gitApiMockHttpTransport = NO_CHANGE_FOUND_MOCK;
process(new DummyRevision("origin_ref"));
String changeId = lastCommitChangeIdLine("origin_ref", repo);
assertThat(changeId).matches(GerritDestination.CHANGE_ID_LABEL + ": I[a-z0-9]+");
LabelFinder labelFinder = new LabelFinder(changeId);
Files.write(workdir.resolve("file"), "some different content".getBytes());
gitApiMockHttpTransport = new GitApiMockHttpTransport() {
@Override
protected byte[] getContent(String method, String url, MockLowLevelHttpRequest request) throws IOException {
String expected = "https://localhost:33333/changes/?q=change:%20" + labelFinder.getValue() + "%20AND%20project:foo/bar";
if (method.equals("GET") && url.equals(expected)) {
String result = "[" + "{" + " change_id : \"" + labelFinder.getValue() + "\"," + " status : \"NEW\"" + "}]";
return result.getBytes(UTF_8);
}
throw new IllegalArgumentException(method + " " + url);
}
};
// Allow to push again in a non-fastforward way.
repo.simpleCommand("update-ref", "-d", "refs/for/master");
process(new DummyRevision("origin_ref"));
assertThat(lastCommitChangeIdLine("origin_ref", repo)).isEqualTo(changeId);
GitTesting.assertThatCheckout(repo, "refs/for/master").containsFile("file", "some different content").containsNoMoreFiles();
}
use of com.google.api.client.testing.http.MockLowLevelHttpRequest in project copybara by google.
the class GerritDestinationTest method setup.
@Before
public void setup() throws Exception {
workdir = Files.createTempDirectory("workdir");
console = new TestingConsole();
options = new OptionsBuilder().setConsole(console).setOutputRootToTmpDir();
urlMapper = Files.createTempDirectory("url_mapper");
options.git = new TestGitOptions(urlMapper, () -> options.general);
options.gerrit = new GerritOptions(() -> options.general, options.git) {
@Override
protected GerritApiTransportImpl getGerritApiTransport(URI uri) throws RepoException {
return new GerritApiTransportImpl(repo(), uri, gitApiMockHttpTransport);
}
};
options.gitDestination = new GitDestinationOptions(() -> options.general, options.git);
options.gitDestination.committerEmail = "commiter@email";
options.gitDestination.committerName = "Bara Kopi";
excludedDestinationPaths = ImmutableList.of();
repoGitDir = localGerritRepo("localhost:33333/foo/bar").getGitDir();
url = "https://localhost:33333/foo/bar";
repo().init();
skylark = new SkylarkTestExecutor(options, GitModule.class);
gitApiMockHttpTransport = new GitApiMockHttpTransport() {
@Override
protected byte[] getContent(String method, String url, MockLowLevelHttpRequest request) throws IOException {
if (method.equals("GET") && url.startsWith("https://localhost:33333/changes/")) {
String result = "[" + "{" + " change_id : \"" + changeIdFromRequest(url) + "\"," + " status : \"NEW\"" + "}]";
return result.getBytes(UTF_8);
}
throw new IllegalArgumentException(method + " " + url);
}
};
}
Aggregations