Search in sources :

Example 1 with MockLowLevelHttpRequest

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);
}
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 2 with MockLowLevelHttpRequest

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());
    }
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) SocketTimeoutException(java.net.SocketTimeoutException) Storage(com.google.api.services.storage.Storage) Get(com.google.api.services.storage.Storage.Objects.Get) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Test(org.junit.Test)

Example 3 with MockLowLevelHttpRequest

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);
}
Also used : DummyRevision(com.google.copybara.testing.DummyRevision) GitApiMockHttpTransport(com.google.copybara.testing.OptionsBuilder.GitApiMockHttpTransport) IOException(java.io.IOException) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Test(org.junit.Test)

Example 4 with MockLowLevelHttpRequest

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();
}
Also used : DummyRevision(com.google.copybara.testing.DummyRevision) GitApiMockHttpTransport(com.google.copybara.testing.OptionsBuilder.GitApiMockHttpTransport) LabelFinder(com.google.copybara.LabelFinder) IOException(java.io.IOException) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Test(org.junit.Test)

Example 5 with MockLowLevelHttpRequest

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);
        }
    };
}
Also used : TestGitOptions(com.google.copybara.testing.git.GitTestUtil.TestGitOptions) RepoException(com.google.copybara.exception.RepoException) IOException(java.io.IOException) URI(java.net.URI) OptionsBuilder(com.google.copybara.testing.OptionsBuilder) SkylarkTestExecutor(com.google.copybara.testing.SkylarkTestExecutor) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) TestingConsole(com.google.copybara.util.console.testing.TestingConsole) GerritApiTransportImpl(com.google.copybara.git.gerritapi.GerritApiTransportImpl) GitApiMockHttpTransport(com.google.copybara.testing.OptionsBuilder.GitApiMockHttpTransport) Before(org.junit.Before)

Aggregations

MockLowLevelHttpRequest (com.google.api.client.testing.http.MockLowLevelHttpRequest)46 MockLowLevelHttpResponse (com.google.api.client.testing.http.MockLowLevelHttpResponse)35 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)33 IOException (java.io.IOException)27 Test (org.junit.Test)25 LowLevelHttpResponse (com.google.api.client.http.LowLevelHttpResponse)23 LowLevelHttpRequest (com.google.api.client.http.LowLevelHttpRequest)18 GenericJson (com.google.api.client.json.GenericJson)10 HttpTransport (com.google.api.client.http.HttpTransport)9 JsonFactory (com.google.api.client.json.JsonFactory)8 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)8 GitApiMockHttpTransport (com.google.copybara.testing.OptionsBuilder.GitApiMockHttpTransport)8 DummyRevision (com.google.copybara.testing.DummyRevision)6 Storage (com.google.api.services.storage.Storage)5 Objectify (com.googlecode.objectify.Objectify)5 HttpRequest (com.google.api.client.http.HttpRequest)4 HttpResponse (com.google.api.client.http.HttpResponse)4 Before (org.junit.Before)4 ErrorInfo (com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo)3 MockGoogleClient (com.google.api.client.googleapis.testing.services.MockGoogleClient)3