googleapis / google-auth-library-python

Google Auth Python Library
https://googleapis.dev/python/google-auth/latest/
Apache License 2.0
776 stars 306 forks source link

2.11.0: pytest is failing #1120

Closed kloczek closed 1 year ago

kloczek commented 2 years ago

Environment details

Steps to reproduce

I'm packaging your module as an rpm package so I'm using the typical PEP517 based build, install and test cycle used on building packages from non-root account.

In below pytesst execution I have vfew files on --ignore list because I have no yest packaged all necessry moduels. tests/test__oauth2client.py is on that listr because https://github.com/googleapis/google-auth-library-python/issues/1118

List of modules installed in build env

```console Package Version ----------------------------- ----------------- aiohttp 3.8.1 aioresponses 0.7.3 aiosignal 1.2.0 alabaster 0.7.12 appdirs 1.4.4 async-timeout 4.0.2 attrs 22.1.0 Babel 2.10.2 Brlapi 0.8.3 build 0.8.0 cachetools 5.2.0 certifi 2021.10.8 cffi 1.15.1 charset-normalizer 2.1.0 click 8.1.2 codespell 2.1.0 cryptography 36.0.2 cssselect 1.1.0 distro 1.7.0 docutils 0.18.1 extras 1.0.0 fixtures 4.0.0 Flask 2.2.1 freezegun 1.2.1 frozenlist 1.3.1 gpg 1.17.1-unknown idna 3.3 imagesize 1.4.1 importlib-metadata 4.12.0 iniconfig 1.1.1 itsdangerous 2.1.2 Jinja2 3.1.1 libcomps 0.1.18 louis 3.22.0 lxml 4.9.1 MarkupSafe 2.1.1 mock 4.0.3 multidict 6.0.2 numpy 1.23.1 packaging 21.3 pbr 5.9.0 pep517 0.12.0 pip 22.2.1 pluggy 1.0.0 ply 3.11 py 1.11.0 pyasn1 0.4.8 pyasn1-modules 0.2.8 pycparser 2.21 Pygments 2.13.0 PyGObject 3.42.2 pyOpenSSL 22.0.0 pyparsing 3.0.9 pytest 7.1.2 pytest-asyncio 0.19.0 pytest-localserver 0.6.0 python-dateutil 2.8.2 pytz 2022.1 pyu2f 0.1.5 requests 2.28.1 responses 0.21.0 rpm 4.17.0 rsa 4.8 scour 0.38.2 setuptools 65.3.0 six 1.16.0 snowballstemmer 2.2.0 Sphinx 5.1.1 sphinx-docstring-typing 0.0.4 sphinxcontrib-applehelp 1.0.2.dev20220730 sphinxcontrib-devhelp 1.0.2.dev20220730 sphinxcontrib-htmlhelp 2.0.0 sphinxcontrib-jsmath 1.0.1.dev20220730 sphinxcontrib-qthelp 1.0.3.dev20220730 sphinxcontrib-serializinghtml 1.1.5 testtools 2.5.0 tomli 2.0.1 urllib3 1.26.12 Werkzeug 2.2.2 wheel 0.37.1 yarl 1.8.1 zipp 3.8.1 ```
kloczek commented 2 years ago

Here is pytest output:

