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

The following examples show how to use com.google.api.client.testing.http.MockHttpTransport. 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: 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 #2
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 #3
Source File: HttpResponseExceptionTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testComputeMessage() 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.setReasonPhrase("Foo");
              return result;
            }
          };
        }
      };
  HttpRequest request = transport.createRequestFactory().buildGetRequest(SIMPLE_GENERIC_URL);
  HttpResponse response = request.execute();
  assertThat(HttpResponseException.computeMessageBuffer(response).toString())
      .isEqualTo("200 Foo\nGET " + SIMPLE_GENERIC_URL);
}
 
Example #4
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParseAsString_utf8() 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.setContentType(Json.MEDIA_TYPE);
              result.setContent(SAMPLE);
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  HttpResponse response = request.execute();
  assertEquals(SAMPLE, response.parseAsString());
}
 
Example #5
Source File: SplunkHttpSinkTaskTest.java    From kafka-connect-splunk with Apache License 2.0 6 votes vote down vote up
@Test
public void connectionRefused() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  when(httpRequest.execute()).thenThrow(ConnectException.class);
  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  assertThrows(RetriableException.class, () -> this.task.put(sinkRecords));
}
 
Example #6
Source File: GithubArchiveTest.java    From copybara with Apache License 2.0 6 votes vote down vote up
@Test
public void repoExceptionOnDownloadFailure() throws Exception {
  httpTransport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) {
           MockLowLevelHttpRequest request = new MockLowLevelHttpRequest() {
              public LowLevelHttpResponse execute() throws IOException {
                throw new IOException("OH NOES!");
              }
           };
          return request;
        }
      };
  RemoteFileOptions options = new RemoteFileOptions();
  options.transport = () -> new GclientHttpStreamFactory(httpTransport, Duration.ofSeconds(20));
  Console console = new TestingConsole();
  OptionsBuilder optionsBuilder = new OptionsBuilder().setConsole(console);
  optionsBuilder.remoteFile = options;
  skylark = new SkylarkTestExecutor(optionsBuilder);
  ValidationException e = assertThrows(ValidationException.class, () -> skylark.eval("sha256",
      "sha256 = remotefiles.github_archive("
          + "project = 'google/copybara',"
          + "revision='674ac754f91e64a0efb8087e59a176484bd534d1').sha256()"));
  assertThat(e).hasCauseThat().hasCauseThat().hasCauseThat().isInstanceOf(RepoException.class);
}
 
Example #7
Source File: FirebaseChannelTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void firebaseGet() 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;

  firebaseChannel.firebaseGet(FIREBASE_DB_URL + "/my/path");

  verify(mockHttpTransport, times(1)).buildRequest("GET", FIREBASE_DB_URL + "/my/path");
}
 
Example #8
Source File: FirebaseChannelTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void firebaseDelete() 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;

  firebaseChannel.firebaseDelete(FIREBASE_DB_URL + "/my/path");

  verify(mockHttpTransport, times(1)).buildRequest("DELETE", FIREBASE_DB_URL + "/my/path");
}
 
Example #9
Source File: IndexingServiceTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuilderWithNullQuotaServer() throws IOException, GeneralSecurityException {
  CredentialFactory credentialFactory =
      scopes ->
          new MockGoogleCredential.Builder()
              .setTransport(new MockHttpTransport())
              .setJsonFactory(JacksonFactory.getDefaultInstance())
              .build();
  thrown.expect(NullPointerException.class);
  thrown.expectMessage(containsString("quota server can not be null"));
  new IndexingServiceImpl.Builder()
      .setSourceId(SOURCE_ID)
      .setIdentitySourceId(IDENTITY_SOURCE_ID)
      .setService(cloudSearch)
      .setCredentialFactory(credentialFactory)
      .setQuotaServer(null)
      .setBatchPolicy(new BatchPolicy.Builder().build())
      .build();
}
 
Example #10
Source File: IndexingServiceTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuilderWithConfigurationAndCredentialFactory()
    throws IOException, GeneralSecurityException {
  CredentialFactory credentialFactory =
      scopes ->
          new MockGoogleCredential.Builder()
              .setTransport(new MockHttpTransport())
              .setJsonFactory(JacksonFactory.getDefaultInstance())
              .build();
  Properties config = new Properties();
  config.put(IndexingServiceImpl.SOURCE_ID, "sourceId");
  config.put(IndexingServiceImpl.IDENTITY_SOURCE_ID, "identitySourceId");
  setupConfig.initConfig(config);
  IndexingServiceImpl.Builder.fromConfiguration(Optional.of(credentialFactory), "unitTest")
      .build();
}
 
