Search in sources :

Example 16 with MockLowLevelHttpRequest

use of com.google.api.client.testing.http.MockLowLevelHttpRequest in project google-auth-library-java by google.

the class MockTokenServerTransport method buildRequest.

@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
    buildRequestCount++;
    if (error != null) {
        throw error;
    }
    int questionMarkPos = url.indexOf('?');
    final String urlWithoutQUery = (questionMarkPos > 0) ? url.substring(0, questionMarkPos) : url;
    final String query = (questionMarkPos > 0) ? url.substring(questionMarkPos + 1) : "";
    if (urlWithoutQUery.equals(tokenServerUri.toString())) {
        return new MockLowLevelHttpRequest(url) {

            @Override
            public LowLevelHttpResponse execute() throws IOException {
                IOException responseError = responseErrorSequence.poll();
                if (responseError != null) {
                    throw responseError;
                }
                LowLevelHttpResponse response = responseSequence.poll();
                if (response != null) {
                    return response;
                }
                String content = this.getContentAsString();
                Map<String, String> query = TestUtils.parseQuery(content);
                String accessToken;
                String refreshToken = null;
                String foundId = query.get("client_id");
                if (foundId != null) {
                    if (!clients.containsKey(foundId)) {
                        throw new IOException("Client ID not found.");
                    }
                    String foundSecret = query.get("client_secret");
                    String expectedSecret = clients.get(foundId);
                    if (foundSecret == null || !foundSecret.equals(expectedSecret)) {
                        throw new IOException("Client secret not found.");
                    }
                    String grantType = query.get("grant_type");
                    if (grantType != null && grantType.equals("authorization_code")) {
                        String foundCode = query.get("code");
                        if (!codes.containsKey(foundCode)) {
                            throw new IOException("Authorization code not found");
                        }
                        refreshToken = codes.get(foundCode);
                    } else {
                        refreshToken = query.get("refresh_token");
                    }
                    if (!refreshTokens.containsKey(refreshToken)) {
                        throw new IOException("Refresh Token not found.");
                    }
                    accessToken = refreshTokens.get(refreshToken);
                } else if (query.containsKey("grant_type")) {
                    String grantType = query.get("grant_type");
                    if (!EXPECTED_GRANT_TYPE.equals(grantType)) {
                        throw new IOException("Unexpected Grant Type.");
                    }
                    String assertion = query.get("assertion");
                    JsonWebSignature signature = JsonWebSignature.parse(JSON_FACTORY, assertion);
                    String foundEmail = signature.getPayload().getIssuer();
                    if (!serviceAccounts.containsKey(foundEmail)) {
                        throw new IOException("Service Account Email not found as issuer.");
                    }
                    accessToken = serviceAccounts.get(foundEmail);
                    String foundScopes = (String) signature.getPayload().get("scope");
                    if (foundScopes == null || foundScopes.length() == 0) {
                        throw new IOException("Scopes not found.");
                    }
                } else {
                    throw new IOException("Unknown token type.");
                }
                // Create the JSON response
                GenericJson refreshContents = new GenericJson();
                refreshContents.setFactory(JSON_FACTORY);
                refreshContents.put("access_token", accessToken);
                refreshContents.put("expires_in", expiresInSeconds);
                refreshContents.put("token_type", "Bearer");
                if (refreshToken != null) {
                    refreshContents.put("refresh_token", refreshToken);
                }
                String refreshText = refreshContents.toPrettyString();
                return new MockLowLevelHttpResponse().setContentType(Json.MEDIA_TYPE).setContent(refreshText);
            }
        };
    } else if (urlWithoutQUery.equals(OAuth2Utils.TOKEN_REVOKE_URI.toString())) {
        return new MockLowLevelHttpRequest(url) {

            @Override
            public LowLevelHttpResponse execute() throws IOException {
                Map<String, String> parameters = TestUtils.parseQuery(query);
                String token = parameters.get("token");
                if (token == null) {
                    throw new IOException("Token to revoke not found.");
                }
                // Token could be access token or refresh token so remove keys and values
                refreshTokens.values().removeAll(Collections.singleton(token));
                refreshTokens.remove(token);
                return new MockLowLevelHttpResponse().setContentType(Json.MEDIA_TYPE);
            }
        };
    }
    return super.buildRequest(method, url);
}
Also used : GenericJson(com.google.api.client.json.GenericJson) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) JsonWebSignature(com.google.api.client.json.webtoken.JsonWebSignature) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest)

