com.google.api.client.testing.http.MockLowLevelHttpResponse Java Examples

The following examples show how to use com.google.api.client.testing.http.MockLowLevelHttpResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IcannHttpReporterTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private MockHttpTransport createMockTransport (final ByteSource iirdeaResponse) {
  return new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      mockRequest = new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(200);
          response.setContentType(PLAIN_TEXT_UTF_8.toString());
          response.setContent(iirdeaResponse.read());
          return response;
        }
      };
      mockRequest.setUrl(url);
      return mockRequest;
    }
  };
}
 
Example #2
Source File: TestingHttpTransport.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Convert the passed Json "result" to a response.
 *
 * <p>A {@code null} result will be converted to a successful response. An error response will
 * be generated only if the {@code result} is a {@link GoogleJsonError}.
 *
 * @param result the Json execute result.
 * @return the converted response of the result.
 * @throws IOException
 */
private MockLowLevelHttpResponse getResponse(GenericJson result) throws IOException {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  if (result instanceof GoogleJsonError) {
    GoogleJsonError error = (GoogleJsonError) result;
    String errorContent = JSON_FACTORY.toString(new GenericJson().set("error", error));
    response
        .setStatusCode(error.getCode())
        .setReasonPhrase(error.getMessage())
        .setContentType(Json.MEDIA_TYPE)
        .setContent(errorContent);
  } else {
    response
        .setStatusCode(HTTP_OK)
        .setContentType(Json.MEDIA_TYPE)
        .setContent(result == null ? "" : JSON_FACTORY.toString(result));
  }
  return response;
}
 
