com.google.api.client.googleapis.testing.auth.oauth2.MockGoogleCredential Java Examples

The following examples show how to use com.google.api.client.googleapis.testing.auth.oauth2.MockGoogleCredential. 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: LocalFileCredentialFactoryTest.java    From connector-sdk with Apache License 2.0 9 votes vote down vote up
@Test
public void testNullServiceAccountIdJson() throws Exception {
  File tmpfile =
      temporaryFolder.newFile("testNullServiceAccountIdJson" + SERVICE_ACCOUNT_FILE_JSON);
  GoogleCredential mockCredential = new MockGoogleCredential.Builder().build();
  List<String> scopes = Arrays.asList("profile");
  when(mockCredentialHelper.getJsonCredential(
      eq(tmpfile.toPath()),
      any(HttpTransport.class),
      any(JsonFactory.class),
      any(HttpRequestInitializer.class),
      eq(scopes)))
      .thenReturn(mockCredential);
  LocalFileCredentialFactory subject =
      new LocalFileCredentialFactory.Builder()
          .setServiceAccountKeyFilePath(tmpfile.getAbsolutePath())
          .build();
  subject.getCredential(Arrays.asList("email"));
  assertEquals(mockCredential, subject.getCredential(scopes));
}
 
Example #2
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 #3
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 #4
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 #5
Source File: BaseApiServiceTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testIOExceptionRetry() throws Exception {
  MockLowLevelHttpRequest request =
      new MockLowLevelHttpRequest("https://www.googleapis.com/mock/v1") {
        @Override
        public MockLowLevelHttpResponse execute() throws IOException {
          throw new IOException("something is wrong");
        }
      };
  MockLowLevelHttpRequest retryRequest = buildRequest(200, new GenericJson());
  HttpTransport transport = new TestingHttpTransport(ImmutableList.of(request, retryRequest));
  TestApiService apiService =
      new TestApiService.Builder()
          .setTransport(transport)
          .setCredentialFactory(scopes -> new MockGoogleCredential.Builder().build())
          .build();
  validateEmptyItem(apiService.get());
}
 
Example #6
Source File: LocalFileCredentialFactoryTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCredentialJsonKey() throws Exception {
  File tmpfile = temporaryFolder.newFile(SERVICE_ACCOUNT_FILE_JSON);
  GoogleCredential mockCredential = new MockGoogleCredential.Builder().build();
  List<String> scopes = Arrays.asList("profile");
  when(mockCredentialHelper.getJsonCredential(
      eq(tmpfile.toPath()),
      any(HttpTransport.class),
      any(JsonFactory.class),
      any(HttpRequestInitializer.class),
      eq(scopes)))
      .thenReturn(mockCredential);
  LocalFileCredentialFactory credentialFactory =
      new LocalFileCredentialFactory.Builder()
          .setServiceAccountKeyFilePath(tmpfile.getAbsolutePath())
          .setServiceAccountId("ServiceAccountID")
          .build();
  assertEquals(mockCredential, credentialFactory.getCredential(scopes));
}
 
Example #7
Source File: LocalFileCredentialFactoryTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCredentialP12() throws Exception {
  File tmpfile = temporaryFolder.newFile(SERVICE_ACCOUNT_FILE_P12);
  GoogleCredential mockCredential = new MockGoogleCredential.Builder().build();
  List<String> scopes = Arrays.asList("profile, calendar");
  when(mockCredentialHelper.getP12Credential(
      eq("ServiceAccount"),
      eq(tmpfile.toPath()),
      any(HttpTransport.class),
      any(JsonFactory.class),
      any(HttpRequestInitializer.class),
      eq(scopes)))
      .thenReturn(mockCredential);
  LocalFileCredentialFactory credentialFactory =
      new LocalFileCredentialFactory.Builder()
          .setServiceAccountKeyFilePath(tmpfile.getAbsolutePath())
          .setServiceAccountId("ServiceAccount")
          .build();
  assertEquals(mockCredential, credentialFactory.getCredential(scopes));
}
 