Example 17 with MockLowLevelHttpRequest

use of com.google.api.client.testing.http.MockLowLevelHttpRequest in project google-api-java-client by google.

the class AbstractGoogleJsonClientTest method testExecuteUnparsed_error.

public void testExecuteUnparsed_error() throws Exception {
    HttpTransport transport = new MockHttpTransport() {

        @Override
        public LowLevelHttpRequest buildRequest(String name, String url) {
            return new MockLowLevelHttpRequest() {

                @Override
                public LowLevelHttpResponse execute() {
                    MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
                    result.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
                    result.setContentType(Json.MEDIA_TYPE);
                    result.setContent("{\"error\":{\"code\":401,\"errors\":[{\"domain\":\"global\"," + "\"location\":\"Authorization\",\"locationType\":\"header\"," + "\"message\":\"me\",\"reason\":\"authError\"}],\"message\":\"me\"}}");
                    return result;
                }
            };
        }
    };
    JsonFactory jsonFactory = new JacksonFactory();
    MockGoogleJsonClient client = new MockGoogleJsonClient.Builder(transport, jsonFactory, HttpTesting.SIMPLE_URL, "", null, false).setApplicationName("Test Application").build();
    MockGoogleJsonClientRequest<String> request = new MockGoogleJsonClientRequest<String>(client, "GET", "foo", null, String.class);
    try {
        request.executeUnparsed();
        fail("expected " + GoogleJsonResponseException.class);
    } catch (GoogleJsonResponseException e) {
        // expected
        GoogleJsonError details = e.getDetails();
        assertEquals("me", details.getMessage());
        assertEquals("me", details.getErrors().get(0).getMessage());
    }
}
Also used : MockGoogleJsonClientRequest(com.google.api.client.googleapis.testing.services.json.MockGoogleJsonClientRequest) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) JsonFactory(com.google.api.client.json.JsonFactory) MockGoogleJsonClient(com.google.api.client.googleapis.testing.services.json.MockGoogleJsonClient) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) HttpTransport(com.google.api.client.http.HttpTransport) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) GoogleJsonError(com.google.api.client.googleapis.json.GoogleJsonError)

Example 18 with MockLowLevelHttpRequest

use of com.google.api.client.testing.http.MockLowLevelHttpRequest in project google-api-java-client by google.

the class AbstractGoogleClientRequestTest method testExecuteUnparsed_error.

public void testExecuteUnparsed_error() throws Exception {
    HttpTransport transport = new MockHttpTransport() {

        @Override
        public LowLevelHttpRequest buildRequest(final String method, final String url) {
            return new MockLowLevelHttpRequest() {

                @Override
                public LowLevelHttpResponse execute() {
                    assertEquals("GET", method);
                    assertEquals("https://www.googleapis.com/test/path/v1/tests/foo", url);
                    MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
                    result.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
                    result.setContentType(Json.MEDIA_TYPE);
                    result.setContent(ERROR_CONTENT);
                    return result;
                }
            };
        }
    };
    MockGoogleClient client = new MockGoogleClient.Builder(transport, ROOT_URL, SERVICE_PATH, JSON_OBJECT_PARSER, null).setApplicationName("Test Application").build();
    MockGoogleClientRequest<String> request = new MockGoogleClientRequest<String>(client, HttpMethods.GET, URI_TEMPLATE, null, String.class);
    try {
        request.put("testId", "foo");
        request.executeUnparsed();
        fail("expected " + HttpResponseException.class);
    } catch (HttpResponseException e) {
        // expected
        assertEquals("401" + StringUtils.LINE_SEPARATOR + ERROR_CONTENT, e.getMessage());
    }
}
Also used : MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) HttpTransport(com.google.api.client.http.HttpTransport) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) MockGoogleClient(com.google.api.client.googleapis.testing.services.MockGoogleClient) MockGoogleClientRequest(com.google.api.client.googleapis.testing.services.MockGoogleClientRequest) HttpResponseException(com.google.api.client.http.HttpResponseException) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest)