Example #3
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testGetContent_otherEncodingWithgzipInItsName_GzipIsNotUsed() throws IOException {
  final MockLowLevelHttpResponse mockResponse = new MockLowLevelHttpResponse();
  mockResponse.setContent("abcd");
  mockResponse.setContentEncoding("otherEncodingWithgzipInItsName");
  mockResponse.setContentType("text/plain");

  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, final String url)
            throws IOException {
          return new MockLowLevelHttpRequest() {
            @Override
            public LowLevelHttpResponse execute() throws IOException {
              return mockResponse;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildHeadRequest(HttpTesting.SIMPLE_GENERIC_URL);
  // If gzip was used on this response, an exception would be thrown
  HttpResponse response = request.execute();
  assertEquals("abcd", response.parseAsString());
}
 
Example #4
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testGetContent_gzipNoContent() throws IOException {
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, final String url)
            throws IOException {
          return new MockLowLevelHttpRequest() {
            @Override
            public LowLevelHttpResponse execute() throws IOException {
              MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
              result.setContent("");
              result.setContentEncoding("gzip");
              result.setContentType("text/plain");
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildHeadRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.execute().getContent();
}
 
Example #5
Source File: RetryDeterminerTest.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
HttpResponseException makeHttpException(int status) throws IOException {
  MockHttpTransport.Builder builder = new MockHttpTransport.Builder();
  MockLowLevelHttpResponse resp = new MockLowLevelHttpResponse();
  resp.setStatusCode(status);
  builder.setLowLevelHttpResponse(resp);
  try {
    HttpResponse res =
        builder.build()
            .createRequestFactory()
            .buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL)
            .execute();
    return new HttpResponseException(res);
  } catch (HttpResponseException exception) {
    return exception; // Throws the exception we want anyway, so just return it.
  }
}
 
Example #6
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParseAsString_validContentTypeWithParams() throws Exception {
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          return new MockLowLevelHttpRequest() {
            @Override
            public LowLevelHttpResponse execute() throws IOException {
              MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
              result.setContent(SAMPLE2);
              result.setContentType(VALID_CONTENT_TYPE_WITH_PARAMS);
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);

  HttpResponse response = request.execute();
  assertEquals(SAMPLE2, response.parseAsString());
  assertEquals(VALID_CONTENT_TYPE_WITH_PARAMS, response.getContentType());
  assertNotNull(response.getMediaType());
}
 
Example #7
Source File: FirebaseProjectManagementServiceImplTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpRetries() throws Exception {
  List<MockLowLevelHttpResponse> mockResponses = ImmutableList.of(
      firstRpcResponse.setStatusCode(503).setContent("{}"),
      new MockLowLevelHttpResponse().setContent("{}"));
  MockHttpTransport transport = new MultiRequestMockHttpTransport(mockResponses);
  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(new MockGoogleCredentials("test-token"))
      .setProjectId(PROJECT_ID)
      .setHttpTransport(transport)
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  HttpRequestFactory requestFactory = TestApiClientUtils.delayBypassedRequestFactory(app);
  FirebaseProjectManagementServiceImpl serviceImpl = new FirebaseProjectManagementServiceImpl(
      app, new MockSleeper(), new MockScheduler(), requestFactory);
  serviceImpl.setInterceptor(interceptor);

  serviceImpl.deleteShaCertificate(SHA1_RESOURCE_NAME);

  String expectedUrl = String.format(
      "%s/v1beta1/%s", FIREBASE_PROJECT_MANAGEMENT_URL, SHA1_RESOURCE_NAME);
  checkRequestHeader(expectedUrl, HttpMethod.DELETE);
}
 
Example #8
Source File: CryptoSignersTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetadataService() throws IOException {
  String signature = BaseEncoding.base64().encode("signed-bytes".getBytes());
  String response = Utils.getDefaultJsonFactory().toString(
      ImmutableMap.of("signature", signature));
  MockHttpTransport transport = new MultiRequestMockHttpTransport(
      ImmutableList.of(
          new MockLowLevelHttpResponse().setContent("[email protected]"),
          new MockLowLevelHttpResponse().setContent(response)));
  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(new MockGoogleCredentials("test-token"))
      .setHttpTransport(transport)
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  CryptoSigner signer = CryptoSigners.getCryptoSigner(app);

  assertTrue(signer instanceof CryptoSigners.IAMCryptoSigner);
  TestResponseInterceptor interceptor = new TestResponseInterceptor();
  ((CryptoSigners.IAMCryptoSigner) signer).setInterceptor(interceptor);

  byte[] data = signer.sign("foo".getBytes());
  assertArrayEquals("signed-bytes".getBytes(), data);
  final String url = "https://iam.googleapis.com/v1/projects/-/serviceAccounts/"
      + "[email protected]:signBlob";
  assertEquals(url, interceptor.getResponse().getRequest().getUrl().toString());
}
 
Example #9
Source File: GooglePublicKeysManagerTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String name, String url) {
  return new MockLowLevelHttpRequest() {
      @Override
    public LowLevelHttpResponse execute() {
      MockLowLevelHttpResponse r = new MockLowLevelHttpResponse();
      r.setStatusCode(200);
      r.addHeader("Cache-Control", "max-age=" + MAX_AGE);
      if (useAgeHeader) {
        r.addHeader("Age", String.valueOf(AGE));
      }
      r.setContentType(Json.MEDIA_TYPE);
      r.setContent(TEST_CERTIFICATES);
      return r;
    }
  };
}
 
Example #10
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private static FirebaseAuth getRetryDisabledAuth(MockLowLevelHttpResponse response) {
  final MockHttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpResponse(response)
      .build();
  final FirebaseApp app = FirebaseApp.initializeApp(new FirebaseOptions.Builder()
      .setCredentials(credentials)
      .setProjectId("test-project-id")
      .setHttpTransport(transport)
      .build());
  return FirebaseAuth.builder()
      .setFirebaseApp(app)
      .setUserManager(new Supplier<FirebaseUserManager>() {
        @Override
        public FirebaseUserManager get() {
          return new FirebaseUserManager(app, transport.createRequestFactory());
        }
      })
      .build();
}
 
Example #11
Source File: ApiClientUtilsTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDisconnectWithErrorSuppression() throws IOException {
  MockLowLevelHttpResponse lowLevelResponse = new MockLowLevelHttpResponse(){
    @Override
    public void disconnect() throws IOException {
      super.disconnect();
      throw new IOException("test error");
    }
  };
  MockHttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpResponse(lowLevelResponse)
      .build();
  HttpResponse response = transport.createRequestFactory().buildGetRequest(TEST_URL).execute();
  assertFalse(lowLevelResponse.isDisconnected());

  ApiClientUtils.disconnectQuietly(response);

  assertTrue(lowLevelResponse.isDisconnected());
}
 
Example #12
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParseAsString_validContentType() throws Exception {
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          return new MockLowLevelHttpRequest() {
            @Override
            public LowLevelHttpResponse execute() throws IOException {
              MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
              result.setContent(SAMPLE2);
              result.setContentType(VALID_CONTENT_TYPE);
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);

  HttpResponse response = request.execute();
  assertEquals(SAMPLE2, response.parseAsString());
  assertEquals(VALID_CONTENT_TYPE, response.getContentType());
  assertNotNull(response.getMediaType());
}
 
Example #13
Source File: HttpHeadersTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testFromHttpResponse_doubleConvert() throws Exception {
  MockLowLevelHttpResponse httpResponse =
      new MockLowLevelHttpResponse()
          .setHeaderNames(Arrays.asList("Content-Type", "Slug"))
          .setHeaderValues(Arrays.asList("foo/bar", "123456789"));

  // Test the normal HttpHeaders class
  SlugHeaders slugHeaders = new SlugHeaders();
  slugHeaders.fromHttpResponse(httpResponse, null);
  assertEquals("foo/bar", slugHeaders.getContentType());
  assertEquals("123456789", slugHeaders.slug);

  // Test creating a HttpHeaders obj using the HttpHeaders' data
  SlugHeaders slugHeaders2 = new SlugHeaders();
  slugHeaders2.fromHttpHeaders(slugHeaders);
  assertEquals("foo/bar", slugHeaders2.getContentType());
  assertEquals("123456789", slugHeaders2.slug);
}
 
Example #14
Source File: HttpHeadersTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testFromHttpResponse_normalFlow() throws Exception {
  MockLowLevelHttpResponse httpResponse =
      new MockLowLevelHttpResponse()
          .setHeaderNames(Arrays.asList("Content-Type", "Slug"))
          .setHeaderValues(Arrays.asList("foo/bar", "123456789"));

  // Test the normal HttpHeaders class
  HttpHeaders httpHeaders = new HttpHeaders();
  httpHeaders.fromHttpResponse(httpResponse, null);
  assertEquals("foo/bar", httpHeaders.getContentType());
  assertEquals(ImmutableList.of("123456789"), httpHeaders.get("Slug"));

  // Test creating a SlugHeaders obj using the HttpHeaders' data
  SlugHeaders slugHeaders = new SlugHeaders();
  slugHeaders.fromHttpHeaders(httpHeaders);
  assertEquals("foo/bar", slugHeaders.getContentType());
  assertEquals("123456789", slugHeaders.slug);
}
 
Example #15
Source File: FakeWebServer.java    From healthcare-dicom-dicomweb-adapter with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
  MockLowLevelHttpRequest request = new MockLowLevelHttpRequest(url) {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
      if (responses.isEmpty()) {
        throw new IOException(
            "Unexpected call to execute(), no injected responses left to return.");
      }
      return responses.remove();
    }
  };
  requests.add(new Request(method, request));
  return request;
}
 
Example #16
Source File: CustomTokenRequestTest.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String method, String url) {
  return new MockLowLevelHttpRequest(url) {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
      response.setContentType(Json.MEDIA_TYPE);
      IdTokenResponse json = new IdTokenResponse();
      json.setAccessToken("abc");
      json.setRefreshToken("def");
      json.setExpiresInSeconds(3600L);
      json.setIdToken(JWT_ENCODED_CONTENT);
      response.setContent(JSON_FACTORY.toString(json));
      return response;
    }
  };
}
 