```console + PYTHONPATH=/home/tkloczko/rpmbuild/BUILDROOT/python-google-auth-2.11.0-2.fc35.x86_64/usr/lib64/python3.8/site-packages:/home/tkloczko/rpmbuild/BUILDROOT/python-google-auth-2.11.0-2.fc35.x86_64/usr/lib/python3.8/site-packages + /usr/bin/pytest -ra --ignore tests/test__oauth2client.py --ignore system_tests/system_tests_sync/test_grpc.py --ignore system_tests/system_tests_sync/test_downscoping.py --ignore system_tests/system_tests_sync/test_app_engine.py --ignore system_tests/system_tests_sync/test_external_accounts.py =========================================================================== test session starts ============================================================================ platform linux -- Python 3.8.13, pytest-7.1.2, pluggy-1.0.0 rootdir: /home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0 plugins: asyncio-0.19.0, localserver-0.6.0 asyncio: mode=strict collected 1088 items system_tests/system_tests_async/test_default.py F [ 0%] system_tests/system_tests_async/test_id_token.py F [ 0%] system_tests/system_tests_async/test_service_account.py EE [ 0%] system_tests/system_tests_sync/test_compute_engine.py ssssssss [ 1%] system_tests/system_tests_sync/test_default.py FF [ 1%] system_tests/system_tests_sync/test_id_token.py FF [ 1%] system_tests/system_tests_sync/test_impersonated_credentials.py EEEE [ 1%] system_tests/system_tests_sync/test_mtls_http.py FFFF [ 2%] system_tests/system_tests_sync/test_oauth2_credentials.py EE [ 2%] system_tests/system_tests_sync/test_requests.py F [ 2%] system_tests/system_tests_sync/test_service_account.py EEEEEE [ 3%] system_tests/system_tests_sync/test_urllib3.py F [ 3%] tests/test__cloud_sdk.py ....F......... [ 4%] tests/test__default.py ............................................................................. [ 11%] tests/test__helpers.py ................... [ 13%] tests/test__service_account_info.py ...... [ 13%] tests/test_app_engine.py ................ [ 15%] tests/test_aws.py ................................................ [ 19%] tests/test_credentials.py ............ [ 20%] tests/test_downscoped.py ................................... [ 23%] tests/test_external_account.py ......................................................................................... [ 32%] tests/test_iam.py .... [ 32%] tests/test_identity_pool.py ............................................. [ 36%] tests/test_impersonated_credentials.py ............................ [ 39%] tests/test_jwt.py ........................................................ [ 44%] tests/test_pluggable.py ............................... [ 47%] tests/compute_engine/test__metadata.py ..................... [ 49%] tests/compute_engine/test_credentials.py .......................... [ 51%] tests/crypt/test__cryptography_rsa.py ................ [ 53%] tests/crypt/test__python_rsa.py .................. [ 54%] tests/crypt/test_crypt.py .. [ 54%] tests/crypt/test_es256.py .............. [ 56%] tests/oauth2/test__client.py ................. [ 57%] tests/oauth2/test_challenges.py .... [ 58%] tests/oauth2/test_credentials.py .............................. [ 60%] tests/oauth2/test_gdch_credentials.py ....... [ 61%] tests/oauth2/test_id_token.py .................. [ 63%] tests/oauth2/test_reauth.py .................. [ 64%] tests/oauth2/test_service_account.py ...................................... [ 68%] tests/oauth2/test_sts.py ......... [ 69%] tests/oauth2/test_utils.py ............... [ 70%] tests/transport/test__custom_tls_signer.py .......... [ 71%] tests/transport/test__http_client.py ....... [ 72%] tests/transport/test__mtls_helper.py ......................... [ 74%] tests/transport/test_grpc.py sssssssssssssss [ 75%] tests/transport/test_mtls.py ... [ 76%] tests/transport/test_requests.py ..................................... [ 79%] tests/transport/test_urllib3.py ........................ [ 81%] tests_async/test__default_async.py ........................................... [ 85%] tests_async/test_credentials_async.py ............ [ 86%] tests_async/test_jwt_async.py ............................. [ 89%] tests_async/oauth2/test__client_async.py ........... [ 90%] tests_async/oauth2/test_credentials_async.py ................... [ 92%] tests_async/oauth2/test_id_token.py ................ [ 93%] tests_async/oauth2/test_reauth_async.py ................. [ 95%] tests_async/oauth2/test_service_account_async.py ........................... [ 97%] tests_async/transport/test_aiohttp_requests.py .......................... [100%] ================================================================================== ERRORS ================================================================================== ____________________________________________________________ ERROR at setup of test_refresh_no_scopes[aiohttp] _____________________________________________________________ service_account_file = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' @pytest.fixture def credentials(service_account_file): > yield _service_account_async.Credentials.from_service_account_file(service_account_file) system_tests/system_tests_async/test_service_account.py:25: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ google/oauth2/service_account.py:238: in from_service_account_file info, signer = _service_account_info.from_filename( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ filename = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' require = ['client_email', 'token_uri'], use_rsa_signer = True def from_filename(filename, require=None, use_rsa_signer=True): """Reads a Google service account JSON file and returns its parsed info. Args: filename (str): The path to the service account .json file. require (Sequence[str]): List of keys required to be present in the info. use_rsa_signer (Optional[bool]): Whether to use RSA signer or EC signer. We use RSA signer by default. Returns: Tuple[ Mapping[str, str], google.auth.crypt.Signer ]: The verified info and a signer instance. """ > with io.open(filename, "r", encoding="utf-8") as json_file: E FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' google/auth/_service_account_info.py:79: FileNotFoundError _____________________________________________________________ ERROR at setup of test_refresh_success[aiohttp] ______________________________________________________________ service_account_file = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' @pytest.fixture def credentials(service_account_file): > yield _service_account_async.Credentials.from_service_account_file(service_account_file) system_tests/system_tests_async/test_service_account.py:25: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ google/oauth2/service_account.py:238: in from_service_account_file info, signer = _service_account_info.from_filename( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ filename = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' require = ['client_email', 'token_uri'], use_rsa_signer = True def from_filename(filename, require=None, use_rsa_signer=True): """Reads a Google service account JSON file and returns its parsed info. Args: filename (str): The path to the service account .json file. require (Sequence[str]): List of keys required to be present in the info. use_rsa_signer (Optional[bool]): Whether to use RSA signer or EC signer. We use RSA signer by default. Returns: Tuple[ Mapping[str, str], google.auth.crypt.Signer ]: The verified info and a signer instance. """ > with io.open(filename, "r", encoding="utf-8") as json_file: E FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' google/auth/_service_account_info.py:79: FileNotFoundError _________________________________________________ ERROR at setup of test_refresh_with_user_credentials_as_source[urllib3] __________________________________________________ @pytest.fixture def authorized_user_file(): """The full path to a valid authorized user file.""" > yield AUTHORIZED_USER_FILE E NameError: name 'AUTHORIZED_USER_FILE' is not defined system_tests/system_tests_sync/conftest.py:53: NameError _________________________________________________ ERROR at setup of test_refresh_with_user_credentials_as_source[requests] _________________________________________________ @pytest.fixture def authorized_user_file(): """The full path to a valid authorized user file.""" > yield AUTHORIZED_USER_FILE E NameError: name 'AUTHORIZED_USER_FILE' is not defined system_tests/system_tests_sync/conftest.py:53: NameError ____________________________________________ ERROR at setup of test_refresh_with_service_account_credentials_as_source[urllib3] ____________________________________________ service_account_file = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' @pytest.fixture def service_account_credentials(service_account_file): > yield service_account.Credentials.from_service_account_file(service_account_file) system_tests/system_tests_sync/test_impersonated_credentials.py:29: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ google/oauth2/service_account.py:238: in from_service_account_file info, signer = _service_account_info.from_filename( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ filename = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' require = ['client_email', 'token_uri'], use_rsa_signer = True def from_filename(filename, require=None, use_rsa_signer=True): """Reads a Google service account JSON file and returns its parsed info. Args: filename (str): The path to the service account .json file. require (Sequence[str]): List of keys required to be present in the info. use_rsa_signer (Optional[bool]): Whether to use RSA signer or EC signer. We use RSA signer by default. Returns: Tuple[ Mapping[str, str], google.auth.crypt.Signer ]: The verified info and a signer instance. """ > with io.open(filename, "r", encoding="utf-8") as json_file: E FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' google/auth/_service_account_info.py:79: FileNotFoundError ___________________________________________ ERROR at setup of test_refresh_with_service_account_credentials_as_source[requests] ____________________________________________ service_account_file = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' @pytest.fixture def service_account_credentials(service_account_file): > yield service_account.Credentials.from_service_account_file(service_account_file) system_tests/system_tests_sync/test_impersonated_credentials.py:29: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ google/oauth2/service_account.py:238: in from_service_account_file info, signer = _service_account_info.from_filename( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ filename = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' require = ['client_email', 'token_uri'], use_rsa_signer = True def from_filename(filename, require=None, use_rsa_signer=True): """Reads a Google service account JSON file and returns its parsed info. Args: filename (str): The path to the service account .json file. require (Sequence[str]): List of keys required to be present in the info. use_rsa_signer (Optional[bool]): Whether to use RSA signer or EC signer. We use RSA signer by default. Returns: Tuple[ Mapping[str, str], google.auth.crypt.Signer ]: The verified info and a signer instance. """ > with io.open(filename, "r", encoding="utf-8") as json_file: E FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' google/auth/_service_account_info.py:79: FileNotFoundError _________________________________________________________________ ERROR at setup of test_refresh[urllib3] __________________________________________________________________ @pytest.fixture def authorized_user_file(): """The full path to a valid authorized user file.""" > yield AUTHORIZED_USER_FILE E NameError: name 'AUTHORIZED_USER_FILE' is not defined system_tests/system_tests_sync/conftest.py:53: NameError _________________________________________________________________ ERROR at setup of test_refresh[requests] _________________________________________________________________ @pytest.fixture def authorized_user_file(): """The full path to a valid authorized user file.""" > yield AUTHORIZED_USER_FILE E NameError: name 'AUTHORIZED_USER_FILE' is not defined system_tests/system_tests_sync/conftest.py:53: NameError ____________________________________________________________ ERROR at setup of test_refresh_no_scopes[urllib3] _____________________________________________________________ service_account_file = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' @pytest.fixture def credentials(service_account_file): > yield service_account.Credentials.from_service_account_file(service_account_file) system_tests/system_tests_sync/test_service_account.py:25: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ google/oauth2/service_account.py:238: in from_service_account_file info, signer = _service_account_info.from_filename( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ filename = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' require = ['client_email', 'token_uri'], use_rsa_signer = True def from_filename(filename, require=None, use_rsa_signer=True): """Reads a Google service account JSON file and returns its parsed info. Args: filename (str): The path to the service account .json file. require (Sequence[str]): List of keys required to be present in the info. use_rsa_signer (Optional[bool]): Whether to use RSA signer or EC signer. We use RSA signer by default. Returns: Tuple[ Mapping[str, str], google.auth.crypt.Signer ]: The verified info and a signer instance. """ > with io.open(filename, "r", encoding="utf-8") as json_file: E FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' google/auth/_service_account_info.py:79: FileNotFoundError ____________________________________________________________ ERROR at setup of test_refresh_no_scopes[requests] ____________________________________________________________ service_account_file = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' @pytest.fixture def credentials(service_account_file): > yield service_account.Credentials.from_service_account_file(service_account_file) system_tests/system_tests_sync/test_service_account.py:25: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ google/oauth2/service_account.py:238: in from_service_account_file info, signer = _service_account_info.from_filename( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ filename = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' require = ['client_email', 'token_uri'], use_rsa_signer = True def from_filename(filename, require=None, use_rsa_signer=True): """Reads a Google service account JSON file and returns its parsed info. Args: filename (str): The path to the service account .json file. require (Sequence[str]): List of keys required to be present in the info. use_rsa_signer (Optional[bool]): Whether to use RSA signer or EC signer. We use RSA signer by default. Returns: Tuple[ Mapping[str, str], google.auth.crypt.Signer ]: The verified info and a signer instance. """ > with io.open(filename, "r", encoding="utf-8") as json_file: E FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' google/auth/_service_account_info.py:79: FileNotFoundError _____________________________________________________________ ERROR at setup of test_refresh_success[urllib3] ______________________________________________________________ service_account_file = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' @pytest.fixture def credentials(service_account_file): > yield service_account.Credentials.from_service_account_file(service_account_file) system_tests/system_tests_sync/test_service_account.py:25: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ google/oauth2/service_account.py:238: in from_service_account_file info, signer = _service_account_info.from_filename( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ filename = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' require = ['client_email', 'token_uri'], use_rsa_signer = True def from_filename(filename, require=None, use_rsa_signer=True): """Reads a Google service account JSON file and returns its parsed info. Args: filename (str): The path to the service account .json file. require (Sequence[str]): List of keys required to be present in the info. use_rsa_signer (Optional[bool]): Whether to use RSA signer or EC signer. We use RSA signer by default. Returns: Tuple[ Mapping[str, str], google.auth.crypt.Signer ]: The verified info and a signer instance. """ > with io.open(filename, "r", encoding="utf-8") as json_file: E FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' google/auth/_service_account_info.py:79: FileNotFoundError _____________________________________________________________ ERROR at setup of test_refresh_success[requests] _____________________________________________________________ service_account_file = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' @pytest.fixture def credentials(service_account_file): > yield service_account.Credentials.from_service_account_file(service_account_file) system_tests/system_tests_sync/test_service_account.py:25: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ google/oauth2/service_account.py:238: in from_service_account_file info, signer = _service_account_info.from_filename( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ filename = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' require = ['client_email', 'token_uri'], use_rsa_signer = True def from_filename(filename, require=None, use_rsa_signer=True): """Reads a Google service account JSON file and returns its parsed info. Args: filename (str): The path to the service account .json file. require (Sequence[str]): List of keys required to be present in the info. use_rsa_signer (Optional[bool]): Whether to use RSA signer or EC signer. We use RSA signer by default. Returns: Tuple[ Mapping[str, str], google.auth.crypt.Signer ]: The verified info and a signer instance. """ > with io.open(filename, "r", encoding="utf-8") as json_file: E FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' google/auth/_service_account_info.py:79: FileNotFoundError ________________________________________________________________ ERROR at setup of test_iam_signer[urllib3] ________________________________________________________________ service_account_file = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' @pytest.fixture def credentials(service_account_file): > yield service_account.Credentials.from_service_account_file(service_account_file) system_tests/system_tests_sync/test_service_account.py:25: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ google/oauth2/service_account.py:238: in from_service_account_file info, signer = _service_account_info.from_filename( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ filename = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' require = ['client_email', 'token_uri'], use_rsa_signer = True def from_filename(filename, require=None, use_rsa_signer=True): """Reads a Google service account JSON file and returns its parsed info. Args: filename (str): The path to the service account .json file. require (Sequence[str]): List of keys required to be present in the info. use_rsa_signer (Optional[bool]): Whether to use RSA signer or EC signer. We use RSA signer by default. Returns: Tuple[ Mapping[str, str], google.auth.crypt.Signer ]: The verified info and a signer instance. """ > with io.open(filename, "r", encoding="utf-8") as json_file: E FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' google/auth/_service_account_info.py:79: FileNotFoundError _______________________________________________________________ ERROR at setup of test_iam_signer[requests] ________________________________________________________________ service_account_file = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' @pytest.fixture def credentials(service_account_file): > yield service_account.Credentials.from_service_account_file(service_account_file) system_tests/system_tests_sync/test_service_account.py:25: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ google/oauth2/service_account.py:238: in from_service_account_file info, signer = _service_account_info.from_filename( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ filename = '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' require = ['client_email', 'token_uri'], use_rsa_signer = True def from_filename(filename, require=None, use_rsa_signer=True): """Reads a Google service account JSON file and returns its parsed info. Args: filename (str): The path to the service account .json file. require (Sequence[str]): List of keys required to be present in the info. use_rsa_signer (Optional[bool]): Whether to use RSA signer or EC signer. We use RSA signer by default. Returns: Tuple[ Mapping[str, str], google.auth.crypt.Signer ]: The verified info and a signer instance. """ > with io.open(filename, "r", encoding="utf-8") as json_file: E FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/system_tests/system_tests_sync/../data/service_account.json' google/auth/_service_account_info.py:79: FileNotFoundError ================================================================================= FAILURES ================================================================================= ______________________________________________________________ test_application_default_credentials[aiohttp] _______________________________________________________________ verify_refresh = ._verify_refresh at 0x7f73f19e5f70> @pytest.mark.asyncio async def test_application_default_credentials(verify_refresh): > credentials, project_id = _default_async.default_async() system_tests/system_tests_async/test_default.py:24: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ scopes = None, request = None, quota_project_id = None def default_async(scopes=None, request=None, quota_project_id=None): """Gets the default credentials for the current environment. `Application Default Credentials`_ provides an easy way to obtain credentials to call Google APIs for server-to-server or local applications. This function acquires credentials from the environment in the following order: 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON private key file, then it is loaded and returned. The project ID returned is the project ID defined in the service account file if available (some older files do not contain project ID information). 2. If the `Google Cloud SDK`_ is installed and has application default credentials set they are loaded and returned. To enable application default credentials with the Cloud SDK run:: gcloud auth application-default login If the Cloud SDK has an active project, the project ID is returned. The active project can be set using:: gcloud config set project 3. If the application is running in the `App Engine standard environment`_ (first generation) then the credentials and project ID from the `App Identity Service`_ are used. 4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or the `App Engine flexible environment`_ or the `App Engine standard environment`_ (second generation) then the credentials and project ID are obtained from the `Metadata Service`_. 5. If no credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. .. _Application Default Credentials: https://developers.google.com\ /identity/protocols/application-default-credentials .. _Google Cloud SDK: https://cloud.google.com/sdk .. _App Engine standard environment: https://cloud.google.com/appengine .. _App Identity Service: https://cloud.google.com/appengine/docs/python\ /appidentity/ .. _Compute Engine: https://cloud.google.com/compute .. _App Engine flexible environment: https://cloud.google.com\ /appengine/flexible .. _Metadata Service: https://cloud.google.com/compute/docs\ /storing-retrieving-metadata .. _Cloud Run: https://cloud.google.com/run Example:: import google.auth credentials, project_id = google.auth.default() Args: scopes (Sequence[str]): The list of scopes for the credentials. If specified, the credentials will automatically be scoped if necessary. request (google.auth.transport.Request): An object used to make HTTP requests. This is used to detect whether the application is running on Compute Engine. If not specified, then it will use the standard library http client to make requests. quota_project_id (Optional[str]): The project ID used for quota and billing. Returns: Tuple[~google.auth.credentials.Credentials, Optional[str]]: the current environment's credentials and project ID. Project ID may be None, which indicates that the Project ID could not be ascertained from the environment. Raises: ~google.auth.exceptions.DefaultCredentialsError: If no credentials were found, or if the credentials found were invalid. """ from google.auth._credentials_async import with_scopes_if_required from google.auth.credentials import CredentialsWithQuotaProject explicit_project_id = os.environ.get( environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT) ) checkers = ( lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id), lambda: _get_gcloud_sdk_credentials(quota_project_id=quota_project_id), _get_gae_credentials, lambda: _get_gce_credentials(request), ) for checker in checkers: credentials, project_id = checker() if credentials is not None: credentials = with_scopes_if_required(credentials, scopes) if quota_project_id and isinstance( credentials, CredentialsWithQuotaProject ): credentials = credentials.with_quota_project(quota_project_id) effective_project_id = explicit_project_id or project_id if not effective_project_id: _default._LOGGER.warning( "No project ID could be determined. Consider running " "`gcloud config set project` or setting the %s " "environment variable", environment_vars.PROJECT, ) return credentials, effective_project_id > raise exceptions.DefaultCredentialsError(_default._HELP_MESSAGE) E google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started google/auth/_default_async.py:284: DefaultCredentialsError ---------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------- WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 1 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 2 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 3 of 3. Reason: timed out WARNING google.auth._default:_default.py:290 Authentication failed using Compute Engine authentication due to unavailable metadata server. _______________________________________________________________________ test_fetch_id_token[aiohttp] _______________________________________________________________________ http_request = @pytest.mark.asyncio async def test_fetch_id_token(http_request): audience = "https://pubsub.googleapis.com" > token = await google.oauth2._id_token_async.fetch_id_token(http_request, audience) system_tests/system_tests_async/test_id_token.py:22: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ request = , audience = 'https://pubsub.googleapis.com' async def fetch_id_token(request, audience): """Fetch the ID Token from the current environment. This function acquires ID token from the environment in the following order. See https://google.aip.dev/auth/4110. 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON file, then ID token is acquired using this service account credentials. 2. If the application is running in Compute Engine, App Engine or Cloud Run, then the ID token are obtained from the metadata server. 3. If metadata server doesn't exist and no valid service account credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. Example:: import google.oauth2._id_token_async import google.auth.transport.aiohttp_requests request = google.auth.transport.aiohttp_requests.Request() target_audience = "https://pubsub.googleapis.com" id_token = await google.oauth2._id_token_async.fetch_id_token(request, target_audience) Args: request (google.auth.transport.aiohttp_requests.Request): A callable used to make HTTP requests. audience (str): The audience that this ID token is intended for. Returns: str: The ID token. Raises: ~google.auth.exceptions.DefaultCredentialsError: If metadata server doesn't exist and no valid service account credentials are found. """ # 1. Try to get credentials from the GOOGLE_APPLICATION_CREDENTIALS environment # variable. credentials_filename = os.environ.get(environment_vars.CREDENTIALS) if credentials_filename: if not ( os.path.exists(credentials_filename) and os.path.isfile(credentials_filename) ): raise exceptions.DefaultCredentialsError( "GOOGLE_APPLICATION_CREDENTIALS path is either not found or invalid." ) try: with open(credentials_filename, "r") as f: from google.oauth2 import _service_account_async as service_account info = json.load(f) if info.get("type") == "service_account": credentials = service_account.IDTokenCredentials.from_service_account_info( info, target_audience=audience ) await credentials.refresh(request) return credentials.token except ValueError as caught_exc: new_exc = exceptions.DefaultCredentialsError( "GOOGLE_APPLICATION_CREDENTIALS is not valid service account credentials.", caught_exc, ) six.raise_from(new_exc, caught_exc) # 2. Try to fetch ID token from metada server if it exists. The code works # for GAE and Cloud Run metadata server as well. try: from google.auth import compute_engine from google.auth.compute_engine import _metadata request_new = requests.Request() if _metadata.ping(request_new): credentials = compute_engine.IDTokenCredentials( request_new, audience, use_metadata_identity_endpoint=True ) credentials.refresh(request_new) return credentials.token except (ImportError, exceptions.TransportError): pass > raise exceptions.DefaultCredentialsError( "Neither metadata server or valid service account credentials are found." ) E google.auth.exceptions.DefaultCredentialsError: Neither metadata server or valid service account credentials are found. google/oauth2/_id_token_async.py:285: DefaultCredentialsError ---------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------- WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 1 of 3. Reason: HTTPConnectionPool(host='169.254.169.254', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(, 'Connection to 169.254.169.254 timed out. (connect timeout=3)')) WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 2 of 3. Reason: HTTPConnectionPool(host='169.254.169.254', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(, 'Connection to 169.254.169.254 timed out. (connect timeout=3)')) WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 3 of 3. Reason: HTTPConnectionPool(host='169.254.169.254', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(, 'Connection to 169.254.169.254 timed out. (connect timeout=3)')) ______________________________________________________________ test_application_default_credentials[urllib3] _______________________________________________________________ verify_refresh = ._verify_refresh at 0x7f73f15a2ee0> def test_application_default_credentials(verify_refresh): > credentials, project_id = google.auth.default() system_tests/system_tests_sync/test_default.py:23: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ scopes = None, request = None, quota_project_id = None, default_scopes = None def default(scopes=None, request=None, quota_project_id=None, default_scopes=None): """Gets the default credentials for the current environment. `Application Default Credentials`_ provides an easy way to obtain credentials to call Google APIs for server-to-server or local applications. This function acquires credentials from the environment in the following order: 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON private key file, then it is loaded and returned. The project ID returned is the project ID defined in the service account file if available (some older files do not contain project ID information). If the environment variable is set to the path of a valid external account JSON configuration file (workload identity federation), then the configuration file is used to determine and retrieve the external credentials from the current environment (AWS, Azure, etc). These will then be exchanged for Google access tokens via the Google STS endpoint. The project ID returned in this case is the one corresponding to the underlying workload identity pool resource if determinable. If the environment variable is set to the path of a valid GDCH service account JSON file (`Google Distributed Cloud Hosted`_), then a GDCH credential will be returned. The project ID returned is the project specified in the JSON file. 2. If the `Google Cloud SDK`_ is installed and has application default credentials set they are loaded and returned. To enable application default credentials with the Cloud SDK run:: gcloud auth application-default login If the Cloud SDK has an active project, the project ID is returned. The active project can be set using:: gcloud config set project 3. If the application is running in the `App Engine standard environment`_ (first generation) then the credentials and project ID from the `App Identity Service`_ are used. 4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or the `App Engine flexible environment`_ or the `App Engine standard environment`_ (second generation) then the credentials and project ID are obtained from the `Metadata Service`_. 5. If no credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. .. _Application Default Credentials: https://developers.google.com\ /identity/protocols/application-default-credentials .. _Google Cloud SDK: https://cloud.google.com/sdk .. _App Engine standard environment: https://cloud.google.com/appengine .. _App Identity Service: https://cloud.google.com/appengine/docs/python\ /appidentity/ .. _Compute Engine: https://cloud.google.com/compute .. _App Engine flexible environment: https://cloud.google.com\ /appengine/flexible .. _Metadata Service: https://cloud.google.com/compute/docs\ /storing-retrieving-metadata .. _Cloud Run: https://cloud.google.com/run .. _Google Distributed Cloud Hosted: https://cloud.google.com/blog/topics\ /hybrid-cloud/announcing-google-distributed-cloud-edge-and-hosted Example:: import google.auth credentials, project_id = google.auth.default() Args: scopes (Sequence[str]): The list of scopes for the credentials. If specified, the credentials will automatically be scoped if necessary. request (Optional[google.auth.transport.Request]): An object used to make HTTP requests. This is used to either detect whether the application is running on Compute Engine or to determine the associated project ID for a workload identity pool resource (external account credentials). If not specified, then it will either use the standard library http client to make requests for Compute Engine credentials or a google.auth.transport.requests.Request client for external account credentials. quota_project_id (Optional[str]): The project ID used for quota and billing. default_scopes (Optional[Sequence[str]]): Default scopes passed by a Google client library. Use 'scopes' for user-defined scopes. Returns: Tuple[~google.auth.credentials.Credentials, Optional[str]]: the current environment's credentials and project ID. Project ID may be None, which indicates that the Project ID could not be ascertained from the environment. Raises: ~google.auth.exceptions.DefaultCredentialsError: If no credentials were found, or if the credentials found were invalid. """ from google.auth.credentials import with_scopes_if_required from google.auth.credentials import CredentialsWithQuotaProject explicit_project_id = os.environ.get( environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT) ) checkers = ( # Avoid passing scopes here to prevent passing scopes to user credentials. # with_scopes_if_required() below will ensure scopes/default scopes are # safely set on the returned credentials since requires_scopes will # guard against setting scopes on user credentials. lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id), lambda: _get_gcloud_sdk_credentials(quota_project_id=quota_project_id), _get_gae_credentials, lambda: _get_gce_credentials(request), ) for checker in checkers: credentials, project_id = checker() if credentials is not None: credentials = with_scopes_if_required( credentials, scopes, default_scopes=default_scopes ) # For external account credentials, scopes are required to determine # the project ID. Try to get the project ID again if not yet # determined. if not project_id and callable( getattr(credentials, "get_project_id", None) ): if request is None: import google.auth.transport.requests request = google.auth.transport.requests.Request() project_id = credentials.get_project_id(request=request) if quota_project_id and isinstance( credentials, CredentialsWithQuotaProject ): credentials = credentials.with_quota_project(quota_project_id) effective_project_id = explicit_project_id or project_id if not effective_project_id: _LOGGER.warning( "No project ID could be determined. Consider running " "`gcloud config set project` or setting the %s " "environment variable", environment_vars.PROJECT, ) return credentials, effective_project_id > raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) E google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started google/auth/_default.py:616: DefaultCredentialsError ---------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------- WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 1 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 2 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 3 of 3. Reason: [Errno 101] Network is unreachable WARNING google.auth._default:_default.py:290 Authentication failed using Compute Engine authentication due to unavailable metadata server. ______________________________________________________________ test_application_default_credentials[requests] ______________________________________________________________ verify_refresh = ._verify_refresh at 0x7f73f19e5af0> def test_application_default_credentials(verify_refresh): > credentials, project_id = google.auth.default() system_tests/system_tests_sync/test_default.py:23: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ scopes = None, request = None, quota_project_id = None, default_scopes = None def default(scopes=None, request=None, quota_project_id=None, default_scopes=None): """Gets the default credentials for the current environment. `Application Default Credentials`_ provides an easy way to obtain credentials to call Google APIs for server-to-server or local applications. This function acquires credentials from the environment in the following order: 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON private key file, then it is loaded and returned. The project ID returned is the project ID defined in the service account file if available (some older files do not contain project ID information). If the environment variable is set to the path of a valid external account JSON configuration file (workload identity federation), then the configuration file is used to determine and retrieve the external credentials from the current environment (AWS, Azure, etc). These will then be exchanged for Google access tokens via the Google STS endpoint. The project ID returned in this case is the one corresponding to the underlying workload identity pool resource if determinable. If the environment variable is set to the path of a valid GDCH service account JSON file (`Google Distributed Cloud Hosted`_), then a GDCH credential will be returned. The project ID returned is the project specified in the JSON file. 2. If the `Google Cloud SDK`_ is installed and has application default credentials set they are loaded and returned. To enable application default credentials with the Cloud SDK run:: gcloud auth application-default login If the Cloud SDK has an active project, the project ID is returned. The active project can be set using:: gcloud config set project 3. If the application is running in the `App Engine standard environment`_ (first generation) then the credentials and project ID from the `App Identity Service`_ are used. 4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or the `App Engine flexible environment`_ or the `App Engine standard environment`_ (second generation) then the credentials and project ID are obtained from the `Metadata Service`_. 5. If no credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. .. _Application Default Credentials: https://developers.google.com\ /identity/protocols/application-default-credentials .. _Google Cloud SDK: https://cloud.google.com/sdk .. _App Engine standard environment: https://cloud.google.com/appengine .. _App Identity Service: https://cloud.google.com/appengine/docs/python\ /appidentity/ .. _Compute Engine: https://cloud.google.com/compute .. _App Engine flexible environment: https://cloud.google.com\ /appengine/flexible .. _Metadata Service: https://cloud.google.com/compute/docs\ /storing-retrieving-metadata .. _Cloud Run: https://cloud.google.com/run .. _Google Distributed Cloud Hosted: https://cloud.google.com/blog/topics\ /hybrid-cloud/announcing-google-distributed-cloud-edge-and-hosted Example:: import google.auth credentials, project_id = google.auth.default() Args: scopes (Sequence[str]): The list of scopes for the credentials. If specified, the credentials will automatically be scoped if necessary. request (Optional[google.auth.transport.Request]): An object used to make HTTP requests. This is used to either detect whether the application is running on Compute Engine or to determine the associated project ID for a workload identity pool resource (external account credentials). If not specified, then it will either use the standard library http client to make requests for Compute Engine credentials or a google.auth.transport.requests.Request client for external account credentials. quota_project_id (Optional[str]): The project ID used for quota and billing. default_scopes (Optional[Sequence[str]]): Default scopes passed by a Google client library. Use 'scopes' for user-defined scopes. Returns: Tuple[~google.auth.credentials.Credentials, Optional[str]]: the current environment's credentials and project ID. Project ID may be None, which indicates that the Project ID could not be ascertained from the environment. Raises: ~google.auth.exceptions.DefaultCredentialsError: If no credentials were found, or if the credentials found were invalid. """ from google.auth.credentials import with_scopes_if_required from google.auth.credentials import CredentialsWithQuotaProject explicit_project_id = os.environ.get( environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT) ) checkers = ( # Avoid passing scopes here to prevent passing scopes to user credentials. # with_scopes_if_required() below will ensure scopes/default scopes are # safely set on the returned credentials since requires_scopes will # guard against setting scopes on user credentials. lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id), lambda: _get_gcloud_sdk_credentials(quota_project_id=quota_project_id), _get_gae_credentials, lambda: _get_gce_credentials(request), ) for checker in checkers: credentials, project_id = checker() if credentials is not None: credentials = with_scopes_if_required( credentials, scopes, default_scopes=default_scopes ) # For external account credentials, scopes are required to determine # the project ID. Try to get the project ID again if not yet # determined. if not project_id and callable( getattr(credentials, "get_project_id", None) ): if request is None: import google.auth.transport.requests request = google.auth.transport.requests.Request() project_id = credentials.get_project_id(request=request) if quota_project_id and isinstance( credentials, CredentialsWithQuotaProject ): credentials = credentials.with_quota_project(quota_project_id) effective_project_id = explicit_project_id or project_id if not effective_project_id: _LOGGER.warning( "No project ID could be determined. Consider running " "`gcloud config set project` or setting the %s " "environment variable", environment_vars.PROJECT, ) return credentials, effective_project_id > raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) E google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started google/auth/_default.py:616: DefaultCredentialsError ---------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------- WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 1 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 2 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 3 of 3. Reason: timed out WARNING google.auth._default:_default.py:290 Authentication failed using Compute Engine authentication due to unavailable metadata server. _______________________________________________________________________ test_fetch_id_token[urllib3] _______________________________________________________________________ http_request = def test_fetch_id_token(http_request): audience = "https://pubsub.googleapis.com" > token = google.oauth2.id_token.fetch_id_token(http_request, audience) system_tests/system_tests_sync/test_id_token.py:22: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ google/oauth2/id_token.py:339: in fetch_id_token id_token_credentials = fetch_id_token_credentials(audience, request=request) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ audience = 'https://pubsub.googleapis.com', request = def fetch_id_token_credentials(audience, request=None): """Create the ID Token credentials from the current environment. This function acquires ID token from the environment in the following order. See https://google.aip.dev/auth/4110. 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON file, then ID token is acquired using this service account credentials. 2. If the application is running in Compute Engine, App Engine or Cloud Run, then the ID token are obtained from the metadata server. 3. If metadata server doesn't exist and no valid service account credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. Example:: import google.oauth2.id_token import google.auth.transport.requests request = google.auth.transport.requests.Request() target_audience = "https://pubsub.googleapis.com" # Create ID token credentials. credentials = google.oauth2.id_token.fetch_id_token_credentials(target_audience, request=request) # Refresh the credential to obtain an ID token. credentials.refresh(request) id_token = credentials.token id_token_expiry = credentials.expiry Args: audience (str): The audience that this ID token is intended for. request (Optional[google.auth.transport.Request]): A callable used to make HTTP requests. A request object will be created if not provided. Returns: google.auth.credentials.Credentials: The ID token credentials. Raises: ~google.auth.exceptions.DefaultCredentialsError: If metadata server doesn't exist and no valid service account credentials are found. """ # 1. Try to get credentials from the GOOGLE_APPLICATION_CREDENTIALS environment # variable. credentials_filename = os.environ.get(environment_vars.CREDENTIALS) if credentials_filename: if not ( os.path.exists(credentials_filename) and os.path.isfile(credentials_filename) ): raise exceptions.DefaultCredentialsError( "GOOGLE_APPLICATION_CREDENTIALS path is either not found or invalid." ) try: with open(credentials_filename, "r") as f: from google.oauth2 import service_account info = json.load(f) if info.get("type") == "service_account": return service_account.IDTokenCredentials.from_service_account_info( info, target_audience=audience ) except ValueError as caught_exc: new_exc = exceptions.DefaultCredentialsError( "GOOGLE_APPLICATION_CREDENTIALS is not valid service account credentials.", caught_exc, ) six.raise_from(new_exc, caught_exc) # 2. Try to fetch ID token from metada server if it exists. The code # works for GAE and Cloud Run metadata server as well. try: from google.auth import compute_engine from google.auth.compute_engine import _metadata # Create a request object if not provided. if not request: request = google.auth.transport.requests.Request() if _metadata.ping(request): return compute_engine.IDTokenCredentials( request, audience, use_metadata_identity_endpoint=True ) except (ImportError, exceptions.TransportError): pass > raise exceptions.DefaultCredentialsError( "Neither metadata server or valid service account credentials are found." ) E google.auth.exceptions.DefaultCredentialsError: Neither metadata server or valid service account credentials are found. google/oauth2/id_token.py:296: DefaultCredentialsError ---------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------- WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 1 of 3. Reason: (, 'Connection to 169.254.169.254 timed out. (connect timeout=3)') WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 2 of 3. Reason: (, 'Connection to 169.254.169.254 timed out. (connect timeout=3)') WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 3 of 3. Reason: (, 'Connection to 169.254.169.254 timed out. (connect timeout=3)') ______________________________________________________________________ test_fetch_id_token[requests] _______________________________________________________________________ http_request = def test_fetch_id_token(http_request): audience = "https://pubsub.googleapis.com" > token = google.oauth2.id_token.fetch_id_token(http_request, audience) system_tests/system_tests_sync/test_id_token.py:22: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ google/oauth2/id_token.py:339: in fetch_id_token id_token_credentials = fetch_id_token_credentials(audience, request=request) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ audience = 'https://pubsub.googleapis.com', request = def fetch_id_token_credentials(audience, request=None): """Create the ID Token credentials from the current environment. This function acquires ID token from the environment in the following order. See https://google.aip.dev/auth/4110. 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON file, then ID token is acquired using this service account credentials. 2. If the application is running in Compute Engine, App Engine or Cloud Run, then the ID token are obtained from the metadata server. 3. If metadata server doesn't exist and no valid service account credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. Example:: import google.oauth2.id_token import google.auth.transport.requests request = google.auth.transport.requests.Request() target_audience = "https://pubsub.googleapis.com" # Create ID token credentials. credentials = google.oauth2.id_token.fetch_id_token_credentials(target_audience, request=request) # Refresh the credential to obtain an ID token. credentials.refresh(request) id_token = credentials.token id_token_expiry = credentials.expiry Args: audience (str): The audience that this ID token is intended for. request (Optional[google.auth.transport.Request]): A callable used to make HTTP requests. A request object will be created if not provided. Returns: google.auth.credentials.Credentials: The ID token credentials. Raises: ~google.auth.exceptions.DefaultCredentialsError: If metadata server doesn't exist and no valid service account credentials are found. """ # 1. Try to get credentials from the GOOGLE_APPLICATION_CREDENTIALS environment # variable. credentials_filename = os.environ.get(environment_vars.CREDENTIALS) if credentials_filename: if not ( os.path.exists(credentials_filename) and os.path.isfile(credentials_filename) ): raise exceptions.DefaultCredentialsError( "GOOGLE_APPLICATION_CREDENTIALS path is either not found or invalid." ) try: with open(credentials_filename, "r") as f: from google.oauth2 import service_account info = json.load(f) if info.get("type") == "service_account": return service_account.IDTokenCredentials.from_service_account_info( info, target_audience=audience ) except ValueError as caught_exc: new_exc = exceptions.DefaultCredentialsError( "GOOGLE_APPLICATION_CREDENTIALS is not valid service account credentials.", caught_exc, ) six.raise_from(new_exc, caught_exc) # 2. Try to fetch ID token from metada server if it exists. The code # works for GAE and Cloud Run metadata server as well. try: from google.auth import compute_engine from google.auth.compute_engine import _metadata # Create a request object if not provided. if not request: request = google.auth.transport.requests.Request() if _metadata.ping(request): return compute_engine.IDTokenCredentials( request, audience, use_metadata_identity_endpoint=True ) except (ImportError, exceptions.TransportError): pass > raise exceptions.DefaultCredentialsError( "Neither metadata server or valid service account credentials are found." ) E google.auth.exceptions.DefaultCredentialsError: Neither metadata server or valid service account credentials are found. google/oauth2/id_token.py:296: DefaultCredentialsError ---------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------- WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 1 of 3. Reason: HTTPConnectionPool(host='169.254.169.254', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(, 'Connection to 169.254.169.254 timed out. (connect timeout=3)')) WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 2 of 3. Reason: HTTPConnectionPool(host='169.254.169.254', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(, 'Connection to 169.254.169.254 timed out. (connect timeout=3)')) WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 3 of 3. Reason: HTTPConnectionPool(host='169.254.169.254', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(, 'Connection to 169.254.169.254 timed out. (connect timeout=3)')) ______________________________________________________________________________ test_requests _______________________________________________________________________________ def test_requests(): > credentials, project_id = google.auth.default() system_tests/system_tests_sync/test_mtls_http.py:34: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ scopes = None, request = None, quota_project_id = None, default_scopes = None def default(scopes=None, request=None, quota_project_id=None, default_scopes=None): """Gets the default credentials for the current environment. `Application Default Credentials`_ provides an easy way to obtain credentials to call Google APIs for server-to-server or local applications. This function acquires credentials from the environment in the following order: 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON private key file, then it is loaded and returned. The project ID returned is the project ID defined in the service account file if available (some older files do not contain project ID information). If the environment variable is set to the path of a valid external account JSON configuration file (workload identity federation), then the configuration file is used to determine and retrieve the external credentials from the current environment (AWS, Azure, etc). These will then be exchanged for Google access tokens via the Google STS endpoint. The project ID returned in this case is the one corresponding to the underlying workload identity pool resource if determinable. If the environment variable is set to the path of a valid GDCH service account JSON file (`Google Distributed Cloud Hosted`_), then a GDCH credential will be returned. The project ID returned is the project specified in the JSON file. 2. If the `Google Cloud SDK`_ is installed and has application default credentials set they are loaded and returned. To enable application default credentials with the Cloud SDK run:: gcloud auth application-default login If the Cloud SDK has an active project, the project ID is returned. The active project can be set using:: gcloud config set project 3. If the application is running in the `App Engine standard environment`_ (first generation) then the credentials and project ID from the `App Identity Service`_ are used. 4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or the `App Engine flexible environment`_ or the `App Engine standard environment`_ (second generation) then the credentials and project ID are obtained from the `Metadata Service`_. 5. If no credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. .. _Application Default Credentials: https://developers.google.com\ /identity/protocols/application-default-credentials .. _Google Cloud SDK: https://cloud.google.com/sdk .. _App Engine standard environment: https://cloud.google.com/appengine .. _App Identity Service: https://cloud.google.com/appengine/docs/python\ /appidentity/ .. _Compute Engine: https://cloud.google.com/compute .. _App Engine flexible environment: https://cloud.google.com\ /appengine/flexible .. _Metadata Service: https://cloud.google.com/compute/docs\ /storing-retrieving-metadata .. _Cloud Run: https://cloud.google.com/run .. _Google Distributed Cloud Hosted: https://cloud.google.com/blog/topics\ /hybrid-cloud/announcing-google-distributed-cloud-edge-and-hosted Example:: import google.auth credentials, project_id = google.auth.default() Args: scopes (Sequence[str]): The list of scopes for the credentials. If specified, the credentials will automatically be scoped if necessary. request (Optional[google.auth.transport.Request]): An object used to make HTTP requests. This is used to either detect whether the application is running on Compute Engine or to determine the associated project ID for a workload identity pool resource (external account credentials). If not specified, then it will either use the standard library http client to make requests for Compute Engine credentials or a google.auth.transport.requests.Request client for external account credentials. quota_project_id (Optional[str]): The project ID used for quota and billing. default_scopes (Optional[Sequence[str]]): Default scopes passed by a Google client library. Use 'scopes' for user-defined scopes. Returns: Tuple[~google.auth.credentials.Credentials, Optional[str]]: the current environment's credentials and project ID. Project ID may be None, which indicates that the Project ID could not be ascertained from the environment. Raises: ~google.auth.exceptions.DefaultCredentialsError: If no credentials were found, or if the credentials found were invalid. """ from google.auth.credentials import with_scopes_if_required from google.auth.credentials import CredentialsWithQuotaProject explicit_project_id = os.environ.get( environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT) ) checkers = ( # Avoid passing scopes here to prevent passing scopes to user credentials. # with_scopes_if_required() below will ensure scopes/default scopes are # safely set on the returned credentials since requires_scopes will # guard against setting scopes on user credentials. lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id), lambda: _get_gcloud_sdk_credentials(quota_project_id=quota_project_id), _get_gae_credentials, lambda: _get_gce_credentials(request), ) for checker in checkers: credentials, project_id = checker() if credentials is not None: credentials = with_scopes_if_required( credentials, scopes, default_scopes=default_scopes ) # For external account credentials, scopes are required to determine # the project ID. Try to get the project ID again if not yet # determined. if not project_id and callable( getattr(credentials, "get_project_id", None) ): if request is None: import google.auth.transport.requests request = google.auth.transport.requests.Request() project_id = credentials.get_project_id(request=request) if quota_project_id and isinstance( credentials, CredentialsWithQuotaProject ): credentials = credentials.with_quota_project(quota_project_id) effective_project_id = explicit_project_id or project_id if not effective_project_id: _LOGGER.warning( "No project ID could be determined. Consider running " "`gcloud config set project` or setting the %s " "environment variable", environment_vars.PROJECT, ) return credentials, effective_project_id > raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) E google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started google/auth/_default.py:616: DefaultCredentialsError ---------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------- WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 1 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 2 of 3. Reason: [Errno 101] Network is unreachable WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 3 of 3. Reason: timed out WARNING google.auth._default:_default.py:290 Authentication failed using Compute Engine authentication due to unavailable metadata server. _______________________________________________________________________________ test_urllib3 _______________________________________________________________________________ def test_urllib3(): > credentials, project_id = google.auth.default() system_tests/system_tests_sync/test_mtls_http.py:59: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ scopes = None, request = None, quota_project_id = None, default_scopes = None def default(scopes=None, request=None, quota_project_id=None, default_scopes=None): """Gets the default credentials for the current environment. `Application Default Credentials`_ provides an easy way to obtain credentials to call Google APIs for server-to-server or local applications. This function acquires credentials from the environment in the following order: 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON private key file, then it is loaded and returned. The project ID returned is the project ID defined in the service account file if available (some older files do not contain project ID information). If the environment variable is set to the path of a valid external account JSON configuration file (workload identity federation), then the configuration file is used to determine and retrieve the external credentials from the current environment (AWS, Azure, etc). These will then be exchanged for Google access tokens via the Google STS endpoint. The project ID returned in this case is the one corresponding to the underlying workload identity pool resource if determinable. If the environment variable is set to the path of a valid GDCH service account JSON file (`Google Distributed Cloud Hosted`_), then a GDCH credential will be returned. The project ID returned is the project specified in the JSON file. 2. If the `Google Cloud SDK`_ is installed and has application default credentials set they are loaded and returned. To enable application default credentials with the Cloud SDK run:: gcloud auth application-default login If the Cloud SDK has an active project, the project ID is returned. The active project can be set using:: gcloud config set project 3. If the application is running in the `App Engine standard environment`_ (first generation) then the credentials and project ID from the `App Identity Service`_ are used. 4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or the `App Engine flexible environment`_ or the `App Engine standard environment`_ (second generation) then the credentials and project ID are obtained from the `Metadata Service`_. 5. If no credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. .. _Application Default Credentials: https://developers.google.com\ /identity/protocols/application-default-credentials .. _Google Cloud SDK: https://cloud.google.com/sdk .. _App Engine standard environment: https://cloud.google.com/appengine .. _App Identity Service: https://cloud.google.com/appengine/docs/python\ /appidentity/ .. _Compute Engine: https://cloud.google.com/compute .. _App Engine flexible environment: https://cloud.google.com\ /appengine/flexible .. _Metadata Service: https://cloud.google.com/compute/docs\ /storing-retrieving-metadata .. _Cloud Run: https://cloud.google.com/run .. _Google Distributed Cloud Hosted: https://cloud.google.com/blog/topics\ /hybrid-cloud/announcing-google-distributed-cloud-edge-and-hosted Example:: import google.auth credentials, project_id = google.auth.default() Args: scopes (Sequence[str]): The list of scopes for the credentials. If specified, the credentials will automatically be scoped if necessary. request (Optional[google.auth.transport.Request]): An object used to make HTTP requests. This is used to either detect whether the application is running on Compute Engine or to determine the associated project ID for a workload identity pool resource (external account credentials). If not specified, then it will either use the standard library http client to make requests for Compute Engine credentials or a google.auth.transport.requests.Request client for external account credentials. quota_project_id (Optional[str]): The project ID used for quota and billing. default_scopes (Optional[Sequence[str]]): Default scopes passed by a Google client library. Use 'scopes' for user-defined scopes. Returns: Tuple[~google.auth.credentials.Credentials, Optional[str]]: the current environment's credentials and project ID. Project ID may be None, which indicates that the Project ID could not be ascertained from the environment. Raises: ~google.auth.exceptions.DefaultCredentialsError: If no credentials were found, or if the credentials found were invalid. """ from google.auth.credentials import with_scopes_if_required from google.auth.credentials import CredentialsWithQuotaProject explicit_project_id = os.environ.get( environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT) ) checkers = ( # Avoid passing scopes here to prevent passing scopes to user credentials. # with_scopes_if_required() below will ensure scopes/default scopes are # safely set on the returned credentials since requires_scopes will # guard against setting scopes on user credentials. lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id), lambda: _get_gcloud_sdk_credentials(quota_project_id=quota_project_id), _get_gae_credentials, lambda: _get_gce_credentials(request), ) for checker in checkers: credentials, project_id = checker() if credentials is not None: credentials = with_scopes_if_required( credentials, scopes, default_scopes=default_scopes ) # For external account credentials, scopes are required to determine # the project ID. Try to get the project ID again if not yet # determined. if not project_id and callable( getattr(credentials, "get_project_id", None) ): if request is None: import google.auth.transport.requests request = google.auth.transport.requests.Request() project_id = credentials.get_project_id(request=request) if quota_project_id and isinstance( credentials, CredentialsWithQuotaProject ): credentials = credentials.with_quota_project(quota_project_id) effective_project_id = explicit_project_id or project_id if not effective_project_id: _LOGGER.warning( "No project ID could be determined. Consider running " "`gcloud config set project` or setting the %s " "environment variable", environment_vars.PROJECT, ) return credentials, effective_project_id > raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) E google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started google/auth/_default.py:616: DefaultCredentialsError ---------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------- WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 1 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 2 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 3 of 3. Reason: timed out WARNING google.auth._default:_default.py:290 Authentication failed using Compute Engine authentication due to unavailable metadata server. ______________________________________________________________ test_requests_with_default_client_cert_source _______________________________________________________________ def test_requests_with_default_client_cert_source(): > credentials, project_id = google.auth.default() system_tests/system_tests_sync/test_mtls_http.py:84: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ scopes = None, request = None, quota_project_id = None, default_scopes = None def default(scopes=None, request=None, quota_project_id=None, default_scopes=None): """Gets the default credentials for the current environment. `Application Default Credentials`_ provides an easy way to obtain credentials to call Google APIs for server-to-server or local applications. This function acquires credentials from the environment in the following order: 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON private key file, then it is loaded and returned. The project ID returned is the project ID defined in the service account file if available (some older files do not contain project ID information). If the environment variable is set to the path of a valid external account JSON configuration file (workload identity federation), then the configuration file is used to determine and retrieve the external credentials from the current environment (AWS, Azure, etc). These will then be exchanged for Google access tokens via the Google STS endpoint. The project ID returned in this case is the one corresponding to the underlying workload identity pool resource if determinable. If the environment variable is set to the path of a valid GDCH service account JSON file (`Google Distributed Cloud Hosted`_), then a GDCH credential will be returned. The project ID returned is the project specified in the JSON file. 2. If the `Google Cloud SDK`_ is installed and has application default credentials set they are loaded and returned. To enable application default credentials with the Cloud SDK run:: gcloud auth application-default login If the Cloud SDK has an active project, the project ID is returned. The active project can be set using:: gcloud config set project 3. If the application is running in the `App Engine standard environment`_ (first generation) then the credentials and project ID from the `App Identity Service`_ are used. 4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or the `App Engine flexible environment`_ or the `App Engine standard environment`_ (second generation) then the credentials and project ID are obtained from the `Metadata Service`_. 5. If no credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. .. _Application Default Credentials: https://developers.google.com\ /identity/protocols/application-default-credentials .. _Google Cloud SDK: https://cloud.google.com/sdk .. _App Engine standard environment: https://cloud.google.com/appengine .. _App Identity Service: https://cloud.google.com/appengine/docs/python\ /appidentity/ .. _Compute Engine: https://cloud.google.com/compute .. _App Engine flexible environment: https://cloud.google.com\ /appengine/flexible .. _Metadata Service: https://cloud.google.com/compute/docs\ /storing-retrieving-metadata .. _Cloud Run: https://cloud.google.com/run .. _Google Distributed Cloud Hosted: https://cloud.google.com/blog/topics\ /hybrid-cloud/announcing-google-distributed-cloud-edge-and-hosted Example:: import google.auth credentials, project_id = google.auth.default() Args: scopes (Sequence[str]): The list of scopes for the credentials. If specified, the credentials will automatically be scoped if necessary. request (Optional[google.auth.transport.Request]): An object used to make HTTP requests. This is used to either detect whether the application is running on Compute Engine or to determine the associated project ID for a workload identity pool resource (external account credentials). If not specified, then it will either use the standard library http client to make requests for Compute Engine credentials or a google.auth.transport.requests.Request client for external account credentials. quota_project_id (Optional[str]): The project ID used for quota and billing. default_scopes (Optional[Sequence[str]]): Default scopes passed by a Google client library. Use 'scopes' for user-defined scopes. Returns: Tuple[~google.auth.credentials.Credentials, Optional[str]]: the current environment's credentials and project ID. Project ID may be None, which indicates that the Project ID could not be ascertained from the environment. Raises: ~google.auth.exceptions.DefaultCredentialsError: If no credentials were found, or if the credentials found were invalid. """ from google.auth.credentials import with_scopes_if_required from google.auth.credentials import CredentialsWithQuotaProject explicit_project_id = os.environ.get( environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT) ) checkers = ( # Avoid passing scopes here to prevent passing scopes to user credentials. # with_scopes_if_required() below will ensure scopes/default scopes are # safely set on the returned credentials since requires_scopes will # guard against setting scopes on user credentials. lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id), lambda: _get_gcloud_sdk_credentials(quota_project_id=quota_project_id), _get_gae_credentials, lambda: _get_gce_credentials(request), ) for checker in checkers: credentials, project_id = checker() if credentials is not None: credentials = with_scopes_if_required( credentials, scopes, default_scopes=default_scopes ) # For external account credentials, scopes are required to determine # the project ID. Try to get the project ID again if not yet # determined. if not project_id and callable( getattr(credentials, "get_project_id", None) ): if request is None: import google.auth.transport.requests request = google.auth.transport.requests.Request() project_id = credentials.get_project_id(request=request) if quota_project_id and isinstance( credentials, CredentialsWithQuotaProject ): credentials = credentials.with_quota_project(quota_project_id) effective_project_id = explicit_project_id or project_id if not effective_project_id: _LOGGER.warning( "No project ID could be determined. Consider running " "`gcloud config set project` or setting the %s " "environment variable", environment_vars.PROJECT, ) return credentials, effective_project_id > raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) E google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started google/auth/_default.py:616: DefaultCredentialsError ---------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------- WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 1 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 2 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 3 of 3. Reason: timed out WARNING google.auth._default:_default.py:290 Authentication failed using Compute Engine authentication due to unavailable metadata server. _______________________________________________________________ test_urllib3_with_default_client_cert_source _______________________________________________________________ def test_urllib3_with_default_client_cert_source(): > credentials, project_id = google.auth.default() system_tests/system_tests_sync/test_mtls_http.py:107: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ scopes = None, request = None, quota_project_id = None, default_scopes = None def default(scopes=None, request=None, quota_project_id=None, default_scopes=None): """Gets the default credentials for the current environment. `Application Default Credentials`_ provides an easy way to obtain credentials to call Google APIs for server-to-server or local applications. This function acquires credentials from the environment in the following order: 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON private key file, then it is loaded and returned. The project ID returned is the project ID defined in the service account file if available (some older files do not contain project ID information). If the environment variable is set to the path of a valid external account JSON configuration file (workload identity federation), then the configuration file is used to determine and retrieve the external credentials from the current environment (AWS, Azure, etc). These will then be exchanged for Google access tokens via the Google STS endpoint. The project ID returned in this case is the one corresponding to the underlying workload identity pool resource if determinable. If the environment variable is set to the path of a valid GDCH service account JSON file (`Google Distributed Cloud Hosted`_), then a GDCH credential will be returned. The project ID returned is the project specified in the JSON file. 2. If the `Google Cloud SDK`_ is installed and has application default credentials set they are loaded and returned. To enable application default credentials with the Cloud SDK run:: gcloud auth application-default login If the Cloud SDK has an active project, the project ID is returned. The active project can be set using:: gcloud config set project 3. If the application is running in the `App Engine standard environment`_ (first generation) then the credentials and project ID from the `App Identity Service`_ are used. 4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or the `App Engine flexible environment`_ or the `App Engine standard environment`_ (second generation) then the credentials and project ID are obtained from the `Metadata Service`_. 5. If no credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. .. _Application Default Credentials: https://developers.google.com\ /identity/protocols/application-default-credentials .. _Google Cloud SDK: https://cloud.google.com/sdk .. _App Engine standard environment: https://cloud.google.com/appengine .. _App Identity Service: https://cloud.google.com/appengine/docs/python\ /appidentity/ .. _Compute Engine: https://cloud.google.com/compute .. _App Engine flexible environment: https://cloud.google.com\ /appengine/flexible .. _Metadata Service: https://cloud.google.com/compute/docs\ /storing-retrieving-metadata .. _Cloud Run: https://cloud.google.com/run .. _Google Distributed Cloud Hosted: https://cloud.google.com/blog/topics\ /hybrid-cloud/announcing-google-distributed-cloud-edge-and-hosted Example:: import google.auth credentials, project_id = google.auth.default() Args: scopes (Sequence[str]): The list of scopes for the credentials. If specified, the credentials will automatically be scoped if necessary. request (Optional[google.auth.transport.Request]): An object used to make HTTP requests. This is used to either detect whether the application is running on Compute Engine or to determine the associated project ID for a workload identity pool resource (external account credentials). If not specified, then it will either use the standard library http client to make requests for Compute Engine credentials or a google.auth.transport.requests.Request client for external account credentials. quota_project_id (Optional[str]): The project ID used for quota and billing. default_scopes (Optional[Sequence[str]]): Default scopes passed by a Google client library. Use 'scopes' for user-defined scopes. Returns: Tuple[~google.auth.credentials.Credentials, Optional[str]]: the current environment's credentials and project ID. Project ID may be None, which indicates that the Project ID could not be ascertained from the environment. Raises: ~google.auth.exceptions.DefaultCredentialsError: If no credentials were found, or if the credentials found were invalid. """ from google.auth.credentials import with_scopes_if_required from google.auth.credentials import CredentialsWithQuotaProject explicit_project_id = os.environ.get( environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT) ) checkers = ( # Avoid passing scopes here to prevent passing scopes to user credentials. # with_scopes_if_required() below will ensure scopes/default scopes are # safely set on the returned credentials since requires_scopes will # guard against setting scopes on user credentials. lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id), lambda: _get_gcloud_sdk_credentials(quota_project_id=quota_project_id), _get_gae_credentials, lambda: _get_gce_credentials(request), ) for checker in checkers: credentials, project_id = checker() if credentials is not None: credentials = with_scopes_if_required( credentials, scopes, default_scopes=default_scopes ) # For external account credentials, scopes are required to determine # the project ID. Try to get the project ID again if not yet # determined. if not project_id and callable( getattr(credentials, "get_project_id", None) ): if request is None: import google.auth.transport.requests request = google.auth.transport.requests.Request() project_id = credentials.get_project_id(request=request) if quota_project_id and isinstance( credentials, CredentialsWithQuotaProject ): credentials = credentials.with_quota_project(quota_project_id) effective_project_id = explicit_project_id or project_id if not effective_project_id: _LOGGER.warning( "No project ID could be determined. Consider running " "`gcloud config set project` or setting the %s " "environment variable", environment_vars.PROJECT, ) return credentials, effective_project_id > raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) E google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started google/auth/_default.py:616: DefaultCredentialsError ---------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------- WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 1 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 2 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 3 of 3. Reason: timed out WARNING google.auth._default:_default.py:290 Authentication failed using Compute Engine authentication due to unavailable metadata server. _____________________________________________________ test_authorized_session_with_service_account_and_self_signed_jwt _____________________________________________________ def test_authorized_session_with_service_account_and_self_signed_jwt(): > credentials, project_id = google.auth.default() system_tests/system_tests_sync/test_requests.py:22: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ scopes = None, request = None, quota_project_id = None, default_scopes = None def default(scopes=None, request=None, quota_project_id=None, default_scopes=None): """Gets the default credentials for the current environment. `Application Default Credentials`_ provides an easy way to obtain credentials to call Google APIs for server-to-server or local applications. This function acquires credentials from the environment in the following order: 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON private key file, then it is loaded and returned. The project ID returned is the project ID defined in the service account file if available (some older files do not contain project ID information). If the environment variable is set to the path of a valid external account JSON configuration file (workload identity federation), then the configuration file is used to determine and retrieve the external credentials from the current environment (AWS, Azure, etc). These will then be exchanged for Google access tokens via the Google STS endpoint. The project ID returned in this case is the one corresponding to the underlying workload identity pool resource if determinable. If the environment variable is set to the path of a valid GDCH service account JSON file (`Google Distributed Cloud Hosted`_), then a GDCH credential will be returned. The project ID returned is the project specified in the JSON file. 2. If the `Google Cloud SDK`_ is installed and has application default credentials set they are loaded and returned. To enable application default credentials with the Cloud SDK run:: gcloud auth application-default login If the Cloud SDK has an active project, the project ID is returned. The active project can be set using:: gcloud config set project 3. If the application is running in the `App Engine standard environment`_ (first generation) then the credentials and project ID from the `App Identity Service`_ are used. 4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or the `App Engine flexible environment`_ or the `App Engine standard environment`_ (second generation) then the credentials and project ID are obtained from the `Metadata Service`_. 5. If no credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. .. _Application Default Credentials: https://developers.google.com\ /identity/protocols/application-default-credentials .. _Google Cloud SDK: https://cloud.google.com/sdk .. _App Engine standard environment: https://cloud.google.com/appengine .. _App Identity Service: https://cloud.google.com/appengine/docs/python\ /appidentity/ .. _Compute Engine: https://cloud.google.com/compute .. _App Engine flexible environment: https://cloud.google.com\ /appengine/flexible .. _Metadata Service: https://cloud.google.com/compute/docs\ /storing-retrieving-metadata .. _Cloud Run: https://cloud.google.com/run .. _Google Distributed Cloud Hosted: https://cloud.google.com/blog/topics\ /hybrid-cloud/announcing-google-distributed-cloud-edge-and-hosted Example:: import google.auth credentials, project_id = google.auth.default() Args: scopes (Sequence[str]): The list of scopes for the credentials. If specified, the credentials will automatically be scoped if necessary. request (Optional[google.auth.transport.Request]): An object used to make HTTP requests. This is used to either detect whether the application is running on Compute Engine or to determine the associated project ID for a workload identity pool resource (external account credentials). If not specified, then it will either use the standard library http client to make requests for Compute Engine credentials or a google.auth.transport.requests.Request client for external account credentials. quota_project_id (Optional[str]): The project ID used for quota and billing. default_scopes (Optional[Sequence[str]]): Default scopes passed by a Google client library. Use 'scopes' for user-defined scopes. Returns: Tuple[~google.auth.credentials.Credentials, Optional[str]]: the current environment's credentials and project ID. Project ID may be None, which indicates that the Project ID could not be ascertained from the environment. Raises: ~google.auth.exceptions.DefaultCredentialsError: If no credentials were found, or if the credentials found were invalid. """ from google.auth.credentials import with_scopes_if_required from google.auth.credentials import CredentialsWithQuotaProject explicit_project_id = os.environ.get( environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT) ) checkers = ( # Avoid passing scopes here to prevent passing scopes to user credentials. # with_scopes_if_required() below will ensure scopes/default scopes are # safely set on the returned credentials since requires_scopes will # guard against setting scopes on user credentials. lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id), lambda: _get_gcloud_sdk_credentials(quota_project_id=quota_project_id), _get_gae_credentials, lambda: _get_gce_credentials(request), ) for checker in checkers: credentials, project_id = checker() if credentials is not None: credentials = with_scopes_if_required( credentials, scopes, default_scopes=default_scopes ) # For external account credentials, scopes are required to determine # the project ID. Try to get the project ID again if not yet # determined. if not project_id and callable( getattr(credentials, "get_project_id", None) ): if request is None: import google.auth.transport.requests request = google.auth.transport.requests.Request() project_id = credentials.get_project_id(request=request) if quota_project_id and isinstance( credentials, CredentialsWithQuotaProject ): credentials = credentials.with_quota_project(quota_project_id) effective_project_id = explicit_project_id or project_id if not effective_project_id: _LOGGER.warning( "No project ID could be determined. Consider running " "`gcloud config set project` or setting the %s " "environment variable", environment_vars.PROJECT, ) return credentials, effective_project_id > raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) E google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started google/auth/_default.py:616: DefaultCredentialsError ---------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------- WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 1 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 2 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 3 of 3. Reason: timed out WARNING google.auth._default:_default.py:290 Authentication failed using Compute Engine authentication due to unavailable metadata server. _____________________________________________________ test_authorized_session_with_service_account_and_self_signed_jwt _____________________________________________________ def test_authorized_session_with_service_account_and_self_signed_jwt(): > credentials, project_id = google.auth.default() system_tests/system_tests_sync/test_urllib3.py:22: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ scopes = None, request = None, quota_project_id = None, default_scopes = None def default(scopes=None, request=None, quota_project_id=None, default_scopes=None): """Gets the default credentials for the current environment. `Application Default Credentials`_ provides an easy way to obtain credentials to call Google APIs for server-to-server or local applications. This function acquires credentials from the environment in the following order: 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set to the path of a valid service account JSON private key file, then it is loaded and returned. The project ID returned is the project ID defined in the service account file if available (some older files do not contain project ID information). If the environment variable is set to the path of a valid external account JSON configuration file (workload identity federation), then the configuration file is used to determine and retrieve the external credentials from the current environment (AWS, Azure, etc). These will then be exchanged for Google access tokens via the Google STS endpoint. The project ID returned in this case is the one corresponding to the underlying workload identity pool resource if determinable. If the environment variable is set to the path of a valid GDCH service account JSON file (`Google Distributed Cloud Hosted`_), then a GDCH credential will be returned. The project ID returned is the project specified in the JSON file. 2. If the `Google Cloud SDK`_ is installed and has application default credentials set they are loaded and returned. To enable application default credentials with the Cloud SDK run:: gcloud auth application-default login If the Cloud SDK has an active project, the project ID is returned. The active project can be set using:: gcloud config set project 3. If the application is running in the `App Engine standard environment`_ (first generation) then the credentials and project ID from the `App Identity Service`_ are used. 4. If the application is running in `Compute Engine`_ or `Cloud Run`_ or the `App Engine flexible environment`_ or the `App Engine standard environment`_ (second generation) then the credentials and project ID are obtained from the `Metadata Service`_. 5. If no credentials are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised. .. _Application Default Credentials: https://developers.google.com\ /identity/protocols/application-default-credentials .. _Google Cloud SDK: https://cloud.google.com/sdk .. _App Engine standard environment: https://cloud.google.com/appengine .. _App Identity Service: https://cloud.google.com/appengine/docs/python\ /appidentity/ .. _Compute Engine: https://cloud.google.com/compute .. _App Engine flexible environment: https://cloud.google.com\ /appengine/flexible .. _Metadata Service: https://cloud.google.com/compute/docs\ /storing-retrieving-metadata .. _Cloud Run: https://cloud.google.com/run .. _Google Distributed Cloud Hosted: https://cloud.google.com/blog/topics\ /hybrid-cloud/announcing-google-distributed-cloud-edge-and-hosted Example:: import google.auth credentials, project_id = google.auth.default() Args: scopes (Sequence[str]): The list of scopes for the credentials. If specified, the credentials will automatically be scoped if necessary. request (Optional[google.auth.transport.Request]): An object used to make HTTP requests. This is used to either detect whether the application is running on Compute Engine or to determine the associated project ID for a workload identity pool resource (external account credentials). If not specified, then it will either use the standard library http client to make requests for Compute Engine credentials or a google.auth.transport.requests.Request client for external account credentials. quota_project_id (Optional[str]): The project ID used for quota and billing. default_scopes (Optional[Sequence[str]]): Default scopes passed by a Google client library. Use 'scopes' for user-defined scopes. Returns: Tuple[~google.auth.credentials.Credentials, Optional[str]]: the current environment's credentials and project ID. Project ID may be None, which indicates that the Project ID could not be ascertained from the environment. Raises: ~google.auth.exceptions.DefaultCredentialsError: If no credentials were found, or if the credentials found were invalid. """ from google.auth.credentials import with_scopes_if_required from google.auth.credentials import CredentialsWithQuotaProject explicit_project_id = os.environ.get( environment_vars.PROJECT, os.environ.get(environment_vars.LEGACY_PROJECT) ) checkers = ( # Avoid passing scopes here to prevent passing scopes to user credentials. # with_scopes_if_required() below will ensure scopes/default scopes are # safely set on the returned credentials since requires_scopes will # guard against setting scopes on user credentials. lambda: _get_explicit_environ_credentials(quota_project_id=quota_project_id), lambda: _get_gcloud_sdk_credentials(quota_project_id=quota_project_id), _get_gae_credentials, lambda: _get_gce_credentials(request), ) for checker in checkers: credentials, project_id = checker() if credentials is not None: credentials = with_scopes_if_required( credentials, scopes, default_scopes=default_scopes ) # For external account credentials, scopes are required to determine # the project ID. Try to get the project ID again if not yet # determined. if not project_id and callable( getattr(credentials, "get_project_id", None) ): if request is None: import google.auth.transport.requests request = google.auth.transport.requests.Request() project_id = credentials.get_project_id(request=request) if quota_project_id and isinstance( credentials, CredentialsWithQuotaProject ): credentials = credentials.with_quota_project(quota_project_id) effective_project_id = explicit_project_id or project_id if not effective_project_id: _LOGGER.warning( "No project ID could be determined. Consider running " "`gcloud config set project` or setting the %s " "environment variable", environment_vars.PROJECT, ) return credentials, effective_project_id > raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) E google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started google/auth/_default.py:616: DefaultCredentialsError ---------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------- WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 1 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 2 of 3. Reason: timed out WARNING google.auth.compute_engine._metadata:_metadata.py:99 Compute Engine Metadata server unavailable on attempt 3 of 3. Reason: timed out WARNING google.auth._default:_default.py:290 Authentication failed using Compute Engine authentication due to unavailable metadata server. ____________________________________________________________________ test__run_subprocess_ignore_stderr ____________________________________________________________________ def test__run_subprocess_ignore_stderr(): command = [ "python", "-c", "from __future__ import print_function;" + "import sys;" + "print('error', file=sys.stderr);" + "print('output', file=sys.stdout)", ] # If we ignore stderr, then the output only has stdout > output = _cloud_sdk._run_subprocess_ignore_stderr(command) tests/test__cloud_sdk.py:85: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ google/auth/_cloud_sdk.py:90: in _run_subprocess_ignore_stderr output = subprocess.check_output(command, stderr=devnull) /usr/lib64/python3.8/subprocess.py:415: in check_output return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, /usr/lib64/python3.8/subprocess.py:493: in run with Popen(*popenargs, **kwargs) as process: /usr/lib64/python3.8/subprocess.py:858: in __init__ self._execute_child(args, executable, preexec_fn, close_fds, _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = args = ['python', '-c', "from __future__ import print_function;import sys;print('error', file=sys.stderr);print('output', file=sys.stdout)"], executable = b'python' preexec_fn = None, close_fds = True, pass_fds = (), cwd = None, env = None, startupinfo = None, creationflags = 0, shell = False, p2cread = -1, p2cwrite = -1, c2pread = 17 c2pwrite = 18, errread = -1, errwrite = 16, restore_signals = True, start_new_session = False def _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session): """Execute program (POSIX version)""" if isinstance(args, (str, bytes)): args = [args] elif isinstance(args, os.PathLike): if shell: raise TypeError('path-like args is not allowed when ' 'shell is true') args = [args] else: args = list(args) if shell: # On Android the default shell is at '/system/bin/sh'. unix_shell = ('/system/bin/sh' if hasattr(sys, 'getandroidapilevel') else '/bin/sh') args = [unix_shell, "-c"] + args if executable: args[0] = executable if executable is None: executable = args[0] sys.audit("subprocess.Popen", executable, args, cwd, env) if (_USE_POSIX_SPAWN and os.path.dirname(executable) and preexec_fn is None and not close_fds and not pass_fds and cwd is None and (p2cread == -1 or p2cread > 2) and (c2pwrite == -1 or c2pwrite > 2) and (errwrite == -1 or errwrite > 2) and not start_new_session): self._posix_spawn(args, executable, env, restore_signals, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) return orig_executable = executable # For transferring possible exec failure from child to parent. # Data format: "exception name:hex errno:description" # Pickle is not used; it is complex and involves memory allocation. errpipe_read, errpipe_write = os.pipe() # errpipe_write must not be in the standard io 0, 1, or 2 fd range. low_fds_to_close = [] while errpipe_write < 3: low_fds_to_close.append(errpipe_write) errpipe_write = os.dup(errpipe_write) for low_fd in low_fds_to_close: os.close(low_fd) try: try: # We must avoid complex work that could involve # malloc or free in the child process to avoid # potential deadlocks, thus we do all this here. # and pass it to fork_exec() if env is not None: env_list = [] for k, v in env.items(): k = os.fsencode(k) if b'=' in k: raise ValueError("illegal environment variable name") env_list.append(k + b'=' + os.fsencode(v)) else: env_list = None # Use execv instead of execve. executable = os.fsencode(executable) if os.path.dirname(executable): executable_list = (executable,) else: # This matches the behavior of os._execvpe(). executable_list = tuple( os.path.join(os.fsencode(dir), executable) for dir in os.get_exec_path(env)) fds_to_keep = set(pass_fds) fds_to_keep.add(errpipe_write) self.pid = _posixsubprocess.fork_exec( args, executable_list, close_fds, tuple(sorted(map(int, fds_to_keep))), cwd, env_list, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, errpipe_read, errpipe_write, restore_signals, start_new_session, preexec_fn) self._child_created = True finally: # be sure the FD is closed no matter what os.close(errpipe_write) self._close_pipe_fds(p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) # Wait for exec to fail or succeed; possibly raising an # exception (limited in size) errpipe_data = bytearray() while True: part = os.read(errpipe_read, 50000) errpipe_data += part if not part or len(errpipe_data) > 50000: break finally: # be sure the FD is closed no matter what os.close(errpipe_read) if errpipe_data: try: pid, sts = os.waitpid(self.pid, 0) if pid == self.pid: self._handle_exitstatus(sts) else: self.returncode = sys.maxsize except ChildProcessError: pass try: exception_name, hex_errno, err_msg = ( errpipe_data.split(b':', 2)) # The encoding here should match the encoding # written in by the subprocess implementations # like _posixsubprocess err_msg = err_msg.decode() except ValueError: exception_name = b'SubprocessError' hex_errno = b'0' err_msg = 'Bad exception data from child: {!r}'.format( bytes(errpipe_data)) child_exception_type = getattr( builtins, exception_name.decode('ascii'), SubprocessError) if issubclass(child_exception_type, OSError) and hex_errno: errno_num = int(hex_errno, 16) child_exec_never_called = (err_msg == "noexec") if child_exec_never_called: err_msg = "" # The error must be from chdir(cwd). err_filename = cwd else: err_filename = orig_executable if errno_num != 0: err_msg = os.strerror(errno_num) > raise child_exception_type(errno_num, err_msg, err_filename) E FileNotFoundError: [Errno 2] No such file or directory: 'python' /usr/lib64/python3.8/subprocess.py:1704: FileNotFoundError ============================================================================= warnings summary ============================================================================= google/auth/transport/_aiohttp_requests.py:201 /home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/google/auth/transport/_aiohttp_requests.py:201: DeprecationWarning: Inheritance class AuthorizedSession from ClientSession is discouraged class AuthorizedSession(aiohttp.ClientSession): tests/transport/test__custom_tls_signer.py:22 /home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/tests/transport/test__custom_tls_signer.py:22: DeprecationWarning: 'urllib3.contrib.pyopenssl' module is deprecated and will be removed in a future release of urllib3 2.x. Read more in this issue: https://github.com/urllib3/urllib3/issues/2680 import urllib3.contrib.pyopenssl # type: ignore tests/transport/test_urllib3.py::TestAuthorizedHttp::test_urlopen_no_refresh tests/transport/test_urllib3.py::TestAuthorizedHttp::test_urlopen_refresh /usr/lib/python3.8/site-packages/_pytest/unraisableexception.py:78: PytestUnraisableExceptionWarning: Exception ignored in: Traceback (most recent call last): File "/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/google/auth/transport/urllib3.py", line 432, in __del__ self.http.clear() AttributeError: 'HttpStub' object has no attribute 'clear' warnings.warn(pytest.PytestUnraisableExceptionWarning(msg)) tests_async/test_credentials_async.py::test_before_request /home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/tests_async/test_credentials_async.py:81: RuntimeWarning: coroutine 'Credentials.before_request' was never awaited credentials.before_request(request, "http://example.com", "GET", headers) Enable tracemalloc to get traceback where the object was allocated. See https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings for more info. tests_async/transport/test_aiohttp_requests.py::TestRequestResponse::test_unsupported_session /home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/tests_async/transport/test_aiohttp_requests.py:119: DeprecationWarning: The object should be created within an async function http = aiohttp.ClientSession(auto_decompress=True) tests_async/transport/test_aiohttp_requests.py::TestRequestResponse::test_unsupported_session tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_constructor tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_constructor_with_auth_request /usr/lib64/python3.8/site-packages/aiohttp/connector.py:771: DeprecationWarning: The object should be created within an async function super().__init__( tests_async/transport/test_aiohttp_requests.py::TestRequestResponse::test_unsupported_session tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_constructor tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_constructor_with_auth_request /usr/lib64/python3.8/site-packages/aiohttp/connector.py:782: DeprecationWarning: The object should be created within an async function resolver = DefaultResolver(loop=self._loop) tests_async/transport/test_aiohttp_requests.py::TestRequestResponse::test_unsupported_session tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_constructor tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_constructor_with_auth_request /usr/lib64/python3.8/site-packages/aiohttp/cookiejar.py:67: DeprecationWarning: The object should be created within an async function super().__init__(loop=loop) tests_async/transport/test_aiohttp_requests.py::TestRequestResponse::test_timeout /home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/tests_async/transport/test_aiohttp_requests.py:128: RuntimeWarning: coroutine 'Request.__call__' was never awaited request(url="http://example.com", method="GET", timeout=5) Enable tracemalloc to get traceback where the object was allocated. See https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings for more info. tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_constructor tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_constructor_with_auth_request /home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/google/auth/transport/_aiohttp_requests.py:247: DeprecationWarning: The object should be created within an async function super(AuthorizedSession, self).__init__() -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html ========================================================================= short test summary info ========================================================================== SKIPPED [8] system_tests/system_tests_sync/test_compute_engine.py:35: Compute Engine metadata service is not available. SKIPPED [1] tests/transport/test_grpc.py:62: gRPC is unavailable. SKIPPED [1] tests/transport/test_grpc.py:81: gRPC is unavailable. SKIPPED [1] tests/transport/test_grpc.py:102: gRPC is unavailable. SKIPPED [1] tests/transport/test_grpc.py:116: gRPC is unavailable. SKIPPED [1] tests/transport/test_grpc.py:144: gRPC is unavailable. SKIPPED [1] tests/transport/test_grpc.py:209: gRPC is unavailable. SKIPPED [1] tests/transport/test_grpc.py:252: gRPC is unavailable. SKIPPED [1] tests/transport/test_grpc.py:281: gRPC is unavailable. SKIPPED [1] tests/transport/test_grpc.py:304: gRPC is unavailable. SKIPPED [1] tests/transport/test_grpc.py:337: gRPC is unavailable. SKIPPED [1] tests/transport/test_grpc.py:373: gRPC is unavailable. SKIPPED [1] tests/transport/test_grpc.py:413: gRPC is unavailable. SKIPPED [1] tests/transport/test_grpc.py:436: gRPC is unavailable. SKIPPED [1] tests/transport/test_grpc.py:457: gRPC is unavailable. SKIPPED [1] tests/transport/test_grpc.py:487: gRPC is unavailable. ERROR system_tests/system_tests_async/test_service_account.py::test_refresh_no_scopes[aiohttp] - FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/... ERROR system_tests/system_tests_async/test_service_account.py::test_refresh_success[aiohttp] - FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/rp... ERROR system_tests/system_tests_sync/test_impersonated_credentials.py::test_refresh_with_user_credentials_as_source[urllib3] - NameError: name 'AUTHORIZED_USER_FILE' is ... ERROR system_tests/system_tests_sync/test_impersonated_credentials.py::test_refresh_with_user_credentials_as_source[requests] - NameError: name 'AUTHORIZED_USER_FILE' is... ERROR system_tests/system_tests_sync/test_impersonated_credentials.py::test_refresh_with_service_account_credentials_as_source[urllib3] - FileNotFoundError: [Errno 2] No... ERROR system_tests/system_tests_sync/test_impersonated_credentials.py::test_refresh_with_service_account_credentials_as_source[requests] - FileNotFoundError: [Errno 2] N... ERROR system_tests/system_tests_sync/test_oauth2_credentials.py::test_refresh[urllib3] - NameError: name 'AUTHORIZED_USER_FILE' is not defined ERROR system_tests/system_tests_sync/test_oauth2_credentials.py::test_refresh[requests] - NameError: name 'AUTHORIZED_USER_FILE' is not defined ERROR system_tests/system_tests_sync/test_service_account.py::test_refresh_no_scopes[urllib3] - FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/r... ERROR system_tests/system_tests_sync/test_service_account.py::test_refresh_no_scopes[requests] - FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/... ERROR system_tests/system_tests_sync/test_service_account.py::test_refresh_success[urllib3] - FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/rpm... ERROR system_tests/system_tests_sync/test_service_account.py::test_refresh_success[requests] - FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/rp... ERROR system_tests/system_tests_sync/test_service_account.py::test_iam_signer[urllib3] - FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/rpmbuild... ERROR system_tests/system_tests_sync/test_service_account.py::test_iam_signer[requests] - FileNotFoundError: [Errno 2] No such file or directory: '/home/tkloczko/rpmbuil... FAILED system_tests/system_tests_async/test_default.py::test_application_default_credentials[aiohttp] - google.auth.exceptions.DefaultCredentialsError: Could not automat... FAILED system_tests/system_tests_async/test_id_token.py::test_fetch_id_token[aiohttp] - google.auth.exceptions.DefaultCredentialsError: Neither metadata server or valid ... FAILED system_tests/system_tests_sync/test_default.py::test_application_default_credentials[urllib3] - google.auth.exceptions.DefaultCredentialsError: Could not automati... FAILED system_tests/system_tests_sync/test_default.py::test_application_default_credentials[requests] - google.auth.exceptions.DefaultCredentialsError: Could not automat... FAILED system_tests/system_tests_sync/test_id_token.py::test_fetch_id_token[urllib3] - google.auth.exceptions.DefaultCredentialsError: Neither metadata server or valid s... FAILED system_tests/system_tests_sync/test_id_token.py::test_fetch_id_token[requests] - google.auth.exceptions.DefaultCredentialsError: Neither metadata server or valid ... FAILED system_tests/system_tests_sync/test_mtls_http.py::test_requests - google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. P... FAILED system_tests/system_tests_sync/test_mtls_http.py::test_urllib3 - google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Pl... FAILED system_tests/system_tests_sync/test_mtls_http.py::test_requests_with_default_client_cert_source - google.auth.exceptions.DefaultCredentialsError: Could not automa... FAILED system_tests/system_tests_sync/test_mtls_http.py::test_urllib3_with_default_client_cert_source - google.auth.exceptions.DefaultCredentialsError: Could not automat... FAILED system_tests/system_tests_sync/test_requests.py::test_authorized_session_with_service_account_and_self_signed_jwt - google.auth.exceptions.DefaultCredentialsError... FAILED system_tests/system_tests_sync/test_urllib3.py::test_authorized_session_with_service_account_and_self_signed_jwt - google.auth.exceptions.DefaultCredentialsError:... FAILED tests/test__cloud_sdk.py::test__run_subprocess_ignore_stderr - FileNotFoundError: [Errno 2] No such file or directory: 'python' ============================================= 13 failed, 1038 passed, 23 skipped, 18 warnings, 14 errors in 138.71s (0:02:18) ============================================== ```
kloczek commented 2 years ago