Example #8
Source File: LocalFileCredentialFactoryTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testfromConfigurationJsonKey() throws Exception {
  File tmpfile = temporaryFolder.newFile("testfromConfiguration" + SERVICE_ACCOUNT_FILE_JSON);
  createConfig(tmpfile.getAbsolutePath(), "");
  GoogleCredential mockCredential = new MockGoogleCredential.Builder().build();
  List<String> scopes = Arrays.asList("profile");
  when(mockCredentialHelper.getJsonCredential(
      eq(tmpfile.toPath()),
      any(HttpTransport.class),
      any(JsonFactory.class),
      any(HttpRequestInitializer.class),
      eq(scopes)))
      .thenReturn(mockCredential);
  LocalFileCredentialFactory credentialFactory = LocalFileCredentialFactory.fromConfiguration();
  assertEquals(mockCredential, credentialFactory.getCredential(scopes));
}
 
Example #9
Source File: LocalFileCredentialFactoryTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testfromConfigurationCredentialP12() throws Exception {
  File tmpfile = temporaryFolder
      .newFile("testfromConfigurationCredentialP12" + SERVICE_ACCOUNT_FILE_P12);
  createConfig(tmpfile.getAbsolutePath(), "ServiceAccount");
  GoogleCredential mockCredential = new MockGoogleCredential.Builder().build();
  List<String> scopes = Arrays.asList("profile, calendar");
  when(mockCredentialHelper.getP12Credential(
      eq("ServiceAccount"),
      eq(tmpfile.toPath()),
      any(HttpTransport.class),
      any(JsonFactory.class),
      any(HttpRequestInitializer.class),
      eq(scopes)))
      .thenReturn(mockCredential);
  LocalFileCredentialFactory credentialFactory = LocalFileCredentialFactory.fromConfiguration();
  assertEquals(mockCredential, credentialFactory.getCredential(scopes));
}
 
Example #10
Source File: BaseApiServiceTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testApiServiceWithPrebuiltClient() throws Exception {
  MockLowLevelHttpRequest request = buildRequest(200, new GenericJson());
  HttpTransport transport = new TestingHttpTransport(ImmutableList.of(request));
  TestApi apiClient =
      (TestApi)
          new TestApi.Builder(transport, JSON_FACTORY, null)
              .setApplicationName("bring your own client")
              .build();
  TestApiService apiService =
      new TestApiService.Builder()
          .setService(apiClient)
          .setTransport(transport)
          .setCredentialFactory(scopes -> new MockGoogleCredential.Builder().build())
          .build();
  validateEmptyItem(apiService.get());
  assertThat(
      request.getHeaderValues("user-agent").get(0), containsString("bring your own client"));
}
 
Example #11
Source File: BaseApiServiceTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequestWithNonEmptyResponse() throws Exception {
  TestItem expected = new TestItem();
  expected.number = 10;
  expected.collection = ImmutableList.of("item1");
  expected.flag = true;
  expected.child = new TestItem();
  expected.text = "golden";

  HttpTransport transport =
      new TestingHttpTransport(ImmutableList.of(buildRequest(200, expected)));
  TestApiService apiService =
      new TestApiService.Builder()
          .setTransport(transport)
          .setCredentialFactory(scopes -> new MockGoogleCredential.Builder().build())
          .build();
  TestItem result = apiService.get();
  assertTrue(result.flag);
  assertEquals(expected.number, result.number);
  assertEquals(expected.text, result.text);
  assertEquals(expected.collection, result.collection);
  validateEmptyItem(result.child);
}
 
Example #12
Source File: DataflowJobManagerTest.java    From feast with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  initMocks(this);
  Builder optionsBuilder = DataflowRunnerConfigOptions.newBuilder();
  optionsBuilder.setProject("project");
  optionsBuilder.setRegion("region");
  optionsBuilder.setZone("zone");
  optionsBuilder.setTempLocation("tempLocation");
  optionsBuilder.setNetwork("network");
  optionsBuilder.setSubnetwork("subnetwork");
  optionsBuilder.putLabels("orchestrator", "feast");
  defaults = optionsBuilder.build();
  MetricsProperties metricsProperties = new MetricsProperties();
  metricsProperties.setEnabled(false);
  Credential credential = null;
  try {
    credential = MockGoogleCredential.getApplicationDefault();
  } catch (IOException e) {
    e.printStackTrace();
  }

  specsStreamingUpdateConfig =
      IngestionJobProto.SpecsStreamingUpdateConfig.newBuilder()
          .setSource(
              KafkaSourceConfig.newBuilder()
                  .setTopic("specs_topic")
                  .setBootstrapServers("servers:9092")
                  .build())
          .build();

  dfJobManager =
      new DataflowJobManager(defaults, metricsProperties, specsStreamingUpdateConfig, credential);
  dfJobManager = spy(dfJobManager);
}
 