Example #17
Source File: UploadIdResponseInterceptorTest.java    From beam with Apache License 2.0 6 votes vote down vote up
/**
 * Builds an HttpResponse with the given string response.
 *
 * @param header header value to provide or null if none.
 * @param uploadId upload id to provide in the url upload id param or null if none.
 * @param uploadType upload type to provide in url upload type param or null if none.
 * @return HttpResponse with the given parameters
 * @throws IOException
 */
private HttpResponse buildHttpResponse(String header, String uploadId, String uploadType)
    throws IOException {
  MockHttpTransport.Builder builder = new MockHttpTransport.Builder();
  MockLowLevelHttpResponse resp = new MockLowLevelHttpResponse();
  builder.setLowLevelHttpResponse(resp);
  resp.setStatusCode(200);
  GenericUrl url = new GenericUrl(HttpTesting.SIMPLE_URL);
  if (header != null) {
    resp.addHeader("X-GUploader-UploadID", header);
  }
  if (uploadId != null) {
    url.put("upload_id", uploadId);
  }
  if (uploadType != null) {
    url.put("uploadType", uploadType);
  }
  return builder.build().createRequestFactory().buildGetRequest(url).execute();
}
 
Example #18
Source File: UpdateRegistrarRdapBaseUrlsActionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private static void addValidResponses(TestHttpTransport httpTransport) {
  MockLowLevelHttpResponse loginResponse = new MockLowLevelHttpResponse();
  loginResponse.addHeader(
      "Set-Cookie",
      "JSESSIONID=bogusid; " + "Expires=Tue, 11-Jun-2019 16:34:21 GMT; Path=/; Secure; HttpOnly");
  loginResponse.addHeader(
      "Set-Cookie",
      "id=myAuthenticationId; "
          + "Expires=Tue, 11-Jun-2019 16:34:21 GMT; Path=/mosapi/v1/app; Secure; HttpOnly");

  MockLowLevelHttpResponse listResponse = new MockLowLevelHttpResponse();
  listResponse.setContent(JSON_LIST_REPLY);

  MockLowLevelHttpResponse logoutResponse = new MockLowLevelHttpResponse();
  logoutResponse.addHeader(
      "Set-Cookie",
      "id=id; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/mosapi/v1/app; Secure; HttpOnly");
  httpTransport.addNextResponse(loginResponse);
  httpTransport.addNextResponse(listResponse);
  httpTransport.addNextResponse(logoutResponse);
}
 