In case of

FAILED tests/test__cloud_sdk.py::test__run_subprocess_ignore_stderr - FileNotFoundError: [Errno 2] No such file or directory: 'python'

Looks like python interpreter executable is hardcoded. Instead shoud be used sys.executable

kloczek commented 2 years ago

After add (for now) all failing units to --deselect list pytest shows warnings

============================================================================= warnings summary =============================================================================
google/auth/transport/_aiohttp_requests.py:201
  /home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/google/auth/transport/_aiohttp_requests.py:201: DeprecationWarning: Inheritance class AuthorizedSession from ClientSession is discouraged
    class AuthorizedSession(aiohttp.ClientSession):

tests/transport/test__custom_tls_signer.py:22
  /home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/tests/transport/test__custom_tls_signer.py:22: DeprecationWarning: 'urllib3.contrib.pyopenssl' module is deprecated and will be removed in a future release of urllib3 2.x. Read more in this issue: https://github.com/urllib3/urllib3/issues/2680
    import urllib3.contrib.pyopenssl  # type: ignore

tests/transport/test_urllib3.py::TestAuthorizedHttp::test_urlopen_no_refresh
tests/transport/test_urllib3.py::TestAuthorizedHttp::test_urlopen_refresh
  /usr/lib/python3.8/site-packages/_pytest/unraisableexception.py:78: PytestUnraisableExceptionWarning: Exception ignored in: <function AuthorizedHttp.__del__ at 0x7f591a490160>

  Traceback (most recent call last):
    File "/home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/google/auth/transport/urllib3.py", line 432, in __del__
      self.http.clear()
  AttributeError: 'HttpStub' object has no attribute 'clear'

    warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))