Example #13
Source File: BaseApiServiceTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestWithNonDefaultRootUrl() throws Exception {
  MockLowLevelHttpRequest request = buildRequest(200, new GenericJson());
  TestingHttpTransport transport = spy(new TestingHttpTransport(ImmutableList.of(request)));
  TestApiService apiService =
      new TestApiService.Builder()
          .setTransport(transport)
          .setCredentialFactory(scopes -> new MockGoogleCredential.Builder().build())
          .setRootUrl("https://staging.googleapis.com")
          .build();
  validateEmptyItem(apiService.get());
  verify(transport).buildRequest("GET", "https://staging.googleapis.com/mock/v1");
}
 
Example #14
Source File: BaseApiServiceTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestWithTimeouts() throws Exception {
  AtomicInteger connectionTimeoutHolder = new AtomicInteger();
  AtomicInteger readTimeoutHolder = new AtomicInteger();
  MockLowLevelHttpRequest request =
      new MockLowLevelHttpRequest("https://www.googleapis.com/mock/v1") {
        @Override
        public MockLowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response
              .setStatusCode(200)
              .setContentType(Json.MEDIA_TYPE)
              .setContent(JSON_FACTORY.toString(new GenericJson()));
          return response;
        }

        @Override
        public void setTimeout(int connectTimeout, int readTimeout) throws IOException {
          connectionTimeoutHolder.set(connectTimeout);
          readTimeoutHolder.set(readTimeout);
        }
      };
  HttpTransport transport =
      new TestingHttpTransport(ImmutableList.of(request));
  TestApiService apiService =
      new TestApiService.Builder()
          .setTransport(transport)
          .setCredentialFactory(scopes -> new MockGoogleCredential.Builder().build())
          .setRequestTimeout(10, 15)
          .build();
  validateEmptyItem(apiService.get());
  assertEquals(10000, connectionTimeoutHolder.get());
  assertEquals(15000, readTimeoutHolder.get());
}
 
Example #15
Source File: BaseApiServiceTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestWithRetryableErrorFor502() throws Exception {
  TestingHttpTransport transport =
      new TestingHttpTransport(
          ImmutableList.of(
              buildRequest(502, new GenericJson()), buildRequest(200, new GenericJson())));
  TestApiService apiService =
      new TestApiService.Builder()
          .setTransport(transport)
          .setCredentialFactory(scopes -> new MockGoogleCredential.Builder().build())
          .build();
  validateEmptyItem(apiService.get());
  assertFalse(transport.requests.hasNext());
}
 
Example #16
Source File: BaseApiServiceTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestWithRetryableError() throws Exception {
  TestingHttpTransport transport =
      new TestingHttpTransport(
          ImmutableList.of(
              buildRequest(503, new GenericJson()), buildRequest(200, new GenericJson())));
  TestApiService apiService =
      new TestApiService.Builder()
          .setTransport(transport)
          .setCredentialFactory(scopes -> new MockGoogleCredential.Builder().build())
          .build();
  validateEmptyItem(apiService.get());
  assertFalse(transport.requests.hasNext());
}
 
Example #17
Source File: BaseApiServiceTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestWithNonRetryableError() throws Exception {
  HttpTransport transport =
      new TestingHttpTransport(ImmutableList.of(buildRequest(400, new GenericJson())));
  TestApiService apiService =
      new TestApiService.Builder()
          .setTransport(transport)
          .setCredentialFactory(scopes -> new MockGoogleCredential.Builder().build())
          .build();
  thrown.expect(GoogleJsonResponseException.class);
  apiService.get();
}
 
Example #18
Source File: BaseApiServiceTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestWithInitializePrimitiveTypes() throws Exception {
  HttpTransport transport =
      new TestingHttpTransport(ImmutableList.of(buildRequest(200, new GenericJson())));
  TestApiService apiService =
      new TestApiService.Builder()
          .setTransport(transport)
          .setCredentialFactory(scopes -> new MockGoogleCredential.Builder().build())
          .build();
  validateEmptyItem(apiService.get());
}
 
