Best Python code snippet using tempest_python
id_token_credentials.py
Source:id_token_credentials.py
...81 raise exceptions.DefaultCredentialsError(82 f"The file {filename} does not have a valid type. Type is {credential_type}, "83 f"expected one of {_VALID_TYPES}."84 )85def _get_explicit_environ_credentials(86 target_audience: Optional[str],87) -> Optional[google_auth_credentials.Credentials]:88 """Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment variable."""89 explicit_file = os.environ.get(environment_vars.CREDENTIALS)90 if explicit_file is None:91 return None92 current_credentials = _load_credentials_from_file(93 os.environ[environment_vars.CREDENTIALS], target_audience=target_audience94 )95 return current_credentials96def _get_gcloud_sdk_credentials(97 target_audience: Optional[str],98) -> Optional[google_auth_credentials.Credentials]:99 """Gets the credentials and project ID from the Cloud SDK."""100 from google.auth import _cloud_sdk101 # Check if application default credentials exist.102 credentials_filename = _cloud_sdk.get_application_default_credentials_path()103 if not os.path.isfile(credentials_filename):104 return None105 current_credentials = _load_credentials_from_file(credentials_filename, target_audience)106 return current_credentials107def _get_gce_credentials(108 target_audience: Optional[str], request: Optional[google.auth.transport.Request] = None109) -> Optional[google_auth_credentials.Credentials]:110 """Gets credentials and project ID from the GCE Metadata Service."""111 # Ping requires a transport, but we want application default credentials112 # to require no arguments. So, we'll use the _http_client transport which113 # uses http.client. This is only acceptable because the metadata server114 # doesn't do SSL and never requires proxies.115 # While this library is normally bundled with compute_engine, there are116 # some cases where it's not available, so we tolerate ImportError.117 try:118 from google.auth import compute_engine119 from google.auth.compute_engine import _metadata120 except ImportError:121 return None122 from google.auth.transport import _http_client123 if request is None:124 request = _http_client.Request()125 if _metadata.ping(request=request):126 return compute_engine.IDTokenCredentials(127 request, target_audience, use_metadata_identity_endpoint=True128 )129 return None130def get_default_id_token_credentials(131 target_audience: Optional[str], request: google.auth.transport.Request = None132) -> google_auth_credentials.Credentials:133 """Gets the default ID Token credentials for the current environment.134 `Application Default Credentials`_ provides an easy way to obtain credentials to call Google APIs for135 server-to-server or local applications.136 .. _Application Default Credentials: https://developers.google.com\137 /identity/protocols/application-default-credentials138 :param target_audience: The intended audience for these credentials.139 :type target_audience: Sequence[str]140 :param request: An object used to make HTTP requests. This is used to detect whether the application141 is running on Compute Engine. If not specified, then it will use the standard library http client142 to make requests.143 :type request: google.auth.transport.Request144 :return: the current environment's credentials.145 :rtype: google.auth.credentials.Credentials146 :raises ~google.auth.exceptions.DefaultCredentialsError:147 If no credentials were found, or if the credentials found were invalid.148 """149 checkers = (150 lambda: _get_explicit_environ_credentials(target_audience),151 lambda: _get_gcloud_sdk_credentials(target_audience),152 lambda: _get_gce_credentials(target_audience, request),153 )154 for checker in checkers:155 current_credentials = checker()156 if current_credentials is not None:157 return current_credentials158 raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)159if __name__ == "__main__":160 from google.auth.transport import requests161 request_adaapter = requests.Request()162 creds = get_default_id_token_credentials(target_audience=None)163 creds.refresh(request=request_adaapter)...
browser_credentials.py
Source:browser_credentials.py
1# Copyright 2012 The Chromium Authors. All rights reserved.2# Use of this source code is governed by a BSD-style license that can be3# found in the LICENSE file.4import json5import logging6import os7from telemetry.core import util8from telemetry.internal.backends import codepen_credentials_backend9from telemetry.internal.backends import facebook_credentials_backend10from telemetry.internal.backends import google_credentials_backend11from telemetry.testing import options_for_unittests12class CredentialsError(Exception):13 """Error that can be thrown when logging in."""14class BrowserCredentials(object):15 def __init__(self, backends=None):16 self._credentials = {}17 self._credentials_path = None18 self._extra_credentials = {}19 if backends is None:20 backends = [21 codepen_credentials_backend.CodePenCredentialsBackend(),22 facebook_credentials_backend.FacebookCredentialsBackend(),23 facebook_credentials_backend.FacebookCredentialsBackend2(),24 google_credentials_backend.GoogleCredentialsBackend(),25 google_credentials_backend.GoogleCredentialsBackend2()]26 self._backends = {}27 for backend in backends:28 self._backends[backend.credentials_type] = backend29 def AddBackend(self, backend):30 assert backend.credentials_type not in self._backends31 self._backends[backend.credentials_type] = backend32 def IsLoggedIn(self, credentials_type):33 if credentials_type not in self._backends:34 raise CredentialsError(35 'Unrecognized credentials type: %s', credentials_type)36 if credentials_type not in self._credentials:37 return False38 return self._backends[credentials_type].IsLoggedIn()39 def CanLogin(self, credentials_type):40 if credentials_type not in self._backends:41 raise CredentialsError(42 'Unrecognized credentials type: %s', credentials_type)43 return credentials_type in self._credentials44 def LoginNeeded(self, tab, credentials_type):45 if credentials_type not in self._backends:46 raise CredentialsError(47 'Unrecognized credentials type: %s', credentials_type)48 if credentials_type not in self._credentials:49 return False50 runner = tab.action_runner51 return self._backends[credentials_type].LoginNeeded(52 tab, runner, self._credentials[credentials_type])53 def LoginNoLongerNeeded(self, tab, credentials_type):54 assert credentials_type in self._backends55 self._backends[credentials_type].LoginNoLongerNeeded(tab)56 @property57 def credentials_path(self):58 return self._credentials_path59 @credentials_path.setter60 def credentials_path(self, credentials_path):61 self._credentials_path = credentials_path62 self._RebuildCredentials()63 def Add(self, credentials_type, data):64 if credentials_type not in self._extra_credentials:65 self._extra_credentials[credentials_type] = {}66 for k, v in data.items():67 assert k not in self._extra_credentials[credentials_type]68 self._extra_credentials[credentials_type][k] = v69 self._RebuildCredentials()70 def _ResetLoggedInState(self):71 """Makes the backends think we're not logged in even though we are.72 Should only be used in unit tests to simulate --dont-override-profile.73 """74 for backend in self._backends.keys():75 # pylint: disable=protected-access76 self._backends[backend]._ResetLoggedInState()77 def _RebuildCredentials(self):78 credentials = {}79 if self._credentials_path == None:80 pass81 elif os.path.exists(self._credentials_path):82 with open(self._credentials_path, 'r') as f:83 credentials = json.loads(f.read())84 # TODO(nduca): use system keychain, if possible.85 homedir_credentials_path = os.path.expanduser('~/.telemetry-credentials')86 homedir_credentials = {}87 if (not options_for_unittests.GetCopy() and88 os.path.exists(homedir_credentials_path)):89 logging.info("Found ~/.telemetry-credentials. Its contents will be used "90 "when no other credentials can be found.")91 with open(homedir_credentials_path, 'r') as f:92 homedir_credentials = json.loads(f.read())93 self._credentials = {}94 all_keys = set(credentials.keys()).union(95 homedir_credentials.keys()).union(96 self._extra_credentials.keys())97 for k in all_keys:98 if k in credentials:99 self._credentials[k] = credentials[k]100 if k in homedir_credentials:101 logging.info("Will use ~/.telemetry-credentials for %s logins." % k)102 self._credentials[k] = homedir_credentials[k]103 if k in self._extra_credentials:104 self._credentials[k] = self._extra_credentials[k]105 def WarnIfMissingCredentials(self, page):106 if page.credentials and not self.CanLogin(page.credentials):107 files_to_tweak = []108 if page.credentials_path:109 files_to_tweak.append(page.credentials_path)110 files_to_tweak.append('~/.telemetry-credentials')111 example_credentials_file = os.path.join(112 util.GetTelemetryDir(), 'examples', 'credentials_example.json')113 logging.warning("""114 Credentials for %s were not found. page %s will not be tested.115 To fix this, either follow the instructions to authenticate to gsutil116 here:117 http://www.chromium.org/developers/telemetry/upload_to_cloud_storage,118 or add your own credentials to:119 %s120 An example credentials file you can copy from is here:121 %s\n""" % (page.credentials, page, ' or '.join(files_to_tweak),...
credentials.py
Source:credentials.py
...18 if credentials_type == 'authorized_user':19 return ApplicationDefaultCredentials(credentials)20 raise ValueError(f'unknown Google Cloud credentials type {credentials_type}')21 @staticmethod22 def default_credentials():23 credentials_file = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS')24 if credentials_file is None:25 application_default_credentials_file = f'{os.environ["HOME"]}/.config/gcloud/application_default_credentials.json'26 if os.path.exists(application_default_credentials_file):27 credentials_file = application_default_credentials_file28 if credentials_file:29 log.info(f'using credentials file {credentials_file}')30 return Credentials.from_file(credentials_file)31 log.warning('unable to locate Google Cloud credentials file, will attempt to '32 'use instance metadata server instead')33 return InstanceMetadataCredentials()34 async def get_access_token(self, session):35 pass36# protocol documented here:...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!