Example #19
Source File: GitHubApiTransportImplTest.java    From copybara with Apache License 2.0 6 votes vote down vote up
@Test
public void testPasswordHeaderSet() throws Exception {
  Map<String, List<String>> headers = new HashMap<>();
  httpTransport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          headers.putAll(this.getHeaders());
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setContent("foo");
          return response;
        }
      };
    }
  };
  transport = new GitHubApiTransportImpl(repo, httpTransport, "store", new TestingConsole());
  transport.get("foo/bar", String.class);
  assertThat(headers).containsEntry("authorization", ImmutableList.of("Basic dXNlcjpTRUNSRVQ="));
}
 
Example #20
Source File: GoogleAuthTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
private HttpRequest constructHttpRequest(final String content, final int statusCode) throws IOException {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
          result.setContentType("application/json");
          result.setContent(content);
          result.setStatusCode(statusCode);
          return result;
        }
      };
    }
  };
  HttpRequest httpRequest = transport.createRequestFactory().buildGetRequest(new GenericUrl("https://google.com")).setParser(new JsonObjectParser(new JacksonFactory()));
  GoogleAuth.configureErrorHandling(httpRequest);
  return httpRequest;
}
 
Example #21
Source File: InstanceIdClientImplTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsubscribeMalformedError() {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse()
      .setStatusCode(500).setContent("not json");
  TestResponseInterceptor interceptor = new TestResponseInterceptor();
  InstanceIdClient client = initInstanceIdClient(response, interceptor);

  try {
    client.unsubscribeFromTopic("test-topic", ImmutableList.of("id1", "id2"));
    fail("No error thrown for HTTP error");
  } catch (FirebaseMessagingException error) {
    checkExceptionFromHttpResponse(error, 500,
        "Unexpected HTTP response with status: 500; body: not json");
  }

  checkTopicManagementRequestHeader(interceptor.getLastRequest(), TEST_IID_UNSUBSCRIBE_URL);
}
 