Example #19
Source File: IndexingServiceTest.java    From connector-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@Parameters({"SYNCHRONOUS", "ASYNCHRONOUS"})
public void fromConfiguration_apiDefaultRequestMode_isSet(String testRequestMode)
    throws Exception {
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  CredentialFactory credentialFactory =
      scopes ->
          new MockGoogleCredential.Builder()
              .setTransport(transport)
              .setJsonFactory(jsonFactory)
              .build();
  Properties config = new Properties();
  config.put(IndexingServiceImpl.SOURCE_ID, "sourceId");
  config.put(IndexingServiceImpl.IDENTITY_SOURCE_ID, "identitySourceId");
  File serviceAcctFile = temporaryFolder.newFile("serviceaccount.json");
  config.put(
      LocalFileCredentialFactory.SERVICE_ACCOUNT_KEY_FILE_CONFIG,
      serviceAcctFile.getAbsolutePath());
  config.put(IndexingServiceImpl.INDEXING_SERVICE_REQUEST_MODE, testRequestMode);
  setupConfig.initConfig(config);
  ListenableFuture<Operation> expected = Futures.immediateFuture(new Operation());
  when(batchingService.indexItem(any())).thenReturn(expected);

  IndexingServiceImpl.Builder indexingServiceBuilder =
      IndexingServiceImpl.Builder.fromConfiguration(Optional.empty(), "unitTest");
  this.indexingService = indexingServiceBuilder
      .setTransport(transport)
      .setCredentialFactory(credentialFactory)
      .setService(cloudSearch)
      .setBatchingIndexingService(batchingService)
      .setContentUploadService(contentUploadService)
      .setContentUploadThreshold(CONTENT_UPLOAD_THRESHOLD)
      .setServiceManagerHelper(serviceManagerHelper)
      .setQuotaServer(quotaServer)
      .build();
  this.indexingService.startAsync().awaitRunning();

  indexingService.deleteItem(GOOD_ID, "abc".getBytes(UTF_8), RequestMode.UNSPECIFIED);
  verify(batchingService).deleteItem(deleteCaptor.capture());
  Items.Delete deleteRequest = deleteCaptor.getValue();
  assertEquals(testRequestMode, deleteRequest.getMode());

  indexingService.indexItem(new Item().setName(GOOD_ID), RequestMode.UNSPECIFIED);
  verify(batchingService).indexItem(indexCaptor.capture());
  Items.Index updateRequest = indexCaptor.getValue();
  IndexItemRequest indexItemRequest = (IndexItemRequest) updateRequest.getJsonContent();
  assertEquals(testRequestMode, indexItemRequest.getMode());
}
 
Example #20
Source File: IndexingServiceTest.java    From connector-sdk with Apache License 2.0 4 votes vote down vote up
private void createService(boolean enableDebugging, boolean allowUnknownGsuitePrincipals)
    throws IOException, GeneralSecurityException {
  this.transport = new TestingHttpTransport("datasources/source/connectors/unitTest");
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  CredentialFactory credentialFactory =
      scopes ->
          new MockGoogleCredential.Builder()
              .setTransport(new MockHttpTransport())
              .setJsonFactory(jsonFactory)
              .build();
  GoogleCredential credential =
      new MockGoogleCredential.Builder()
          .setTransport(this.transport)
          .setJsonFactory(jsonFactory)
          .build();
  CloudSearch.Builder serviceBuilder =
      new CloudSearch.Builder(this.transport, jsonFactory, credential);
  this.cloudSearch = serviceBuilder.setApplicationName("IndexingServiceTest").build();
  when(batchingService.state()).thenReturn(State.NEW);
  when(contentUploadService.state()).thenReturn(State.NEW);
  doAnswer(invocation -> new ServiceManager(invocation.getArgument(0)))
      .when(serviceManagerHelper)
      .getServiceManager(Arrays.asList(batchingService, contentUploadService));
  this.indexingService =
      new IndexingServiceImpl.Builder()
          .setTransport(transport)
          .setJsonFactory(jsonFactory)
          .setCredentialFactory(credentialFactory)
          .setSourceId(SOURCE_ID)
          .setIdentitySourceId(IDENTITY_SOURCE_ID)
          .setService(cloudSearch)
          .setBatchingIndexingService(batchingService)
          .setContentUploadService(contentUploadService)
          .setContentUploadThreshold(CONTENT_UPLOAD_THRESHOLD)
          .setServiceManagerHelper(serviceManagerHelper)
          .setQuotaServer(quotaServer)
          .setConnectorId("unitTest")
          .setEnableDebugging(enableDebugging)
          .setAllowUnknownGsuitePrincipals(allowUnknownGsuitePrincipals)
          .build();
  this.indexingService.startAsync().awaitRunning();
}