tests_async/test_credentials_async.py::test_before_request
  /home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/tests_async/test_credentials_async.py:81: RuntimeWarning: coroutine 'Credentials.before_request' was never awaited
    credentials.before_request(request, "http://example.com", "GET", headers)
  Enable tracemalloc to get traceback where the object was allocated.
  See https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings for more info.

tests_async/transport/test_aiohttp_requests.py::TestRequestResponse::test_unsupported_session
  /home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/tests_async/transport/test_aiohttp_requests.py:119: DeprecationWarning: The object should be created within an async function
    http = aiohttp.ClientSession(auto_decompress=True)

tests_async/transport/test_aiohttp_requests.py::TestRequestResponse::test_unsupported_session
tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_constructor
tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_constructor_with_auth_request
  /usr/lib64/python3.8/site-packages/aiohttp/connector.py:771: DeprecationWarning: The object should be created within an async function
    super().__init__(

tests_async/transport/test_aiohttp_requests.py::TestRequestResponse::test_unsupported_session
tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_constructor
tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_constructor_with_auth_request
  /usr/lib64/python3.8/site-packages/aiohttp/connector.py:782: DeprecationWarning: The object should be created within an async function
    resolver = DefaultResolver(loop=self._loop)

tests_async/transport/test_aiohttp_requests.py::TestRequestResponse::test_unsupported_session
tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_constructor
tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_constructor_with_auth_request
  /usr/lib64/python3.8/site-packages/aiohttp/cookiejar.py:67: DeprecationWarning: The object should be created within an async function
    super().__init__(loop=loop)

tests_async/transport/test_aiohttp_requests.py::TestRequestResponse::test_timeout
  /home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/tests_async/transport/test_aiohttp_requests.py:128: RuntimeWarning: coroutine 'Request.__call__' was never awaited
    request(url="http://example.com", method="GET", timeout=5)
  Enable tracemalloc to get traceback where the object was allocated.
  See https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings for more info.

tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_constructor
tests_async/transport/test_aiohttp_requests.py::TestAuthorizedSession::test_constructor_with_auth_request
  /home/tkloczko/rpmbuild/BUILD/google-auth-library-python-2.11.0/google/auth/transport/_aiohttp_requests.py:247: DeprecationWarning: The object should be created within an async function
    super(AuthorizedSession, self).__init__()

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
========================================================================= short test summary info ==========================================================================
clundin25 commented 2 years ago

Hi @kloczek can you give me detailed steps to follow to reproduce this?

kloczek commented 2 years ago

One sec ..

kloczek commented 2 years ago

Make sure that you have installed build module

git clone https://github.com/googleapis/google-auth-library-python/
cd google-auth-library-python
python3 -sBm build -w --no-isolation
python3 -sBm pip install -I dist/google_auth-*.whl --root /tmp/python-google-auth-2.11.0 --disable-pip-version-check --no-cache-dir --no-deps --no-index --no-warn-script-location --progress-bar off --verbose --ignore-installed --no-warn-script-location
PYTHONPATH=/tmp/python-google-auth-2.11.0 pytest -ra --ignore tests/test__oauth2client.py