Python google.auth.credentials() Examples
The following are 30
code examples of google.auth.credentials().
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 also want to check out all available functions/classes of the module
google.auth
, or try the search function
.
Example #1
Source File: test_mtls_http.py From google-auth-library-python with Apache License 2.0 | 6 votes |
def test_urllib3_with_default_client_cert_source(): credentials, project_id = google.auth.default() credentials = google.auth.credentials.with_scopes_if_required( credentials, ["https://www.googleapis.com/auth/pubsub"] ) authed_http = google.auth.transport.urllib3.AuthorizedHttp(credentials) if mtls.has_default_client_cert_source(): assert authed_http.configure_mtls_channel( client_cert_callback=mtls.default_client_cert_source() ) # Sleep 1 second to avoid 503 error. time.sleep(1) response = authed_http.request("GET", MTLS_ENDPOINT.format(project_id)) assert response.status == 200
Example #2
Source File: test_requests.py From google-auth-library-python with Apache License 2.0 | 6 votes |
def test_request_max_allowed_time_timeout_error(self, frozen_time): tick_one_second = functools.partial( frozen_time.tick, delta=datetime.timedelta(seconds=1.0) ) credentials = mock.Mock( wraps=TimeTickCredentialsStub(time_tick=tick_one_second) ) adapter = TimeTickAdapterStub( time_tick=tick_one_second, responses=[make_response(status=http_client.OK)] ) authed_session = google.auth.transport.requests.AuthorizedSession(credentials) authed_session.mount(self.TEST_URL, adapter) # Because a request takes a full mocked second, max_allowed_time shorter # than that will cause a timeout error. with pytest.raises(requests.exceptions.Timeout): authed_session.request("GET", self.TEST_URL, max_allowed_time=0.9)
Example #3
Source File: test_requests.py From google-auth-library-python with Apache License 2.0 | 6 votes |
def test_request_max_allowed_time_w_transport_timeout_no_error(self, frozen_time): tick_one_second = functools.partial( frozen_time.tick, delta=datetime.timedelta(seconds=1.0) ) credentials = mock.Mock( wraps=TimeTickCredentialsStub(time_tick=tick_one_second) ) adapter = TimeTickAdapterStub( time_tick=tick_one_second, responses=[ make_response(status=http_client.UNAUTHORIZED), make_response(status=http_client.OK), ], ) authed_session = google.auth.transport.requests.AuthorizedSession(credentials) authed_session.mount(self.TEST_URL, adapter) # A short configured transport timeout does not affect max_allowed_time. # The latter is not adjusted to it and is only concerned with the actual # execution time. The call below should thus not raise a timeout error. authed_session.request("GET", self.TEST_URL, timeout=0.5, max_allowed_time=3.1)
Example #4
Source File: test_client.py From python-firestore with Apache License 2.0 | 6 votes |
def test_constructor_explicit(self): credentials = _make_credentials() database = "now-db" client_info = mock.Mock() client_options = mock.Mock() client = self._make_one( project=self.PROJECT, credentials=credentials, database=database, client_info=client_info, client_options=client_options, ) self.assertEqual(client.project, self.PROJECT) self.assertEqual(client._credentials, credentials) self.assertEqual(client._database, database) self.assertIs(client._client_info, client_info) self.assertIs(client._client_options, client_options)
Example #5
Source File: test_client.py From python-firestore with Apache License 2.0 | 6 votes |
def test__rpc_metadata_property_with_emulator(self): emulator_host = "localhost:8081" with mock.patch("os.getenv") as getenv: getenv.return_value = emulator_host credentials = _make_credentials() database = "quanta" client = self._make_one( project=self.PROJECT, credentials=credentials, database=database ) self.assertEqual( client._rpc_metadata, [ ("google-cloud-resource-prefix", client._database_string), ("authorization", "Bearer owner"), ], )
Example #6
Source File: test_grpc.py From google-auth-library-python with Apache License 2.0 | 6 votes |
def test_grpc_request_with_on_demand_jwt_credentials(): credentials, project_id = google.auth.default() credentials = google.auth.jwt.OnDemandCredentials.from_signing_credentials( credentials ) transport = publisher_grpc_transport.PublisherGrpcTransport( address=publisher_client.PublisherClient.SERVICE_ADDRESS, credentials=credentials, ) # Create a pub/sub client. client = pubsub_v1.PublisherClient(transport=transport) # list the topics and drain the iterator to test that an authorized API # call works. list_topics_iter = client.list_topics(project="projects/{}".format(project_id)) list(list_topics_iter)
Example #7
Source File: test_requests.py From google-auth-library-python with Apache License 2.0 | 6 votes |
def test_configure_mtls_channel_with_callback(self): mock_callback = mock.Mock() mock_callback.return_value = ( pytest.public_cert_bytes, pytest.private_key_bytes, ) auth_session = google.auth.transport.requests.AuthorizedSession( credentials=mock.Mock() ) auth_session.configure_mtls_channel(mock_callback) assert auth_session.is_mtls assert isinstance( auth_session.adapters["https://"], google.auth.transport.requests._MutualTlsAdapter, )
Example #8
Source File: test_client.py From python-firestore with Apache License 2.0 | 6 votes |
def test___database_string_property(self): credentials = _make_credentials() database = "cheeeeez" with pytest.deprecated_call(): client = self._make_one( project=self.PROJECT, credentials=credentials, database=database ) self.assertIsNone(client._database_string_internal) database_string = client._database_string expected = "projects/{}/databases/{}".format(client.project, client._database) self.assertEqual(database_string, expected) self.assertIs(database_string, client._database_string_internal) # Swap it out with a unique value to verify it is cached. client._database_string_internal = mock.sentinel.cached self.assertIs(client._database_string, mock.sentinel.cached)
Example #9
Source File: test_grpc.py From google-auth-library-python with Apache License 2.0 | 6 votes |
def test_grpc_request_with_regular_credentials(http_request): credentials, project_id = google.auth.default() credentials = google.auth.credentials.with_scopes_if_required( credentials, ["https://www.googleapis.com/auth/pubsub"] ) transport = publisher_grpc_transport.PublisherGrpcTransport( address=publisher_client.PublisherClient.SERVICE_ADDRESS, credentials=credentials, ) # Create a pub/sub client. client = pubsub_v1.PublisherClient(transport=transport) # list the topics and drain the iterator to test that an authorized API # call works. list_topics_iter = client.list_topics(project="projects/{}".format(project_id)) list(list_topics_iter)
Example #10
Source File: test_mtls_http.py From google-auth-library-python with Apache License 2.0 | 6 votes |
def test_requests_with_default_client_cert_source(): credentials, project_id = google.auth.default() credentials = google.auth.credentials.with_scopes_if_required( credentials, ["https://www.googleapis.com/auth/pubsub"] ) authed_session = google.auth.transport.requests.AuthorizedSession(credentials) if mtls.has_default_client_cert_source(): authed_session.configure_mtls_channel( client_cert_callback=mtls.default_client_cert_source() ) assert authed_session.is_mtls # Sleep 1 second to avoid 503 error. time.sleep(1) response = authed_session.get(MTLS_ENDPOINT.format(project_id)) assert response.ok
Example #11
Source File: test_mtls_http.py From google-auth-library-python with Apache License 2.0 | 6 votes |
def test_urllib3(): credentials, project_id = google.auth.default() credentials = google.auth.credentials.with_scopes_if_required( credentials, ["https://www.googleapis.com/auth/pubsub"] ) authed_http = google.auth.transport.urllib3.AuthorizedHttp(credentials) is_mtls = authed_http.configure_mtls_channel() # If the devices has default client cert source, then a mutual TLS channel # is supposed to be created. assert is_mtls == mtls.has_default_client_cert_source() # Sleep 1 second to avoid 503 error. time.sleep(1) if is_mtls: response = authed_http.request("GET", MTLS_ENDPOINT.format(project_id)) else: response = authed_http.request("GET", REGULAR_ENDPOINT.format(project_id)) assert response.status == 200
Example #12
Source File: test_mtls_http.py From google-auth-library-python with Apache License 2.0 | 6 votes |
def test_requests(): credentials, project_id = google.auth.default() credentials = google.auth.credentials.with_scopes_if_required( credentials, ["https://www.googleapis.com/auth/pubsub"] ) authed_session = google.auth.transport.requests.AuthorizedSession(credentials) authed_session.configure_mtls_channel() # If the devices has default client cert source, then a mutual TLS channel # is supposed to be created. assert authed_session.is_mtls == mtls.has_default_client_cert_source() # Sleep 1 second to avoid 503 error. time.sleep(1) if authed_session.is_mtls: response = authed_session.get(MTLS_ENDPOINT.format(project_id)) else: response = authed_session.get(REGULAR_ENDPOINT.format(project_id)) assert response.ok
Example #13
Source File: test_auth.py From pandas-gbq with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_get_credentials_default_credentials(monkeypatch): import google.auth import google.auth.credentials import google.cloud.bigquery def mock_default_credentials(scopes=None, request=None): return ( mock.create_autospec(google.auth.credentials.Credentials), "default-project", ) monkeypatch.setattr(google.auth, "default", mock_default_credentials) credentials, project = auth.get_credentials() assert project == "default-project" assert credentials is not None
Example #14
Source File: test_auth.py From pandas-gbq with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_get_credentials_load_user_no_default(monkeypatch): import google.auth import google.auth.credentials import pydata_google_auth.cache def mock_default_credentials(scopes=None, request=None): return (None, None) monkeypatch.setattr(google.auth, "default", mock_default_credentials) mock_user_credentials = mock.create_autospec( google.auth.credentials.Credentials ) mock_cache = mock.create_autospec( pydata_google_auth.cache.CredentialsCache ) mock_cache.load.return_value = mock_user_credentials monkeypatch.setattr(auth, "get_credentials_cache", lambda _: mock_cache) credentials, project = auth.get_credentials() assert project is None assert credentials is mock_user_credentials
Example #15
Source File: test_requests.py From google-auth-library-python with Apache License 2.0 | 6 votes |
def test_request_no_refresh(self): credentials = mock.Mock(wraps=CredentialsStub()) response = make_response() adapter = AdapterStub([response]) authed_session = google.auth.transport.requests.AuthorizedSession(credentials) authed_session.mount(self.TEST_URL, adapter) result = authed_session.request("GET", self.TEST_URL) assert response == result assert credentials.before_request.called assert not credentials.refresh.called assert len(adapter.requests) == 1 assert adapter.requests[0].url == self.TEST_URL assert adapter.requests[0].headers["authorization"] == "token"
Example #16
Source File: test_bucket.py From Particle-Cloud-Framework with Apache License 2.0 | 5 votes |
def _make_credentials(): import google.auth.credentials return mock.Mock(spec=google.auth.credentials.Credentials)
Example #17
Source File: test_iam.py From google-auth-library-python with Apache License 2.0 | 5 votes |
def test_key_id(self): signer = iam.Signer( mock.sentinel.request, mock.sentinel.credentials, mock.sentinel.service_account_email, ) assert signer.key_id is None
Example #18
Source File: test_bucket.py From Particle-Cloud-Framework with Apache License 2.0 | 5 votes |
def _make_one(self,project,credentials): from google.cloud.storage.client import Client return Client(project=project, credentials=credentials)
Example #19
Source File: test_iam.py From google-auth-library-python with Apache License 2.0 | 5 votes |
def test_constructor(self): request = mock.sentinel.request credentials = mock.create_autospec( google.auth.credentials.Credentials, instance=True ) signer = iam.Signer(request, credentials, mock.sentinel.service_account_email) assert signer._request == mock.sentinel.request assert signer._credentials == credentials assert signer._service_account_email == mock.sentinel.service_account_email
Example #20
Source File: test_requests.py From google-auth-library-python with Apache License 2.0 | 5 votes |
def test_constructor_with_auth_request(self): http = mock.create_autospec(requests.Session) auth_request = google.auth.transport.requests.Request(http) authed_session = google.auth.transport.requests.AuthorizedSession( mock.sentinel.credentials, auth_request=auth_request ) assert authed_session._auth_request == auth_request
Example #21
Source File: base_google.py From airflow with Apache License 2.0 | 5 votes |
def provide_gcp_credential_file(func: Callable[..., RT]) -> Callable[..., RT]: """ Function decorator that provides a GCP credentials for application supporting Application Default Credentials (ADC) strategy. It is recommended to use ``provide_gcp_credential_file_as_context`` context manager to limit the scope when authorization data is available. Using context manager also makes it easier to use multiple connection in one function. """ @functools.wraps(func) def wrapper(self: GoogleBaseHook, *args, **kwargs) -> RT: with self.provide_gcp_credential_file_as_context(): return func(self, *args, **kwargs) return wrapper
Example #22
Source File: base_google.py From airflow with Apache License 2.0 | 5 votes |
def _authorize(self) -> google_auth_httplib2.AuthorizedHttp: """ Returns an authorized HTTP object to be used to build a Google cloud service hook connection. """ credentials = self._get_credentials() http = build_http() http = set_user_agent(http, "airflow/" + version.version) authed_http = google_auth_httplib2.AuthorizedHttp(credentials, http=http) return authed_http
Example #23
Source File: base_google.py From airflow with Apache License 2.0 | 5 votes |
def _get_credentials(self) -> google.auth.credentials.Credentials: """ Returns the Credentials object for Google API """ credentials, _ = self._get_credentials_and_project_id() return credentials
Example #24
Source File: base_google.py From airflow with Apache License 2.0 | 5 votes |
def _get_credentials_and_project_id(self) -> Tuple[google.auth.credentials.Credentials, Optional[str]]: """ Returns the Credentials object for Google API and the associated project_id """ if self._cached_credentials is not None: return self._cached_credentials, self._cached_project_id key_path: Optional[str] = self._get_field('key_path', None) try: keyfile_dict: Optional[str] = self._get_field('keyfile_dict', None) keyfile_dict_json: Optional[Dict[str, str]] = None if keyfile_dict: keyfile_dict_json = json.loads(keyfile_dict) except json.decoder.JSONDecodeError: raise AirflowException('Invalid key JSON.') credentials, project_id = get_credentials_and_project_id( key_path=key_path, keyfile_dict=keyfile_dict_json, scopes=self.scopes, delegate_to=self.delegate_to ) overridden_project_id = self._get_field('project') if overridden_project_id: project_id = overridden_project_id self._cached_credentials = credentials self._cached_project_id = project_id return credentials, project_id
Example #25
Source File: base_google.py From airflow with Apache License 2.0 | 5 votes |
def __init__(self, gcp_conn_id: str = 'google_cloud_default', delegate_to: Optional[str] = None) -> None: super().__init__() self.gcp_conn_id = gcp_conn_id self.delegate_to = delegate_to self.extras = self.get_connection(self.gcp_conn_id).extra_dejson # type: Dict self._cached_credentials: Optional[google.auth.credentials.Credentials] = None self._cached_project_id: Optional[str] = None
Example #26
Source File: test_automl.py From docker-python with Apache License 2.0 | 5 votes |
def test_default_credentials_prediction_client(self): env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'AUTOML') with env: prediction_client = automl.PredictionServiceClient() self.assertIsNotNone(prediction_client.credentials) self.assertIsInstance(prediction_client.credentials, KaggleKernelCredentials) self.assertTrue(prediction_client._connection.user_agent.startswith("kaggle-gcp-client/1.0"))
Example #27
Source File: test_automl.py From docker-python with Apache License 2.0 | 5 votes |
def test_default_credentials_tables_client(self): env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'AUTOML') with env: init_automl() tables_client = automl_v1beta1.TablesClient() self.assertIsNotNone(tables_client.credentials) self.assertIsInstance(tables_client.credentials, KaggleKernelCredentials) self.assertTrue(tables_client._connection.user_agent.startswith("kaggle-gcp-client/1.0"))
Example #28
Source File: test_automl.py From docker-python with Apache License 2.0 | 5 votes |
def test_default_credentials_automl_v1beta1_client(self): env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'AUTOML') with env: init_automl() automl_client = automl_v1beta1.AutoMlClient() self.assertIsNotNone(automl_client.credentials) self.assertIsInstance(automl_client.credentials, KaggleKernelCredentials) self.assertTrue(automl_client._connection.user_agent.startswith("kaggle-gcp-client/1.0"))
Example #29
Source File: test_automl.py From docker-python with Apache License 2.0 | 5 votes |
def test_default_credentials_automl_client(self): env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'AUTOML') with env: init_automl() automl_client = automl.AutoMlClient() self.assertIsNotNone(automl_client.credentials) self.assertIsInstance(automl_client.credentials, KaggleKernelCredentials) self.assertTrue(automl_client._connection.user_agent.startswith("kaggle-gcp-client/1.0"))
Example #30
Source File: test_automl.py From docker-python with Apache License 2.0 | 5 votes |
def test_tables_client_credentials(self): credentials = _make_credentials() env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'AUTOML') with env: init_automl() tables_client = automl_v1beta1.TablesClient(credentials=credentials) self.assertEqual(tables_client.auto_ml_client.credentials, credentials)