Example #11
Source File: IndexingServiceTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuilderWithServices() throws IOException, GeneralSecurityException {
  CredentialFactory credentialFactory =
      scopes ->
          new MockGoogleCredential.Builder()
              .setTransport(new MockHttpTransport())
              .setJsonFactory(JacksonFactory.getDefaultInstance())
              .build();
  assertNotNull(
      new IndexingServiceImpl.Builder()
          .setSourceId(SOURCE_ID)
          .setIdentitySourceId(IDENTITY_SOURCE_ID)
          .setService(cloudSearch)
          .setBatchingIndexingService(batchingService)
          .setCredentialFactory(credentialFactory)
          .setBatchPolicy(new BatchPolicy.Builder().build())
          .setRetryPolicy(new RetryPolicy.Builder().build())
          .setConnectorId("unitTest")
          .build());
}
 
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_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 #13
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParseAsString_noContentType() 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);
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  HttpResponse response = request.execute();
  assertEquals(SAMPLE2, response.parseAsString());
}
 
Example #14
Source File: HttpResponseExceptionTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testConstructorWithStatusMessage() 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.setReasonPhrase("OK");
              return result;
            }
          };
        }
      };
  HttpRequest request = transport.createRequestFactory().buildGetRequest(SIMPLE_GENERIC_URL);
  HttpResponse response = request.execute();
  HttpResponseException responseException = new HttpResponseException(response);
  assertEquals("OK", responseException.getStatusMessage());
}
 
Example #15
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 #16
Source File: GoogleProxyTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void createProxy_proxyCreated() throws Exception {
  Properties properties = new Properties();
  properties.setProperty(TRANSPORT_PROXY_TYPE_KEY, "SOCKS");
  properties.setProperty(TRANSPORT_PROXY_HOSTNAME_KEY, "1.2.3.4");
  properties.setProperty(TRANSPORT_PROXY_PORT_KEY, "1234");
  properties.setProperty(TRANSPORT_PROXY_USERNAME_KEY, "user");
  properties.setProperty(TRANSPORT_PROXY_PASSWORD_KEY, "1234");
  setupConfig.initConfig(properties);

  GoogleProxy proxy = GoogleProxy.fromConfiguration();

  assertEquals(
      new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("1.2.3.4", 1234)), proxy.getProxy());

  HttpTransport transport = new MockHttpTransport();
  HttpRequest request = transport.createRequestFactory().buildGetRequest(new GenericUrl());
  proxy.getHttpRequestInitializer().initialize(request);
  assertEquals("Basic dXNlcjoxMjM0", request.getHeaders().get("Proxy-Authorization"));
}
 
Example #17
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testParseAsString_invalidContentType() 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(INVALID_CONTENT_TYPE);
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);

  HttpResponse response = request.execute();
  assertEquals(SAMPLE2, response.parseAsString());
  assertEquals(INVALID_CONTENT_TYPE, response.getContentType());
  assertNull(response.getMediaType());
}
 
Example #18
Source File: BigQueryServicesImplTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);

  // Set up the MockHttpRequest for future inspection
  request =
      new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          return response;
        }
      };

  // A mock transport that lets us mock the API responses.
  MockHttpTransport transport =
      new MockHttpTransport.Builder().setLowLevelHttpRequest(request).build();

  // A sample BigQuery API client that uses default JsonFactory and RetryHttpInitializer.
  bigquery =
      new Bigquery.Builder(
              transport, Transport.getJsonFactory(), new RetryHttpRequestInitializer())
          .build();
}
 
Example #19
Source File: SplunkHttpSinkTaskTest.java    From kafka-connect-splunk with Apache License 2.0 6 votes vote down vote up
@Test
public void invalidIndex() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(400);
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords));
}
 
Example #20
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testDownload() 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.setContentType(Json.MEDIA_TYPE);
              result.setContent(SAMPLE);
              return result;
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  HttpResponse response = request.execute();
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  response.download(outputStream);
  assertEquals(SAMPLE, outputStream.toString("UTF-8"));
}
 
Example #21
Source File: HttpResponseTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public void testGetContent_gzipEncoding_ReturnRawStream() 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.setResponseReturnRawInputStream(true);
  assertFalse(
      "it should not decompress stream",
      request.execute().getContent() instanceof GZIPInputStream);
}
 
Example #22
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 #23
Source File: FirebaseCustomTokenTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateCustomTokenWithoutServiceAccountCredentials() throws Exception {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  String content = Utils.getDefaultJsonFactory().toString(
      ImmutableMap.of("signature", BaseEncoding.base64().encode("test-signature".getBytes())));
  response.setContent(content);
  MockHttpTransport transport = new MultiRequestMockHttpTransport(ImmutableList.of(response));

  FirebaseOptions options = FirebaseOptions.builder()
      .setCredentials(new MockGoogleCredentials("test-token"))
      .setProjectId("test-project-id")
      .setServiceAccountId("[email protected]")
      .setHttpTransport(transport)
      .build();
  FirebaseApp app = FirebaseApp.initializeApp(options);
  FirebaseAuth auth = FirebaseAuth.getInstance(app);

  String token = auth.createCustomTokenAsync("user1").get();
  FirebaseCustomAuthToken parsedToken = FirebaseCustomAuthToken.parse(new GsonFactory(), token);
  assertEquals(parsedToken.getPayload().getUid(), "user1");
  assertEquals(parsedToken.getPayload().getSubject(), "[email protected]");
  assertEquals(parsedToken.getPayload().getIssuer(), "[email protected]");
  assertNull(parsedToken.getPayload().getDeveloperClaims());
  assertEquals("test-signature", new String(parsedToken.getSignatureBytes()));
}
 