Example #22
Source File: InstanceIdClientImplTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsubscribeError() {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  TestResponseInterceptor interceptor = new TestResponseInterceptor();
  InstanceIdClient client = initInstanceIdClient(response, interceptor);

  for (int statusCode : HTTP_ERRORS) {
    response.setStatusCode(statusCode).setContent("{\"error\": \"test error\"}");

    try {
      client.unsubscribeFromTopic("test-topic", ImmutableList.of("id1", "id2"));
      fail("No error thrown for HTTP error");
    } catch (FirebaseMessagingException error) {
      checkExceptionFromHttpResponse(error, statusCode, "test error");
    }

    checkTopicManagementRequestHeader(interceptor.getLastRequest(), TEST_IID_UNSUBSCRIBE_URL);
  }
}
 
Example #23
Source File: InstanceIdClientImplTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribeMalformedError() {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse()
      .setStatusCode(500).setContent("not json");
  TestResponseInterceptor interceptor = new TestResponseInterceptor();
  InstanceIdClient client = initInstanceIdClient(response, interceptor);

  try {
    client.subscribeToTopic("test-topic", ImmutableList.of("id1", "id2"));
    fail("No error thrown for HTTP error");
  } catch (FirebaseMessagingException error) {
    checkExceptionFromHttpResponse(error, 500,
        "Unexpected HTTP response with status: 500; body: not json");
  }

  checkTopicManagementRequestHeader(interceptor.getLastRequest(), TEST_IID_SUBSCRIBE_URL);
}
 
Example #24
Source File: InstanceIdClientImplTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribeEmptyPayloadError() {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse()
      .setStatusCode(500).setContent("{}");
  TestResponseInterceptor interceptor = new TestResponseInterceptor();
  InstanceIdClient client = initInstanceIdClient(response, interceptor);

  try {
    client.subscribeToTopic("test-topic", ImmutableList.of("id1", "id2"));
    fail("No error thrown for HTTP error");
  } catch (FirebaseMessagingException error) {
    checkExceptionFromHttpResponse(error, 500,
        "Unexpected HTTP response with status: 500; body: {}");
  }

  checkTopicManagementRequestHeader(interceptor.getLastRequest(), TEST_IID_SUBSCRIBE_URL);
}
 
Example #25
Source File: AbstractGoogleClientRequestTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testReturnRawInputStream_True() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          return new MockLowLevelHttpResponse().setContentEncoding("gzip").setContent(new ByteArrayInputStream(
              BaseEncoding.base64()
                  .decode("H4sIAAAAAAAAAPNIzcnJV3DPz0/PSVVwzskvTVEILskvSkxPVQQA/LySchsAAAA=")));
        }
      };
    }
  };
  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);
  request.setReturnRawInputStream(true);
  InputStream inputStream = request.executeAsInputStream();
  // The response will not be wrapped due to setReturnRawInputStream(true)
  assertTrue(inputStream instanceof ByteArrayInputStream);
}
 
Example #26
Source File: FirebaseChannelTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void firebasePut() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport =
      spy(
          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);
                  return response;
                }
              };
            }
          });
  FirebaseChannel.getInstance().httpTransport = mockHttpTransport;
  Game game = new Game();

  firebaseChannel.firebasePut(FIREBASE_DB_URL + "/my/path", game);

  verify(mockHttpTransport, times(1)).buildRequest("PUT", FIREBASE_DB_URL + "/my/path");
}
 
