Search in sources :

Example 11 with MockLowLevelHttpResponse

use of com.google.api.client.testing.http.MockLowLevelHttpResponse in project java-docs-samples by GoogleCloudPlatform.

the class TextAppTest method setUp.

@Before
public void setUp() throws Exception {
    // Mock out the vision service for unit tests.
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpTransport transport = new MockHttpTransport() {

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

                @Override
                public LowLevelHttpResponse execute() throws IOException {
                    MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                    response.setStatusCode(200);
                    response.setContentType(Json.MEDIA_TYPE);
                    response.setContent("{\"responses\": [{\"textAnnotations\": []}]}");
                    return response;
                }
            };
        }
    };
    Vision vision = new Vision(transport, jsonFactory, null);
    appUnderTest = new TextApp(vision, null);
}
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) Vision(com.google.api.services.vision.v1.Vision) JsonFactory(com.google.api.client.json.JsonFactory) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Before(org.junit.Before)

Example 12 with MockLowLevelHttpResponse

use of com.google.api.client.testing.http.MockLowLevelHttpResponse in project scout.rt by eclipse.

the class HttpServiceTunnelTest method testTunnel.

@Test
public void testTunnel() throws IOException {
    when(mockUrl.getValue()).thenReturn("http://localhost");
    final MockLowLevelHttpResponse expectedResponse = new MockLowLevelHttpResponse().setContent(getInputStream(new ServiceTunnelResponse("testData", new Object[] {})));
    HttpServiceTunnel tunnel = new HttpServiceTunnel() {

        @Override
        protected IHttpTransportManager getHttpTransportManager() {
            return new IHttpTransportManager() {

                private MockHttpTransport m_transport = new MockHttpTransport.Builder().setLowLevelHttpResponse(expectedResponse).build();

                @Override
                public HttpTransport getHttpTransport() {
                    return m_transport;
                }

                @Override
                public HttpRequestFactory getHttpRequestFactory() {
                    return m_transport.createRequestFactory();
                }

                @Override
                public void interceptNewHttpTransport(IHttpTransportBuilder builder) {
                // nop
                }
            };
        }
    };
    tunnel.setContentHandler(getTestContentHandler());
    ServiceTunnelRequest request = new ServiceTunnelRequest("IPingService", "ping", null, null);
    ServiceTunnelResponse response = tunnel.tunnel(request);
    assertNotNull(response);
}
Also used : MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) IHttpTransportManager(org.eclipse.scout.rt.shared.http.IHttpTransportManager) ServiceTunnelRequest(org.eclipse.scout.rt.shared.servicetunnel.ServiceTunnelRequest) ServiceTunnelResponse(org.eclipse.scout.rt.shared.servicetunnel.ServiceTunnelResponse) IHttpTransportBuilder(org.eclipse.scout.rt.shared.http.IHttpTransportBuilder) Test(org.junit.Test)

Example 13 with MockLowLevelHttpResponse

use of com.google.api.client.testing.http.MockLowLevelHttpResponse in project tink by google.

the class PaymentMethodTokenRecipientTest method testShouldDecryptV1WhenFetchingSenderVerifyingKeys.

@Test
public void testShouldDecryptV1WhenFetchingSenderVerifyingKeys() throws Exception {
    PaymentMethodTokenRecipient recipient = new PaymentMethodTokenRecipient.Builder().fetchSenderVerifyingKeysWith(new GooglePaymentsPublicKeysManager.Builder().setHttpTransport(new MockHttpTransport.Builder().setLowLevelHttpResponse(new MockLowLevelHttpResponse().setContent(GOOGLE_VERIFYING_PUBLIC_KEYS_JSON)).build()).build()).recipientId(RECIPIENT_ID).addRecipientPrivateKey(MERCHANT_PRIVATE_KEY_PKCS8_BASE64).build();
    assertEquals(PLAINTEXT, recipient.unseal(CIPHERTEXT_EC_V1));
}
Also used : MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) Test(org.junit.Test)

Example 14 with MockLowLevelHttpResponse

use of com.google.api.client.testing.http.MockLowLevelHttpResponse 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 15 with MockLowLevelHttpResponse

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

the class ServiceAccountCredentialsTest method refreshAccessToken_failsNotFoundError.

@Test
public void refreshAccessToken_failsNotFoundError() throws IOException {
    final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2";
    final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2";
    MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory();
    MockTokenServerTransport transport = transportFactory.transport;
    ServiceAccountCredentials credentials = ServiceAccountCredentials.fromPkcs8(SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID, SCOPES, transportFactory, null);
    transport.addServiceAccount(SA_CLIENT_EMAIL, accessToken1);
    TestUtils.assertContainsBearerToken(credentials.getRequestMetadata(CALL_URI), accessToken1);
    try {
        transport.addResponseSequence(new MockLowLevelHttpResponse().setStatusCode(404));
        transport.addServiceAccount(SA_CLIENT_EMAIL, accessToken2);
        credentials.refresh();
        fail("Should not retry on Not Found");
    } catch (IOException expected) {
    // Expected
    }
}
Also used : MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) MockTokenServerTransportFactory(com.google.auth.oauth2.GoogleCredentialsTest.MockTokenServerTransportFactory) IOException(java.io.IOException) Test(org.junit.Test)

Aggregations

MockLowLevelHttpResponse (com.google.api.client.testing.http.MockLowLevelHttpResponse)63 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)40 MockLowLevelHttpRequest (com.google.api.client.testing.http.MockLowLevelHttpRequest)38 Test (org.junit.Test)31 LowLevelHttpResponse (com.google.api.client.http.LowLevelHttpResponse)24 LowLevelHttpRequest (com.google.api.client.http.LowLevelHttpRequest)22 IOException (java.io.IOException)21 HttpTransport (com.google.api.client.http.HttpTransport)10 GenericJson (com.google.api.client.json.GenericJson)9 HttpResponse (com.google.api.client.http.HttpResponse)8 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)8 JsonFactory (com.google.api.client.json.JsonFactory)7 HttpRequest (com.google.api.client.http.HttpRequest)6 GenericUrl (com.google.api.client.http.GenericUrl)5 Objectify (com.googlecode.objectify.Objectify)5 Storage (com.google.api.services.storage.Storage)4 TestingConsole (com.google.copybara.util.console.testing.TestingConsole)4 ErrorInfo (com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo)3 MockGoogleClient (com.google.api.client.googleapis.testing.services.MockGoogleClient)3 MockGoogleClientRequest (com.google.api.client.googleapis.testing.services.MockGoogleClientRequest)3