Search in sources :

Example 1 with MockHttpTransport

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);
}
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 MockHttpTransport

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());
    }
}
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 MockHttpTransport

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")));
}
Also used : GenericJson(com.google.api.client.json.GenericJson) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) Storage(com.google.api.services.storage.Storage) JsonFactory(com.google.api.client.json.JsonFactory) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) Test(org.junit.Test)

Example 4 with MockHttpTransport

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");
}
Also used : GitRepository(com.google.copybara.git.GitRepository) Entry(java.util.Map.Entry) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) LowLevelHttpRequest(com.google.api.client.http.LowLevelHttpRequest) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) GerritOptions(com.google.copybara.git.GerritOptions) IOException(java.io.IOException) OptionsBuilder(com.google.copybara.testing.OptionsBuilder) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Before(org.junit.Before)

Example 5 with MockHttpTransport

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());
}
Also used : MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) LowLevelHttpRequest(com.google.api.client.http.LowLevelHttpRequest) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) IOException(java.io.IOException) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Predicate(java.util.function.Predicate) GitRepository(com.google.copybara.git.GitRepository) TestingConsole(com.google.copybara.util.console.testing.TestingConsole) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse)

Aggregations

MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)75 MockLowLevelHttpRequest (com.google.api.client.testing.http.MockLowLevelHttpRequest)36 MockLowLevelHttpResponse (com.google.api.client.testing.http.MockLowLevelHttpResponse)36 HttpTransport (com.google.api.client.http.HttpTransport)29 Test (org.junit.Test)27 IOException (java.io.IOException)25 LowLevelHttpRequest (com.google.api.client.http.LowLevelHttpRequest)21 LowLevelHttpResponse (com.google.api.client.http.LowLevelHttpResponse)20 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)18 HttpRequest (com.google.api.client.http.HttpRequest)13 JsonFactory (com.google.api.client.json.JsonFactory)13 GenericJson (com.google.api.client.json.GenericJson)12 Storage (com.google.api.services.storage.Storage)9 HttpResponse (com.google.api.client.http.HttpResponse)7 MockGoogleClient (com.google.api.client.googleapis.testing.services.MockGoogleClient)6 MockGoogleClientRequest (com.google.api.client.googleapis.testing.services.MockGoogleClientRequest)5 GenericUrl (com.google.api.client.http.GenericUrl)5 Objectify (com.googlecode.objectify.Objectify)5 ByteArrayInputStream (java.io.ByteArrayInputStream)5 MockTokenServerTransport (com.google.api.client.googleapis.testing.auth.oauth2.MockTokenServerTransport)4