Example #27
Source File: HttpHeadersTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testFromHttpResponse_void(String value) throws Exception {
  MockLowLevelHttpResponse httpResponse =
      new MockLowLevelHttpResponse()
          .setHeaderNames(Arrays.asList("v", "v", "s"))
          .setHeaderValues(Arrays.asList("ignore", "ignore2", "svalue"));
  V v = new V();
  v.fromHttpResponse(httpResponse, null);
  assertNull(v.v);
  assertEquals("svalue", v.s);
}
 
Example #28
Source File: MockGoogleCredential.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
/**
* Returns a new {@link MockHttpTransport} with a sample {@link MockLowLevelHttpResponse}. The
* response includes sample TokenResponse content as specified in DEFAULT_TOKEN_RESPONSE_JSON. This
* is meant to produce a minimal implementation that allows methods such as
* {@link GoogleCredential#executeRefreshToken()} to be called without failing abruptly. This
* content is static. If you are making assertions based on the content of the request, then
* MockTokenServerTransport should be used instead.
*
* @return mockHttpTransport
*/
public static MockHttpTransport newMockHttpTransportWithSampleTokenResponse() {
  MockLowLevelHttpResponse mockLowLevelHttpResponse = new MockLowLevelHttpResponse()
     .setContentType(Json.MEDIA_TYPE)
     .setContent(DEFAULT_TOKEN_RESPONSE_JSON);
  MockLowLevelHttpRequest request = new MockLowLevelHttpRequest()
      .setResponse(mockLowLevelHttpResponse);
  return new MockHttpTransport.Builder()
      .setLowLevelHttpRequest(request)
      .build();
}
 
Example #29
Source File: PasswordReaderTest.java    From dbeam with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecryptPasswordOnpasswordFileKmsEncryptedParameter() throws IOException {

  // Using MockHttpTransport, read more at:
  // https://developers.google.com/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport =
      new MockHttpTransport.Builder()
          .setLowLevelHttpResponse(
              new MockLowLevelHttpResponse()
                  .setStatusCode(200)
                  .setContentType(Json.MEDIA_TYPE)
                  .setContent(
                      JacksonFactory.getDefaultInstance()
                          .toByteArray(
                              new DecryptResponse()
                                  .encodePlaintext("something_decrypted".getBytes()))))
          .build();
  PasswordReader passwordReader =
      new PasswordReader(
          KmsDecrypter.decrypter()
              .project(Optional.of("fake_project"))
              .credentials(NoopCredentialFactory.fromOptions(null).getCredential())
              .transport(mockHttpTransport)
              .build());

  DBeamPipelineOptions options = PipelineOptionsFactory.create().as(DBeamPipelineOptions.class);
  options.setPasswordFileKmsEncrypted(passwordFile.getPath());

  final Optional<String> actualPassword = passwordReader.readPassword(options);

  Assert.assertEquals(Optional.of("something_decrypted"), actualPassword);
}
 
Example #30
Source File: DeleteServletTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void doPost_deleteGame() throws Exception {
  // Insert a game
  Objectify ofy = ObjectifyService.ofy();
  Game game = new Game(USER_ID, "my-opponent", "         ", true);
  ofy.save().entity(game).now();
  String gameKey = game.getId();
  when(mockRequest.getParameter("gameKey")).thenReturn(gameKey);

  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport =
      spy(
          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);
                  return response;
                }
              };
            }
          });
  FirebaseChannel.getInstance().httpTransport = mockHttpTransport;

  servletUnderTest.doPost(mockRequest, mockResponse);

  verify(mockHttpTransport, times(1))
      .buildRequest(eq("DELETE"), Matchers.matches(FIREBASE_DB_URL + "/channels/[\\w-]+.json$"));
}