Example 19 with MockLowLevelHttpRequest

use of com.google.api.client.testing.http.MockLowLevelHttpRequest in project google-api-java-client by google.

the class MockTokenServerTransport method buildRequest.

@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
    if (url.equals(tokenServerUrl)) {
        MockLowLevelHttpRequest request = new MockLowLevelHttpRequest(url) {

            @Override
            public LowLevelHttpResponse execute() throws IOException {
                String content = this.getContentAsString();
                Map<String, String> query = TestUtils.parseQuery(content);
                String accessToken = null;
                String foundId = query.get("client_id");
                if (foundId != null) {
                    if (!clients.containsKey(foundId)) {
                        throw new IOException("Client ID not found.");
                    }
                    String foundSecret = query.get("client_secret");
                    String expectedSecret = clients.get(foundId);
                    if (foundSecret == null || !foundSecret.equals(expectedSecret)) {
                        throw new IOException("Client secret not found.");
                    }
                    String foundRefresh = query.get("refresh_token");
                    if (!refreshTokens.containsKey(foundRefresh)) {
                        throw new IOException("Refresh Token not found.");
                    }
                    accessToken = refreshTokens.get(foundRefresh);
                } else if (query.containsKey("grant_type")) {
                    String grantType = query.get("grant_type");
                    if (!EXPECTED_GRANT_TYPE.equals(grantType)) {
                        throw new IOException("Unexpected Grant Type.");
                    }
                    String assertion = query.get("assertion");
                    JsonWebSignature signature = JsonWebSignature.parse(JSON_FACTORY, assertion);
                    String foundEmail = signature.getPayload().getIssuer();
                    if (!serviceAccounts.containsKey(foundEmail)) {
                        throw new IOException("Service Account Email not found as issuer.");
                    }
                    accessToken = serviceAccounts.get(foundEmail);
                    String foundScopes = (String) signature.getPayload().get("scope");
                    if (foundScopes == null || foundScopes.length() == 0) {
                        throw new IOException("Scopes not found.");
                    }
                } else {
                    throw new IOException("Unknown token type.");
                }
                // Create the JSon response
                GenericJson refreshContents = new GenericJson();
                refreshContents.setFactory(JSON_FACTORY);
                refreshContents.put("access_token", accessToken);
                refreshContents.put("expires_in", 3600000);
                refreshContents.put("token_type", "Bearer");
                String refreshText = refreshContents.toPrettyString();
                MockLowLevelHttpResponse response = new MockLowLevelHttpResponse().setContentType(Json.MEDIA_TYPE).setContent(refreshText);
                return response;
            }
        };
        return request;
    }
    return super.buildRequest(method, url);
}
Also used : GenericJson(com.google.api.client.json.GenericJson) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) JsonWebSignature(com.google.api.client.json.webtoken.JsonWebSignature) IOException(java.io.IOException) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest)

Example 20 with MockLowLevelHttpRequest

use of com.google.api.client.testing.http.MockLowLevelHttpRequest in project druid by druid-io.

the class GoogleStorageTest method testInsert.

@Test
public void testInsert() throws IOException {
    String content = "abcdefghij";
    MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
    response.addHeader("Location", "http://random-path");
    response.setContent("{}");
    MockHttpTransport transport = new MockHttpTransport.Builder().setLowLevelHttpResponse(response).build();
    GoogleStorage googleStorage = makeGoogleStorage(transport);
    googleStorage.insert("bucket", "path", new ByteArrayContent("text/html", StringUtils.toUtf8(content)));
    MockLowLevelHttpRequest request = transport.getLowLevelHttpRequest();
    String actual = request.getContentAsString();
    Assert.assertEquals(content, actual);
}
Also used : MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) ByteArrayContent(com.google.api.client.http.ByteArrayContent) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Test(org.junit.Test)

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