Example #24
Source File: FirebaseUserManagerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testTimeout() throws Exception {
  MockHttpTransport transport = new MultiRequestMockHttpTransport(ImmutableList.of(
      new MockLowLevelHttpResponse().setContent(TestUtils.loadResource("getUser.json"))));
  FirebaseApp.initializeApp(new FirebaseOptions.Builder()
      .setCredentials(credentials)
      .setProjectId("test-project-id")
      .setHttpTransport(transport)
      .setConnectTimeout(30000)
      .setReadTimeout(60000)
      .build());
  FirebaseAuth auth = FirebaseAuth.getInstance();
  FirebaseUserManager userManager = auth.getUserManager();
  TestResponseInterceptor interceptor = new TestResponseInterceptor();
  userManager.setInterceptor(interceptor);

  FirebaseAuth.getInstance().getUserAsync("testuser").get();
  HttpRequest request = interceptor.getResponse().getRequest();
  assertEquals(30000, request.getConnectTimeout());
  assertEquals(60000, request.getReadTimeout());
}
 
Example #25
Source File: GcsUtilTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileSizeWhenFileNotFoundNonBatch() throws Exception {
  MockLowLevelHttpResponse notFoundResponse = new MockLowLevelHttpResponse();
  notFoundResponse.setContent("");
  notFoundResponse.setStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND);

  MockHttpTransport mockTransport =
      new MockHttpTransport.Builder().setLowLevelHttpResponse(notFoundResponse).build();

  GcsOptions pipelineOptions = gcsOptionsWithTestCredential();
  GcsUtil gcsUtil = pipelineOptions.getGcsUtil();

  gcsUtil.setStorageClient(new Storage(mockTransport, Transport.getJsonFactory(), null));

  thrown.expect(FileNotFoundException.class);
  gcsUtil.fileSize(GcsPath.fromComponents("testbucket", "testobject"));
}
 
Example #26
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 #27
Source File: FirebaseTokenVerifierImplTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyTokenCertificateError() {
  MockHttpTransport failingTransport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      throw new IOException("Expected error");
    }
  };
  GooglePublicKeysManager publicKeysManager = newPublicKeysManager(failingTransport);
  FirebaseTokenVerifier idTokenVerifier = newTestTokenVerifier(publicKeysManager);
  String token = tokenFactory.createToken();

  try {
    idTokenVerifier.verifyToken(token);
    Assert.fail("No exception thrown");
  } catch (FirebaseAuthException expected) {
    assertTrue(expected.getCause() instanceof IOException);
    assertEquals("Expected error", expected.getCause().getMessage());
  }
}
 
Example #28
Source File: SplunkHttpSinkTaskTest.java    From kafka-connect-splunk with Apache License 2.0 6 votes vote down vote up
@Test
public void contentLengthTooLarge() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(417);
  when(httpResponse.getContentType()).thenReturn("text/html");
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords));
}
 
Example #29
Source File: HttpRequestTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testExecute_headerSerialization() throws Exception {
  // custom headers
  MyHeaders myHeaders = new MyHeaders();
  myHeaders.foo = "bar";
  myHeaders.objNum = 5;
  myHeaders.list = ImmutableList.of("a", "b", "c");
  myHeaders.objList = ImmutableList.of("a2", "b2", "c2");
  myHeaders.r = new String[] {"a1", "a2"};
  myHeaders.setAcceptEncoding(null);
  myHeaders.setUserAgent("foo");
  myHeaders.set("a", "b");
  myHeaders.value = E.VALUE;
  myHeaders.otherValue = E.OTHER_VALUE;
  // execute request
  final MockLowLevelHttpRequest lowLevelRequest = new MockLowLevelHttpRequest();
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          return lowLevelRequest;
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setHeaders(myHeaders);
  request.execute();
  // check headers
  assertEquals(ImmutableList.of("bar"), lowLevelRequest.getHeaderValues("foo"));
  assertEquals(ImmutableList.of("a", "b", "c"), lowLevelRequest.getHeaderValues("list"));
  assertEquals(ImmutableList.of("a2", "b2", "c2"), lowLevelRequest.getHeaderValues("objlist"));
  assertEquals(ImmutableList.of("a1", "a2"), lowLevelRequest.getHeaderValues("r"));
  assertTrue(lowLevelRequest.getHeaderValues("accept-encoding").isEmpty());
  assertEquals(
      ImmutableList.of("foo Google-HTTP-Java-Client/" + HttpRequest.VERSION + " (gzip)"),
      lowLevelRequest.getHeaderValues("user-agent"));
  assertEquals(ImmutableList.of("b"), lowLevelRequest.getHeaderValues("a"));
  assertEquals(ImmutableList.of("VALUE"), lowLevelRequest.getHeaderValues("value"));
  assertEquals(ImmutableList.of("other"), lowLevelRequest.getHeaderValues("othervalue"));
}
 
Example #30
Source File: GcsUtilTest.java    From beam with Apache License 2.0 5 votes vote down vote up
/** 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);
}