From d2ccdf69559fa28b0447dde2cbb16df690d81fe3 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 06:20:20 -0400 Subject: [PATCH 01/52] ci: remove Python 3.7 from run_single_test.sh --- ci/run_single_test.sh | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/ci/run_single_test.sh b/ci/run_single_test.sh index f7d6a53e7edd..a01d92e55b15 100755 --- a/ci/run_single_test.sh +++ b/ci/run_single_test.sh @@ -16,7 +16,7 @@ # This script requires the following environment variables to be set: # `TEST_TYPE` should be one of ["lint", "lint_setup_py", "docs", "docfx", "prerelease"] -# `PY_VERSION` should be one of ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] +# `PY_VERSION` should be one of ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] # This script is called by the `ci/run_conditional_tests.sh` script. # A specific `nox` session will be run, depending on the value of @@ -70,10 +70,6 @@ case ${TEST_TYPE} in ;; unit) case ${PY_VERSION} in - "3.7") - nox -s unit-3.7 - retval=$? - ;; "3.8") nox -s unit-3.8 retval=$? From 09ad9e1a799663480a6a6bc3e6b7469d42457937 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 06:20:42 -0400 Subject: [PATCH 02/52] chore(templates): update python version in mypy.ini.j2 to 3.8 --- packages/gapic-generator/gapic/ads-templates/mypy.ini.j2 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/gapic-generator/gapic/ads-templates/mypy.ini.j2 b/packages/gapic-generator/gapic/ads-templates/mypy.ini.j2 index 574c5aed394b..beaa679a8d2b 100644 --- a/packages/gapic-generator/gapic/ads-templates/mypy.ini.j2 +++ b/packages/gapic-generator/gapic/ads-templates/mypy.ini.j2 @@ -1,3 +1,3 @@ [mypy] -python_version = 3.7 +python_version = 3.8 namespace_packages = True From ea3801ee1ff5268995ecfb4ee16ac75b1a08776f Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 06:21:39 -0400 Subject: [PATCH 03/52] docs(gapic-generator): update Python version in index.rst to 3.8+ --- packages/gapic-generator/docs/getting-started/index.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/gapic-generator/docs/getting-started/index.rst b/packages/gapic-generator/docs/getting-started/index.rst index 6f288f6bb5c2..1215c6867ebf 100644 --- a/packages/gapic-generator/docs/getting-started/index.rst +++ b/packages/gapic-generator/docs/getting-started/index.rst @@ -2,7 +2,7 @@ Getting Started --------------- This code generator is implemented as a plugin to ``protoc``, the compiler -for `protocol buffers`_, and will run in any environment that Python 3.7+ and +for `protocol buffers`_, and will run in any environment that Python 3.8+ and protocol buffers do. It is recommended to install the tool locally and run it through ``protoc``. From e57206dd29be351f41d6e4af6d05af2e68c030de Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 06:22:03 -0400 Subject: [PATCH 04/52] docs(gapic-generator): update Python version in bazel.rst to 3.8+ --- packages/gapic-generator/docs/getting-started/bazel.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/gapic-generator/docs/getting-started/bazel.rst b/packages/gapic-generator/docs/getting-started/bazel.rst index 21af6d43fb42..3d8cea77bde6 100644 --- a/packages/gapic-generator/docs/getting-started/bazel.rst +++ b/packages/gapic-generator/docs/getting-started/bazel.rst @@ -29,7 +29,7 @@ install it is simply downloading the binary and making it executable: Python and Dependencies ~~~~~~~~~~~~~~~~~~~~~~~ Bazel build is mostly hermetic, with a few exceptions for Python generator. -Specifically it expects Python 3.7+ with the python dev packages to be installed. +Specifically it expects Python 3.8+ with the python dev packages to be installed. On Linux, to install those, simply run: From 8279e27e3c57bedc4c898474202b0398a94f6c29 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 06:22:22 -0400 Subject: [PATCH 05/52] docs(gapic-generator): update Python version in _verifying.rst to 3.8 --- packages/gapic-generator/docs/getting-started/_verifying.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/gapic-generator/docs/getting-started/_verifying.rst b/packages/gapic-generator/docs/getting-started/_verifying.rst index 325090ed1aa3..5cc7e26a2d44 100644 --- a/packages/gapic-generator/docs/getting-started/_verifying.rst +++ b/packages/gapic-generator/docs/getting-started/_verifying.rst @@ -8,7 +8,7 @@ Create a virtual environment for the library: .. code-block:: shell - $ virtualenv ~/.local/client-lib --python=`which python3.7` + $ virtualenv ~/.local/client-lib --python=`which python3.8` $ source ~/.local/client-lib/bin/activate Next, install the library: From f377a01c54fbd124f5573c4c0657f46e622d0c32 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 06:36:08 -0400 Subject: [PATCH 06/52] chore(templates): update Python version requirement and clean up __init__.py.j2 --- .../gapic/ads-templates/%namespace/%name/__init__.py.j2 | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/gapic-generator/gapic/ads-templates/%namespace/%name/__init__.py.j2 b/packages/gapic-generator/gapic/ads-templates/%namespace/%name/__init__.py.j2 index abdafe27172a..eca52e4449b4 100644 --- a/packages/gapic-generator/gapic/ads-templates/%namespace/%name/__init__.py.j2 +++ b/packages/gapic-generator/gapic/ads-templates/%namespace/%name/__init__.py.j2 @@ -6,8 +6,8 @@ import importlib import sys -if sys.version_info < (3, 7): - raise ImportError('This module requires Python 3.7 or later.') +if sys.version_info < (3, 8): + raise ImportError('This module requires Python 3.8 or later.') _lazy_type_to_package_map = { @@ -30,14 +30,14 @@ _lazy_type_to_package_map = { # Background on how this behaves: https://www.python.org/dev/peps/pep-0562/ -def __getattr__(name): # Requires Python >= 3.7 +def __getattr__(name): if name == '__all__': all_names = globals()['__all__'] = sorted(_lazy_type_to_package_map) return all_names elif name in _lazy_type_to_package_map: module = importlib.import_module(f'{_lazy_type_to_package_map[name]}') klass = getattr(module, name) - {# new_klass = type(name, (klass,), {'__doc__': klass.__doc__}) #} + globals()[name] = klass return klass else: From 042e3ef0320360bfe23ed7acca7218f05578f712 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 06:36:11 -0400 Subject: [PATCH 07/52] chore(templates): update Python version requirement and clean up versioned __init__.py.j2 --- .../%namespace/%name/%version/__init__.py.j2 | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/gapic-generator/gapic/ads-templates/%namespace/%name/%version/__init__.py.j2 b/packages/gapic-generator/gapic/ads-templates/%namespace/%name/%version/__init__.py.j2 index 5a8d6d6bacbc..00353bc6b47f 100644 --- a/packages/gapic-generator/gapic/ads-templates/%namespace/%name/%version/__init__.py.j2 +++ b/packages/gapic-generator/gapic/ads-templates/%namespace/%name/%version/__init__.py.j2 @@ -11,8 +11,8 @@ from {{package_path}} import gapic_version as package_version __version__ = package_version.__version__ -if sys.version_info < (3, 7): - raise ImportError('This module requires Python 3.7 or later.') +if sys.version_info < (3, 8): + raise ImportError('This module requires Python 3.8 or later.') _lazy_type_to_package_map = { @@ -37,14 +37,14 @@ _lazy_type_to_package_map = { # Background on how this behaves: https://www.python.org/dev/peps/pep-0562/ -def __getattr__(name): # Requires Python >= 3.7 +def __getattr__(name): if name == '__all__': all_names = globals()['__all__'] = sorted(_lazy_type_to_package_map) return all_names elif name in _lazy_type_to_package_map: module = importlib.import_module(f'{_lazy_type_to_package_map[name]}') klass = getattr(module, name) - {# new_klass = type(name, (klass,), {'__doc__': klass.__doc__}) #} + globals()[name] = klass return klass else: From e75c0f68a8002060b78f551cb52b1a343b41a747 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 07:51:39 -0400 Subject: [PATCH 08/52] chore(gapic-generator): remove outdated comment in options.py --- packages/gapic-generator/gapic/utils/options.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/gapic-generator/gapic/utils/options.py b/packages/gapic-generator/gapic/utils/options.py index 30184f12c0a9..953972c543c0 100644 --- a/packages/gapic-generator/gapic/utils/options.py +++ b/packages/gapic-generator/gapic/utils/options.py @@ -57,7 +57,7 @@ class Options: OPT_FLAGS: FrozenSet[str] = frozenset( ( "add-iam-methods", # microgenerator implementation for `reroute_to_grpc_interface` - "lazy-import", # requires >= 3.7 + "lazy-import", "metadata", # generate GAPIC metadata JSON file "old-naming", # TODO(dovs): Come up with a better comment "retry-config", # takes a path From 0eb3b09d35aac3247e244b6b322e9c0f8c58168b Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 13:16:36 -0400 Subject: [PATCH 09/52] chore(gapic): update Python version requirement to 3.10 in setup.py and noxfile.py --- packages/gapic-generator/noxfile.py | 5 ++--- packages/gapic-generator/setup.py | 3 +-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/packages/gapic-generator/noxfile.py b/packages/gapic-generator/noxfile.py index d931a5258814..e170072d4696 100644 --- a/packages/gapic-generator/noxfile.py +++ b/packages/gapic-generator/noxfile.py @@ -44,7 +44,6 @@ RUFF_EXCLUDES = "*golden*,*pb2.py,*pb2.pyi" ALL_PYTHON = ( - "3.9", "3.10", "3.11", "3.12", @@ -181,7 +180,7 @@ def fragment(session, use_ads_templates=False): session.install("-e", ".") # The specific failure is `Plugin output is unparseable` - if session.python in ("3.9", "3.10"): + if session.python == "3.10": session.install("google-api-core<2.28") frag_files = ( @@ -251,7 +250,7 @@ def showcase_library( # Warnings emitted from google-api-core starting in 2.28 # appear to cause issues when running protoc. # The specific failure is `Plugin output is unparseable` - if session.python in ("3.9", "3.10"): + if session.python == "3.10": session.install("google-api-core<2.28") # Install a client library for Showcase. diff --git a/packages/gapic-generator/setup.py b/packages/gapic-generator/setup.py index 6bd32bc0caff..95c587d165ae 100644 --- a/packages/gapic-generator/setup.py +++ b/packages/gapic-generator/setup.py @@ -70,7 +70,6 @@ "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", @@ -81,7 +80,7 @@ "Topic :: Software Development :: Libraries :: Python Modules", ], platforms="Posix; MacOS X", - python_requires=">=3.9", + python_requires=">=3.10", install_requires=dependencies, include_package_data=True, zip_safe=False, From 830c66f0eb14d5bf7be2a25de7a80b90df56c526 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 13:16:47 -0400 Subject: [PATCH 10/52] chore(gapic): use functools.cache instead of lru_cache in wrappers.py --- packages/gapic-generator/gapic/schema/wrappers.py | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/packages/gapic-generator/gapic/schema/wrappers.py b/packages/gapic-generator/gapic/schema/wrappers.py index f654d0a82d18..085132b4bf4e 100644 --- a/packages/gapic-generator/gapic/schema/wrappers.py +++ b/packages/gapic-generator/gapic/schema/wrappers.py @@ -1284,19 +1284,13 @@ def _to_regex(self, path_template: str) -> Pattern: return re.compile(f"^{self._convert_to_regex(path_template)}$") # Use caching to avoid repeated computation - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2161): - # Use `@functools.cache` instead of `@functools.lru_cache` once python 3.8 is dropped. - # https://docs.python.org/3/library/functools.html#functools.cache - @functools.lru_cache(maxsize=None) + @functools.cache def to_regex(self) -> Pattern: return self._to_regex(self.path_template) @property # Use caching to avoid repeated computation - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2161): - # Use `@functools.cache` instead of `@functools.lru_cache` once python 3.8 is dropped. - # https://docs.python.org/3/library/functools.html#functools.cache - @functools.lru_cache(maxsize=None) + @functools.cache def key(self) -> Union[str, None]: if self.path_template == "": return self.field From eb0105071fbf225267e0ef0406037455928d5281 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 13:16:52 -0400 Subject: [PATCH 11/52] chore(gapic): update Python version in setup and mypy templates --- packages/gapic-generator/gapic/ads-templates/mypy.ini.j2 | 2 +- packages/gapic-generator/gapic/ads-templates/setup.py.j2 | 3 +-- packages/gapic-generator/gapic/templates/setup.py.j2 | 3 +-- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/packages/gapic-generator/gapic/ads-templates/mypy.ini.j2 b/packages/gapic-generator/gapic/ads-templates/mypy.ini.j2 index beaa679a8d2b..cb397f571128 100644 --- a/packages/gapic-generator/gapic/ads-templates/mypy.ini.j2 +++ b/packages/gapic-generator/gapic/ads-templates/mypy.ini.j2 @@ -1,3 +1,3 @@ [mypy] -python_version = 3.8 +python_version = 3.10 namespace_packages = True diff --git a/packages/gapic-generator/gapic/ads-templates/setup.py.j2 b/packages/gapic-generator/gapic/ads-templates/setup.py.j2 index b0230a674f4b..1684c2de1a61 100644 --- a/packages/gapic-generator/gapic/ads-templates/setup.py.j2 +++ b/packages/gapic-generator/gapic/ads-templates/setup.py.j2 @@ -64,7 +64,6 @@ setuptools.setup( "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", @@ -75,7 +74,7 @@ setuptools.setup( ], platforms="Posix; MacOS X; Windows", packages=packages, - python_requires=">=3.9", + python_requires=">=3.10", install_requires=dependencies, include_package_data=True, zip_safe=False, diff --git a/packages/gapic-generator/gapic/templates/setup.py.j2 b/packages/gapic-generator/gapic/templates/setup.py.j2 index 2a725f7a1c5e..b803e1b6df96 100644 --- a/packages/gapic-generator/gapic/templates/setup.py.j2 +++ b/packages/gapic-generator/gapic/templates/setup.py.j2 @@ -89,7 +89,6 @@ setuptools.setup( "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", @@ -100,7 +99,7 @@ setuptools.setup( ], platforms="Posix; MacOS X; Windows", packages=packages, - python_requires=">=3.9", + python_requires=">=3.10", install_requires=dependencies, extras_require=extras, include_package_data=True, From 9a6decef3be36cd6a4b9611d2211fda246a24155 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 13:17:02 -0400 Subject: [PATCH 12/52] chore(gapic): clean up Python version guards and imports in templates --- .../%namespace/%name/%version/__init__.py.j2 | 4 ++-- .../%namespace/%name/__init__.py.j2 | 4 ++-- .../%name_%version/%sub/__init__.py.j2 | 19 +++---------------- .../%name_%version/%sub/test_%service.py.j2 | 8 ++------ 4 files changed, 9 insertions(+), 26 deletions(-) diff --git a/packages/gapic-generator/gapic/ads-templates/%namespace/%name/%version/__init__.py.j2 b/packages/gapic-generator/gapic/ads-templates/%namespace/%name/%version/__init__.py.j2 index 00353bc6b47f..8bb1a4d8fc37 100644 --- a/packages/gapic-generator/gapic/ads-templates/%namespace/%name/%version/__init__.py.j2 +++ b/packages/gapic-generator/gapic/ads-templates/%namespace/%name/%version/__init__.py.j2 @@ -11,8 +11,8 @@ from {{package_path}} import gapic_version as package_version __version__ = package_version.__version__ -if sys.version_info < (3, 8): - raise ImportError('This module requires Python 3.8 or later.') +if sys.version_info < (3, 10): + raise ImportError('This module requires Python 3.10 or later.') _lazy_type_to_package_map = { diff --git a/packages/gapic-generator/gapic/ads-templates/%namespace/%name/__init__.py.j2 b/packages/gapic-generator/gapic/ads-templates/%namespace/%name/__init__.py.j2 index eca52e4449b4..6f8f58eb8b4f 100644 --- a/packages/gapic-generator/gapic/ads-templates/%namespace/%name/__init__.py.j2 +++ b/packages/gapic-generator/gapic/ads-templates/%namespace/%name/__init__.py.j2 @@ -6,8 +6,8 @@ import importlib import sys -if sys.version_info < (3, 8): - raise ImportError('This module requires Python 3.8 or later.') +if sys.version_info < (3, 10): + raise ImportError('This module requires Python 3.10 or later.') _lazy_type_to_package_map = { diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/__init__.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/__init__.py.j2 index 9eb968dd011b..8b80bec9281a 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/__init__.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/__init__.py.j2 @@ -10,12 +10,7 @@ import sys __version__ = package_version.__version__ -if sys.version_info >= (3, 8): # pragma: NO COVER - from importlib import metadata -else: # pragma: NO COVER - # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove - # this code path once we drop support for Python 3.7 - import importlib_metadata as metadata +from importlib import metadata {# Import subpackages. -#} {% for subpackage, _ in api.subpackages|dictsort %} @@ -65,20 +60,12 @@ else: # pragma: NO COVER _py_version_str = sys.version.split()[0] _package_label = "{{package_path}}" - if sys.version_info < (3, 9): + if sys.version_info < (3, 10): warnings.warn("You are using a non-supported Python version " + f"({_py_version_str}). Google will not post any further " + f"updates to {_package_label} supporting this Python version. " + "Please upgrade to the latest Python version, or at " + - f"least to Python 3.9, and then update {_package_label}.", - FutureWarning) - if sys.version_info[:2] == (3, 9): - warnings.warn(f"You are using a Python version ({_py_version_str}) " + - f"which Google will stop supporting in {_package_label} in " + - "January 2026. Please " + - "upgrade to the latest Python version, or at " + - "least to Python 3.10, before then, and " + - f"then update {_package_label}.", + f"least to Python 3.10, and then update {_package_label}.", FutureWarning) def parse_version_to_tuple(version_string: str): diff --git a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 index 0a48dd6e1887..cb5f9c4d77df 100644 --- a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 +++ b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 @@ -10,12 +10,8 @@ import os {% if api.all_method_settings.values()|map(attribute="auto_populated_fields", default=[])|list %} import re {% endif %} -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock +from unittest import mock +from unittest.mock import AsyncMock import grpc from grpc.experimental import aio From 3f6a95ceb4053737d58d51f69413a18646027609 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 06:26:56 -0400 Subject: [PATCH 13/52] ci: update Python version comment in run_conditional_tests.sh --- ci/run_conditional_tests.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ci/run_conditional_tests.sh b/ci/run_conditional_tests.sh index 35505a059f65..afdb605b960d 100755 --- a/ci/run_conditional_tests.sh +++ b/ci/run_conditional_tests.sh @@ -17,7 +17,7 @@ # `BUILD_TYPE` should be one of ["presubmit", "continuous"] # `TEST_TYPE` should be one of ["docs", "docfx", "prerelease", "unit"] # or match the name of the nox session that you want to run. -# `PY_VERSION` should be one of ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +# `PY_VERSION` should be one of ["3.8", "3.9", "3.10", "3.11", "3.12"] # `TEST_TYPE` and `PY_VERSION` are required by the script `ci/run_single_test.sh` From 37f8f6a24d966e80db88985e48a6435049177544 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 14:08:12 -0400 Subject: [PATCH 14/52] chore(gapic): drop Python 3.8 and 3.9 from CI shell scripts --- ci/run_conditional_tests.sh | 2 +- ci/run_single_test.sh | 10 +--------- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/ci/run_conditional_tests.sh b/ci/run_conditional_tests.sh index afdb605b960d..9b8eaee52e5b 100755 --- a/ci/run_conditional_tests.sh +++ b/ci/run_conditional_tests.sh @@ -17,7 +17,7 @@ # `BUILD_TYPE` should be one of ["presubmit", "continuous"] # `TEST_TYPE` should be one of ["docs", "docfx", "prerelease", "unit"] # or match the name of the nox session that you want to run. -# `PY_VERSION` should be one of ["3.8", "3.9", "3.10", "3.11", "3.12"] +# `PY_VERSION` should be one of ["3.10", "3.11", "3.12"] # `TEST_TYPE` and `PY_VERSION` are required by the script `ci/run_single_test.sh` diff --git a/ci/run_single_test.sh b/ci/run_single_test.sh index a01d92e55b15..376660a58b2a 100755 --- a/ci/run_single_test.sh +++ b/ci/run_single_test.sh @@ -16,7 +16,7 @@ # This script requires the following environment variables to be set: # `TEST_TYPE` should be one of ["lint", "lint_setup_py", "docs", "docfx", "prerelease"] -# `PY_VERSION` should be one of ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] +# `PY_VERSION` should be one of ["3.10", "3.11", "3.12", "3.13"] # This script is called by the `ci/run_conditional_tests.sh` script. # A specific `nox` session will be run, depending on the value of @@ -70,14 +70,6 @@ case ${TEST_TYPE} in ;; unit) case ${PY_VERSION} in - "3.8") - nox -s unit-3.8 - retval=$? - ;; - "3.9") - nox -s unit-3.9 - retval=$? - ;; "3.10") nox -s unit-3.10 retval=$? From 9770d830a695e701d2928d6a32f487153850e741 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 14:08:23 -0400 Subject: [PATCH 15/52] chore(gapic): remove Python 3.9 from generated noxfile templates --- packages/gapic-generator/gapic/ads-templates/noxfile.py.j2 | 1 - packages/gapic-generator/gapic/templates/noxfile.py.j2 | 1 - 2 files changed, 2 deletions(-) diff --git a/packages/gapic-generator/gapic/ads-templates/noxfile.py.j2 b/packages/gapic-generator/gapic/ads-templates/noxfile.py.j2 index 34c35ed0f3b1..0a42cd6e4fa0 100644 --- a/packages/gapic-generator/gapic/ads-templates/noxfile.py.j2 +++ b/packages/gapic-generator/gapic/ads-templates/noxfile.py.j2 @@ -11,7 +11,6 @@ import nox # type: ignore # Add tests for Python 3.15 alpha1 # https://peps.python.org/pep-0790/ ALL_PYTHON = [ - "3.9", "3.10", "3.11", "3.12", diff --git a/packages/gapic-generator/gapic/templates/noxfile.py.j2 b/packages/gapic-generator/gapic/templates/noxfile.py.j2 index c628aad47051..244173b4b42d 100644 --- a/packages/gapic-generator/gapic/templates/noxfile.py.j2 +++ b/packages/gapic-generator/gapic/templates/noxfile.py.j2 @@ -25,7 +25,6 @@ if os.path.isdir("samples"): LINT_PATHS.append("samples") ALL_PYTHON = [ - "3.9", "3.10", "3.11", "3.12", From 8017018a534bebb0aa164a5bb700c751726b423d Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 14:08:31 -0400 Subject: [PATCH 16/52] chore(gapic): update target version in generator and clean up test macros --- .generator/cli.py | 2 +- .generator/test_cli.py | 2 +- .../tests/unit/gapic/%name_%version/%sub/test_macros.j2 | 4 +--- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/.generator/cli.py b/.generator/cli.py index 9415e0ca2ea3..0f5078204c44 100644 --- a/.generator/cli.py +++ b/.generator/cli.py @@ -354,7 +354,7 @@ def _run_post_processor(output: str, library_id: str, is_mono_repo: bool): # TODO(https://github.com/googleapis/google-cloud-python/issues/15538): # Investigate if a `target_version needs to be maintained # or can be eliminated. - target_version = "py39" + target_version = "py310" common_args = [ f"--target-version={target_version}", "--line-length=88", diff --git a/.generator/test_cli.py b/.generator/test_cli.py index 68d61343f145..4ccd9a3b1359 100644 --- a/.generator/test_cli.py +++ b/.generator/test_cli.py @@ -741,7 +741,7 @@ def test_run_individual_session_success(mocker, caplog, is_mono_repo): "cli.subprocess.run", return_value=MagicMock(returncode=0) ) - test_session = "unit-3.9" + test_session = "unit-3.10" test_library_id = "test-library" repo = "repo" _run_individual_session(test_session, test_library_id, repo, is_mono_repo) diff --git a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_macros.j2 b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_macros.j2 index 2ab58f5cb881..ff6a15014e10 100644 --- a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_macros.j2 +++ b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_macros.j2 @@ -1005,9 +1005,7 @@ async def test_{{ method_name }}_async_pages(): {% endif %} ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.{{ method_name }}(request={}) ).pages: pages.append(page_) From e7a2039f724786c25757c518826aec4c9754fb1d Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 14:14:11 -0400 Subject: [PATCH 17/52] docs(gapic-generator): update Python version to 3.10 in getting-started docs --- packages/gapic-generator/docs/getting-started/_verifying.rst | 2 +- packages/gapic-generator/docs/getting-started/bazel.rst | 2 +- packages/gapic-generator/docs/getting-started/index.rst | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/gapic-generator/docs/getting-started/_verifying.rst b/packages/gapic-generator/docs/getting-started/_verifying.rst index 5cc7e26a2d44..7603047a4c4b 100644 --- a/packages/gapic-generator/docs/getting-started/_verifying.rst +++ b/packages/gapic-generator/docs/getting-started/_verifying.rst @@ -8,7 +8,7 @@ Create a virtual environment for the library: .. code-block:: shell - $ virtualenv ~/.local/client-lib --python=`which python3.8` + $ virtualenv ~/.local/client-lib --python=`which python3.10` $ source ~/.local/client-lib/bin/activate Next, install the library: diff --git a/packages/gapic-generator/docs/getting-started/bazel.rst b/packages/gapic-generator/docs/getting-started/bazel.rst index 3d8cea77bde6..6b6e2702dbf8 100644 --- a/packages/gapic-generator/docs/getting-started/bazel.rst +++ b/packages/gapic-generator/docs/getting-started/bazel.rst @@ -29,7 +29,7 @@ install it is simply downloading the binary and making it executable: Python and Dependencies ~~~~~~~~~~~~~~~~~~~~~~~ Bazel build is mostly hermetic, with a few exceptions for Python generator. -Specifically it expects Python 3.8+ with the python dev packages to be installed. +Specifically it expects Python 3.10+ with the python dev packages to be installed. On Linux, to install those, simply run: diff --git a/packages/gapic-generator/docs/getting-started/index.rst b/packages/gapic-generator/docs/getting-started/index.rst index 1215c6867ebf..a82fddbefa83 100644 --- a/packages/gapic-generator/docs/getting-started/index.rst +++ b/packages/gapic-generator/docs/getting-started/index.rst @@ -2,7 +2,7 @@ Getting Started --------------- This code generator is implemented as a plugin to ``protoc``, the compiler -for `protocol buffers`_, and will run in any environment that Python 3.8+ and +for `protocol buffers`_, and will run in any environment that Python 3.10+ and protocol buffers do. It is recommended to install the tool locally and run it through ``protoc``. From c4951ded9c6352434f812863dcd028f6b8c7a992 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 14:18:44 -0400 Subject: [PATCH 18/52] chore(gapic): clean up imports in ads-templates test template --- .../unit/gapic/%name_%version/%sub/test_%service.py.j2 | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/packages/gapic-generator/gapic/ads-templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 b/packages/gapic-generator/gapic/ads-templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 index 39d5fa7d35e7..6ef2d20d14f8 100644 --- a/packages/gapic-generator/gapic/ads-templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 +++ b/packages/gapic-generator/gapic/ads-templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 @@ -7,12 +7,8 @@ import os {% if api.all_method_settings.values()|map(attribute="auto_populated_fields", default=[])|list %} import re {% endif %} -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock +from unittest import mock +from unittest.mock import AsyncMock import grpc from grpc.experimental import aio From 8917093b3cd61ed54374a4e8530de21d859c5159 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 14:28:05 -0400 Subject: [PATCH 19/52] chore(gapic): add ignore pragmas for false positives --- .generator/Dockerfile | 2 +- .pre-commit-config.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.generator/Dockerfile b/.generator/Dockerfile index 2c8a0674bac0..2bfa0e2defdf 100644 --- a/.generator/Dockerfile +++ b/.generator/Dockerfile @@ -66,7 +66,7 @@ RUN unzip protoc-25.3-linux-x86_64.zip -d protoc # Download/extract pandoc # Pandoc is required by gapic-generator-python for parsing documentation -ENV PANDOC_VERSION=3.8.2 +ENV PANDOC_VERSION=3.8.2 # version-scanner: ignore RUN mkdir pandoc-binary RUN wget https://github.com/jgm/pandoc/releases/download/${PANDOC_VERSION}/pandoc-${PANDOC_VERSION}-linux-amd64.tar.gz RUN tar -xvf pandoc-${PANDOC_VERSION}-linux-amd64.tar.gz -C pandoc-binary --strip-components=1 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5405cc8ff1f3..427359befa73 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,6 +26,6 @@ repos: hooks: - id: black - repo: https://github.com/pycqa/flake8 - rev: 3.9.2 + rev: 3.9.2 # version-scanner: ignore hooks: - id: flake8 From 57281c339cf7ca7e404f121f02b8f5c9f34b3502 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 14:33:29 -0400 Subject: [PATCH 20/52] chore(gapic): use ignore-next-line pragma in Dockerfile --- .generator/Dockerfile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.generator/Dockerfile b/.generator/Dockerfile index 2bfa0e2defdf..fc626f4b3481 100644 --- a/.generator/Dockerfile +++ b/.generator/Dockerfile @@ -66,7 +66,8 @@ RUN unzip protoc-25.3-linux-x86_64.zip -d protoc # Download/extract pandoc # Pandoc is required by gapic-generator-python for parsing documentation -ENV PANDOC_VERSION=3.8.2 # version-scanner: ignore +# version-scanner: ignore-next-line +ENV PANDOC_VERSION=3.8.2 RUN mkdir pandoc-binary RUN wget https://github.com/jgm/pandoc/releases/download/${PANDOC_VERSION}/pandoc-${PANDOC_VERSION}-linux-amd64.tar.gz RUN tar -xvf pandoc-${PANDOC_VERSION}-linux-amd64.tar.gz -C pandoc-binary --strip-components=1 From 9ae1839b0fb59027e62592ba3d16987682872495 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 1 May 2026 15:14:27 -0400 Subject: [PATCH 21/52] chore(gapic): remove Python 3.9 templates and update workflow matrix --- .github/workflows/gapic-generator-tests.yml | 2 +- .../testing/constraints-3.9-async-rest.txt.j2 | 24 ------------------- .../templates/testing/constraints-3.9.txt.j2 | 21 ---------------- 3 files changed, 1 insertion(+), 46 deletions(-) delete mode 100644 packages/gapic-generator/gapic/templates/testing/constraints-3.9-async-rest.txt.j2 delete mode 100644 packages/gapic-generator/gapic/templates/testing/constraints-3.9.txt.j2 diff --git a/.github/workflows/gapic-generator-tests.yml b/.github/workflows/gapic-generator-tests.yml index 204e110a0b72..3909f860ab98 100644 --- a/.github/workflows/gapic-generator-tests.yml +++ b/.github/workflows/gapic-generator-tests.yml @@ -18,7 +18,7 @@ env: SHOWCASE_VERSION: 0.35.0 PROTOC_VERSION: 3.20.2 LATEST_STABLE_PYTHON: 3.14 - ALL_PYTHON: "['3.9', '3.10', '3.11', '3.12', '3.13', '3.14']" + ALL_PYTHON: "['3.10', '3.11', '3.12', '3.13', '3.14']" jobs: check_changes: diff --git a/packages/gapic-generator/gapic/templates/testing/constraints-3.9-async-rest.txt.j2 b/packages/gapic-generator/gapic/templates/testing/constraints-3.9-async-rest.txt.j2 deleted file mode 100644 index 3a1222949a04..000000000000 --- a/packages/gapic-generator/gapic/templates/testing/constraints-3.9-async-rest.txt.j2 +++ /dev/null @@ -1,24 +0,0 @@ -{% set rest_async_io_enabled = api.all_library_settings[api.naming.proto_package].python_settings.experimental_features.rest_async_io_enabled %} -{% if rest_async_io_enabled %} -# -*- coding: utf-8 -*- -{% from '_pypi_packages.j2' import pypi_packages %} -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file, -# pinning their versions to their lower bounds. -# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# then this file should have google-cloud-foo==1.14.0 -google-api-core==2.21.0 -google-auth==2.35.0 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 -{% for package_tuple, package_info in pypi_packages.items() %} -{# Quick check to make sure `package_info.package_name` is not the package being generated so we don't circularly include this package in its own constraints file. #} -{% if api.naming.warehouse_package_name != package_info.package_name %} -{% if api.requires_package(package_tuple) %} -{{ package_info.package_name }}=={{ package_info.lower_bound }} -{% endif %} -{% endif %} -{% endfor %} -{% endif %} diff --git a/packages/gapic-generator/gapic/templates/testing/constraints-3.9.txt.j2 b/packages/gapic-generator/gapic/templates/testing/constraints-3.9.txt.j2 deleted file mode 100644 index 95510412186f..000000000000 --- a/packages/gapic-generator/gapic/templates/testing/constraints-3.9.txt.j2 +++ /dev/null @@ -1,21 +0,0 @@ -# -*- coding: utf-8 -*- -{% from '_pypi_packages.j2' import pypi_packages %} -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file, -# pinning their versions to their lower bounds. -# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# then this file should have google-cloud-foo==1.14.0 -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 -{% for package_tuple, package_info in pypi_packages.items() %} -{# Quick check to make sure `package_info.package_name` is not the package being generated so we don't circularly include this package in its own constraints file. #} -{% if api.naming.warehouse_package_name != package_info.package_name %} -{% if api.requires_package(package_tuple) %} -{{ package_info.package_name }}=={{ package_info.lower_bound }} -{% endif %} -{% endif %} -{% endfor %} From 490f52aa520142c55b123d89e11679c388e1242e Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 07:51:35 -0400 Subject: [PATCH 22/52] chore(gapic-generator): update goldens for asset --- .../asset/google/cloud/asset_v1/__init__.py | 19 ++-------- .../integration/goldens/asset/noxfile.py | 1 - .../tests/integration/goldens/asset/setup.py | 3 +- .../goldens/asset/testing/constraints-3.9.txt | 15 -------- .../unit/gapic/asset_v1/test_asset_service.py | 36 +++++-------------- 5 files changed, 13 insertions(+), 61 deletions(-) delete mode 100755 packages/gapic-generator/tests/integration/goldens/asset/testing/constraints-3.9.txt diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/__init__.py index 31068ac47299..3bc2be21fdc5 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/__init__.py @@ -20,12 +20,7 @@ __version__ = package_version.__version__ -if sys.version_info >= (3, 8): # pragma: NO COVER - from importlib import metadata -else: # pragma: NO COVER - # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove - # this code path once we drop support for Python 3.7 - import importlib_metadata as metadata +from importlib import metadata from .services.asset_service import AssetServiceClient @@ -121,20 +116,12 @@ _py_version_str = sys.version.split()[0] _package_label = "google.cloud.asset_v1" - if sys.version_info < (3, 9): + if sys.version_info < (3, 10): warnings.warn("You are using a non-supported Python version " + f"({_py_version_str}). Google will not post any further " + f"updates to {_package_label} supporting this Python version. " + "Please upgrade to the latest Python version, or at " + - f"least to Python 3.9, and then update {_package_label}.", - FutureWarning) - if sys.version_info[:2] == (3, 9): - warnings.warn(f"You are using a Python version ({_py_version_str}) " + - f"which Google will stop supporting in {_package_label} in " + - "January 2026. Please " + - "upgrade to the latest Python version, or at " + - "least to Python 3.10, before then, and " + - f"then update {_package_label}.", + f"least to Python 3.10, and then update {_package_label}.", FutureWarning) def parse_version_to_tuple(version_string: str): diff --git a/packages/gapic-generator/tests/integration/goldens/asset/noxfile.py b/packages/gapic-generator/tests/integration/goldens/asset/noxfile.py index ca9b5afb08f6..8a864233181b 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/noxfile.py @@ -32,7 +32,6 @@ LINT_PATHS.append("samples") ALL_PYTHON = [ - "3.9", "3.10", "3.11", "3.12", diff --git a/packages/gapic-generator/tests/integration/goldens/asset/setup.py b/packages/gapic-generator/tests/integration/goldens/asset/setup.py index 44bb98121411..a7b2657a98dd 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/setup.py @@ -83,7 +83,6 @@ "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", @@ -94,7 +93,7 @@ ], platforms="Posix; MacOS X; Windows", packages=packages, - python_requires=">=3.9", + python_requires=">=3.10", install_requires=dependencies, extras_require=extras, include_package_data=True, diff --git a/packages/gapic-generator/tests/integration/goldens/asset/testing/constraints-3.9.txt b/packages/gapic-generator/tests/integration/goldens/asset/testing/constraints-3.9.txt deleted file mode 100755 index cbf952c44973..000000000000 --- a/packages/gapic-generator/tests/integration/goldens/asset/testing/constraints-3.9.txt +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file, -# pinning their versions to their lower bounds. -# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# then this file should have google-cloud-foo==1.14.0 -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 -google-cloud-access-context-manager==0.2.0 -google-cloud-os-config==1.13.0 -grpc-google-iam-v1==0.14.0 diff --git a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py index 36f92b53433b..bf4e8882e38c 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py @@ -14,12 +14,8 @@ # limitations under the License. # import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock +from unittest import mock +from unittest.mock import AsyncMock import grpc from grpc.experimental import aio @@ -1699,9 +1695,7 @@ async def test_list_assets_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_assets(request={}) ).pages: pages.append(page_) @@ -4036,9 +4030,7 @@ async def test_search_all_resources_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.search_all_resources(request={}) ).pages: pages.append(page_) @@ -4557,9 +4549,7 @@ async def test_search_all_iam_policies_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.search_all_iam_policies(request={}) ).pages: pages.append(page_) @@ -6652,9 +6642,7 @@ async def test_list_saved_queries_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_saved_queries(request={}) ).pages: pages.append(page_) @@ -8038,9 +8026,7 @@ async def test_analyze_org_policies_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.analyze_org_policies(request={}) ).pages: pages.append(page_) @@ -8569,9 +8555,7 @@ async def test_analyze_org_policy_governed_containers_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.analyze_org_policy_governed_containers(request={}) ).pages: pages.append(page_) @@ -9100,9 +9084,7 @@ async def test_analyze_org_policy_governed_assets_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.analyze_org_policy_governed_assets(request={}) ).pages: pages.append(page_) From 8ff40d854cbd7c27575ad625c4cb775f3f3df2d5 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 07:51:35 -0400 Subject: [PATCH 23/52] chore(gapic-generator): update goldens for credentials --- .../google/iam/credentials_v1/__init__.py | 19 +++---------------- .../goldens/credentials/noxfile.py | 1 - .../integration/goldens/credentials/setup.py | 3 +-- .../credentials/testing/constraints-3.9.txt | 12 ------------ .../credentials_v1/test_iam_credentials.py | 8 ++------ 5 files changed, 6 insertions(+), 37 deletions(-) delete mode 100755 packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.9.txt diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/__init__.py index 2890169a652d..44c85c1895f8 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/__init__.py @@ -20,12 +20,7 @@ __version__ = package_version.__version__ -if sys.version_info >= (3, 8): # pragma: NO COVER - from importlib import metadata -else: # pragma: NO COVER - # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove - # this code path once we drop support for Python 3.7 - import importlib_metadata as metadata +from importlib import metadata from .services.iam_credentials import IAMCredentialsClient @@ -52,20 +47,12 @@ _py_version_str = sys.version.split()[0] _package_label = "google.iam.credentials_v1" - if sys.version_info < (3, 9): + if sys.version_info < (3, 10): warnings.warn("You are using a non-supported Python version " + f"({_py_version_str}). Google will not post any further " + f"updates to {_package_label} supporting this Python version. " + "Please upgrade to the latest Python version, or at " + - f"least to Python 3.9, and then update {_package_label}.", - FutureWarning) - if sys.version_info[:2] == (3, 9): - warnings.warn(f"You are using a Python version ({_py_version_str}) " + - f"which Google will stop supporting in {_package_label} in " + - "January 2026. Please " + - "upgrade to the latest Python version, or at " + - "least to Python 3.10, before then, and " + - f"then update {_package_label}.", + f"least to Python 3.10, and then update {_package_label}.", FutureWarning) def parse_version_to_tuple(version_string: str): diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py b/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py index a614b73d8480..5d529145149f 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py @@ -32,7 +32,6 @@ LINT_PATHS.append("samples") ALL_PYTHON = [ - "3.9", "3.10", "3.11", "3.12", diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/setup.py b/packages/gapic-generator/tests/integration/goldens/credentials/setup.py index 66af125ed53b..74e94c582cc0 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/setup.py @@ -80,7 +80,6 @@ "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", @@ -91,7 +90,7 @@ ], platforms="Posix; MacOS X; Windows", packages=packages, - python_requires=">=3.9", + python_requires=">=3.10", install_requires=dependencies, extras_require=extras, include_package_data=True, diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.9.txt b/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.9.txt deleted file mode 100755 index 4fabf1676a51..000000000000 --- a/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.9.txt +++ /dev/null @@ -1,12 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file, -# pinning their versions to their lower bounds. -# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# then this file should have google-cloud-foo==1.14.0 -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py index fa2116cdd719..f890571724a9 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py @@ -14,12 +14,8 @@ # limitations under the License. # import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock +from unittest import mock +from unittest.mock import AsyncMock import grpc from grpc.experimental import aio From 1bc002325d1e0da692a5e71dfd05fb199ac7a93c Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 07:51:36 -0400 Subject: [PATCH 24/52] chore(gapic-generator): update goldens for eventarc --- .../google/cloud/eventarc_v1/__init__.py | 19 +++------------ .../integration/goldens/eventarc/noxfile.py | 1 - .../integration/goldens/eventarc/setup.py | 3 +-- .../eventarc/testing/constraints-3.9.txt | 13 ---------- .../unit/gapic/eventarc_v1/test_eventarc.py | 24 +++++-------------- 5 files changed, 10 insertions(+), 50 deletions(-) delete mode 100755 packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.9.txt diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/__init__.py index 20d981ec3ecc..8bb9d3e0d187 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/__init__.py @@ -20,12 +20,7 @@ __version__ = package_version.__version__ -if sys.version_info >= (3, 8): # pragma: NO COVER - from importlib import metadata -else: # pragma: NO COVER - # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove - # this code path once we drop support for Python 3.7 - import importlib_metadata as metadata +from importlib import metadata from .services.eventarc import EventarcClient @@ -81,20 +76,12 @@ _py_version_str = sys.version.split()[0] _package_label = "google.cloud.eventarc_v1" - if sys.version_info < (3, 9): + if sys.version_info < (3, 10): warnings.warn("You are using a non-supported Python version " + f"({_py_version_str}). Google will not post any further " + f"updates to {_package_label} supporting this Python version. " + "Please upgrade to the latest Python version, or at " + - f"least to Python 3.9, and then update {_package_label}.", - FutureWarning) - if sys.version_info[:2] == (3, 9): - warnings.warn(f"You are using a Python version ({_py_version_str}) " + - f"which Google will stop supporting in {_package_label} in " + - "January 2026. Please " + - "upgrade to the latest Python version, or at " + - "least to Python 3.10, before then, and " + - f"then update {_package_label}.", + f"least to Python 3.10, and then update {_package_label}.", FutureWarning) def parse_version_to_tuple(version_string: str): diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/noxfile.py b/packages/gapic-generator/tests/integration/goldens/eventarc/noxfile.py index 584bb9d01c7e..6d38b74914ff 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/noxfile.py @@ -32,7 +32,6 @@ LINT_PATHS.append("samples") ALL_PYTHON = [ - "3.9", "3.10", "3.11", "3.12", diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/setup.py b/packages/gapic-generator/tests/integration/goldens/eventarc/setup.py index 200443c6be46..1d17384d2430 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/setup.py @@ -81,7 +81,6 @@ "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", @@ -92,7 +91,7 @@ ], platforms="Posix; MacOS X; Windows", packages=packages, - python_requires=">=3.9", + python_requires=">=3.10", install_requires=dependencies, extras_require=extras, include_package_data=True, diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.9.txt b/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.9.txt deleted file mode 100755 index b8eeaad1b14b..000000000000 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.9.txt +++ /dev/null @@ -1,13 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file, -# pinning their versions to their lower bounds. -# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# then this file should have google-cloud-foo==1.14.0 -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 -grpc-google-iam-v1==0.14.0 diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py index eff2b1349f42..49229b3c3646 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py @@ -14,12 +14,8 @@ # limitations under the License. # import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock +from unittest import mock +from unittest.mock import AsyncMock import grpc from grpc.experimental import aio @@ -1809,9 +1805,7 @@ async def test_list_triggers_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_triggers(request={}) ).pages: pages.append(page_) @@ -3655,9 +3649,7 @@ async def test_list_channels_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_channels(request={}) ).pages: pages.append(page_) @@ -5464,9 +5456,7 @@ async def test_list_providers_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_providers(request={}) ).pages: pages.append(page_) @@ -6296,9 +6286,7 @@ async def test_list_channel_connections_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_channel_connections(request={}) ).pages: pages.append(page_) From f43aa3bd4f1872a8f96f57c17ec2e3ed5fc0ac9e Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 07:51:36 -0400 Subject: [PATCH 25/52] chore(gapic-generator): update goldens for logging --- .../google/cloud/logging_v2/__init__.py | 19 ++----------- .../integration/goldens/logging/noxfile.py | 1 - .../integration/goldens/logging/setup.py | 3 +- .../logging/testing/constraints-3.9.txt | 12 -------- .../logging_v2/test_config_service_v2.py | 28 +++++-------------- .../logging_v2/test_logging_service_v2.py | 20 ++++--------- .../logging_v2/test_metrics_service_v2.py | 12 ++------ 7 files changed, 19 insertions(+), 76 deletions(-) delete mode 100755 packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.9.txt diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/__init__.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/__init__.py index 242a43882502..321ade08f204 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/__init__.py @@ -20,12 +20,7 @@ __version__ = package_version.__version__ -if sys.version_info >= (3, 8): # pragma: NO COVER - from importlib import metadata -else: # pragma: NO COVER - # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove - # this code path once we drop support for Python 3.7 - import importlib_metadata as metadata +from importlib import metadata from .services.config_service_v2 import ConfigServiceV2Client @@ -124,20 +119,12 @@ _py_version_str = sys.version.split()[0] _package_label = "google.cloud.logging_v2" - if sys.version_info < (3, 9): + if sys.version_info < (3, 10): warnings.warn("You are using a non-supported Python version " + f"({_py_version_str}). Google will not post any further " + f"updates to {_package_label} supporting this Python version. " + "Please upgrade to the latest Python version, or at " + - f"least to Python 3.9, and then update {_package_label}.", - FutureWarning) - if sys.version_info[:2] == (3, 9): - warnings.warn(f"You are using a Python version ({_py_version_str}) " + - f"which Google will stop supporting in {_package_label} in " + - "January 2026. Please " + - "upgrade to the latest Python version, or at " + - "least to Python 3.10, before then, and " + - f"then update {_package_label}.", + f"least to Python 3.10, and then update {_package_label}.", FutureWarning) def parse_version_to_tuple(version_string: str): diff --git a/packages/gapic-generator/tests/integration/goldens/logging/noxfile.py b/packages/gapic-generator/tests/integration/goldens/logging/noxfile.py index 491848c947bd..e45a048b01af 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/noxfile.py @@ -32,7 +32,6 @@ LINT_PATHS.append("samples") ALL_PYTHON = [ - "3.9", "3.10", "3.11", "3.12", diff --git a/packages/gapic-generator/tests/integration/goldens/logging/setup.py b/packages/gapic-generator/tests/integration/goldens/logging/setup.py index d330baf0cfcd..a17cf4632a23 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/setup.py @@ -80,7 +80,6 @@ "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", @@ -91,7 +90,7 @@ ], platforms="Posix; MacOS X; Windows", packages=packages, - python_requires=">=3.9", + python_requires=">=3.10", install_requires=dependencies, extras_require=extras, include_package_data=True, diff --git a/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.9.txt b/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.9.txt deleted file mode 100755 index 4fabf1676a51..000000000000 --- a/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.9.txt +++ /dev/null @@ -1,12 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file, -# pinning their versions to their lower bounds. -# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# then this file should have google-cloud-foo==1.14.0 -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py index a82aa311bceb..9ed5971fae95 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py @@ -14,12 +14,8 @@ # limitations under the License. # import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock +from unittest import mock +from unittest.mock import AsyncMock import grpc from grpc.experimental import aio @@ -1445,9 +1441,7 @@ async def test_list_buckets_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_buckets(request={}) ).pages: pages.append(page_) @@ -3617,9 +3611,7 @@ async def test_list_views_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_views(request={}) ).pages: pages.append(page_) @@ -5052,9 +5044,7 @@ async def test_list_sinks_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_sinks(request={}) ).pages: pages.append(page_) @@ -7559,9 +7549,7 @@ async def test_list_links_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_links(request={}) ).pages: pages.append(page_) @@ -8383,9 +8371,7 @@ async def test_list_exclusions_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_exclusions(request={}) ).pages: pages.append(page_) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py index e03a5e8bb8d2..e091184a3e02 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py @@ -14,12 +14,8 @@ # limitations under the License. # import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock +from unittest import mock +from unittest.mock import AsyncMock import grpc from grpc.experimental import aio @@ -1978,9 +1974,7 @@ async def test_list_log_entries_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_log_entries(request={}) ).pages: pages.append(page_) @@ -2334,9 +2328,7 @@ async def test_list_monitored_resource_descriptors_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_monitored_resource_descriptors(request={}) ).pages: pages.append(page_) @@ -2845,9 +2837,7 @@ async def test_list_logs_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_logs(request={}) ).pages: pages.append(page_) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py index 724afc7a5d59..784f6e665bd9 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py @@ -14,12 +14,8 @@ # limitations under the License. # import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock +from unittest import mock +from unittest.mock import AsyncMock import grpc from grpc.experimental import aio @@ -1445,9 +1441,7 @@ async def test_list_log_metrics_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_log_metrics(request={}) ).pages: pages.append(page_) From 4ecc6e445621dbe867a17542b2b8c6290f992dc7 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 07:51:36 -0400 Subject: [PATCH 26/52] chore(gapic-generator): update goldens for logging_internal --- .../google/cloud/logging_v2/__init__.py | 19 ++----------- .../goldens/logging_internal/noxfile.py | 1 - .../goldens/logging_internal/setup.py | 3 +- .../testing/constraints-3.9.txt | 12 -------- .../logging_v2/test_config_service_v2.py | 28 +++++-------------- .../logging_v2/test_logging_service_v2.py | 20 ++++--------- .../logging_v2/test_metrics_service_v2.py | 12 ++------ 7 files changed, 19 insertions(+), 76 deletions(-) delete mode 100755 packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.9.txt diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/__init__.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/__init__.py index 38f3dc49f500..6e70f5a50377 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/__init__.py @@ -20,12 +20,7 @@ __version__ = package_version.__version__ -if sys.version_info >= (3, 8): # pragma: NO COVER - from importlib import metadata -else: # pragma: NO COVER - # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove - # this code path once we drop support for Python 3.7 - import importlib_metadata as metadata +from importlib import metadata from .services.config_service_v2 import BaseConfigServiceV2Client @@ -124,20 +119,12 @@ _py_version_str = sys.version.split()[0] _package_label = "google.cloud.logging_v2" - if sys.version_info < (3, 9): + if sys.version_info < (3, 10): warnings.warn("You are using a non-supported Python version " + f"({_py_version_str}). Google will not post any further " + f"updates to {_package_label} supporting this Python version. " + "Please upgrade to the latest Python version, or at " + - f"least to Python 3.9, and then update {_package_label}.", - FutureWarning) - if sys.version_info[:2] == (3, 9): - warnings.warn(f"You are using a Python version ({_py_version_str}) " + - f"which Google will stop supporting in {_package_label} in " + - "January 2026. Please " + - "upgrade to the latest Python version, or at " + - "least to Python 3.10, before then, and " + - f"then update {_package_label}.", + f"least to Python 3.10, and then update {_package_label}.", FutureWarning) def parse_version_to_tuple(version_string: str): diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/noxfile.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/noxfile.py index 491848c947bd..e45a048b01af 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/noxfile.py @@ -32,7 +32,6 @@ LINT_PATHS.append("samples") ALL_PYTHON = [ - "3.9", "3.10", "3.11", "3.12", diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/setup.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/setup.py index d330baf0cfcd..a17cf4632a23 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/setup.py @@ -80,7 +80,6 @@ "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", @@ -91,7 +90,7 @@ ], platforms="Posix; MacOS X; Windows", packages=packages, - python_requires=">=3.9", + python_requires=">=3.10", install_requires=dependencies, extras_require=extras, include_package_data=True, diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.9.txt b/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.9.txt deleted file mode 100755 index 4fabf1676a51..000000000000 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.9.txt +++ /dev/null @@ -1,12 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file, -# pinning their versions to their lower bounds. -# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# then this file should have google-cloud-foo==1.14.0 -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py index 71d63642bf6e..a069b0cac511 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py @@ -14,12 +14,8 @@ # limitations under the License. # import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock +from unittest import mock +from unittest.mock import AsyncMock import grpc from grpc.experimental import aio @@ -1445,9 +1441,7 @@ async def test_list_buckets_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_buckets(request={}) ).pages: pages.append(page_) @@ -3617,9 +3611,7 @@ async def test__list_views_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client._list_views(request={}) ).pages: pages.append(page_) @@ -5052,9 +5044,7 @@ async def test__list_sinks_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client._list_sinks(request={}) ).pages: pages.append(page_) @@ -7559,9 +7549,7 @@ async def test__list_links_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client._list_links(request={}) ).pages: pages.append(page_) @@ -8383,9 +8371,7 @@ async def test__list_exclusions_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client._list_exclusions(request={}) ).pages: pages.append(page_) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py index e03a5e8bb8d2..e091184a3e02 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py @@ -14,12 +14,8 @@ # limitations under the License. # import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock +from unittest import mock +from unittest.mock import AsyncMock import grpc from grpc.experimental import aio @@ -1978,9 +1974,7 @@ async def test_list_log_entries_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_log_entries(request={}) ).pages: pages.append(page_) @@ -2334,9 +2328,7 @@ async def test_list_monitored_resource_descriptors_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_monitored_resource_descriptors(request={}) ).pages: pages.append(page_) @@ -2845,9 +2837,7 @@ async def test_list_logs_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_logs(request={}) ).pages: pages.append(page_) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py index e4c6d2122fec..ef477b2f063a 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py @@ -14,12 +14,8 @@ # limitations under the License. # import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock +from unittest import mock +from unittest.mock import AsyncMock import grpc from grpc.experimental import aio @@ -1445,9 +1441,7 @@ async def test__list_log_metrics_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client._list_log_metrics(request={}) ).pages: pages.append(page_) From 6dc61c299dc2517bec88026532f0f86ec43ed4f5 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 07:51:37 -0400 Subject: [PATCH 27/52] chore(gapic-generator): update goldens for redis --- .../redis/google/cloud/redis_v1/__init__.py | 19 +++---------------- .../integration/goldens/redis/noxfile.py | 1 - .../tests/integration/goldens/redis/setup.py | 3 +-- .../goldens/redis/testing/constraints-3.9.txt | 12 ------------ .../unit/gapic/redis_v1/test_cloud_redis.py | 12 +++--------- 5 files changed, 7 insertions(+), 40 deletions(-) delete mode 100755 packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.9.txt diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/__init__.py index c5182e2f8447..a17533fce850 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/__init__.py @@ -20,12 +20,7 @@ __version__ = package_version.__version__ -if sys.version_info >= (3, 8): # pragma: NO COVER - from importlib import metadata -else: # pragma: NO COVER - # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove - # this code path once we drop support for Python 3.7 - import importlib_metadata as metadata +from importlib import metadata from .services.cloud_redis import CloudRedisClient @@ -71,20 +66,12 @@ _py_version_str = sys.version.split()[0] _package_label = "google.cloud.redis_v1" - if sys.version_info < (3, 9): + if sys.version_info < (3, 10): warnings.warn("You are using a non-supported Python version " + f"({_py_version_str}). Google will not post any further " + f"updates to {_package_label} supporting this Python version. " + "Please upgrade to the latest Python version, or at " + - f"least to Python 3.9, and then update {_package_label}.", - FutureWarning) - if sys.version_info[:2] == (3, 9): - warnings.warn(f"You are using a Python version ({_py_version_str}) " + - f"which Google will stop supporting in {_package_label} in " + - "January 2026. Please " + - "upgrade to the latest Python version, or at " + - "least to Python 3.10, before then, and " + - f"then update {_package_label}.", + f"least to Python 3.10, and then update {_package_label}.", FutureWarning) def parse_version_to_tuple(version_string: str): diff --git a/packages/gapic-generator/tests/integration/goldens/redis/noxfile.py b/packages/gapic-generator/tests/integration/goldens/redis/noxfile.py index abaab5a4121d..8f69757517f1 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/noxfile.py @@ -32,7 +32,6 @@ LINT_PATHS.append("samples") ALL_PYTHON = [ - "3.9", "3.10", "3.11", "3.12", diff --git a/packages/gapic-generator/tests/integration/goldens/redis/setup.py b/packages/gapic-generator/tests/integration/goldens/redis/setup.py index e121207415e7..34c062d8462b 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/setup.py @@ -84,7 +84,6 @@ "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", @@ -95,7 +94,7 @@ ], platforms="Posix; MacOS X; Windows", packages=packages, - python_requires=">=3.9", + python_requires=">=3.10", install_requires=dependencies, extras_require=extras, include_package_data=True, diff --git a/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.9.txt b/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.9.txt deleted file mode 100755 index 4fabf1676a51..000000000000 --- a/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.9.txt +++ /dev/null @@ -1,12 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file, -# pinning their versions to their lower bounds. -# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# then this file should have google-cloud-foo==1.14.0 -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 diff --git a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py index 035e18dcd386..1856ce1728f0 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -14,12 +14,8 @@ # limitations under the License. # import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock +from unittest import mock +from unittest.mock import AsyncMock import grpc from grpc.experimental import aio @@ -1478,9 +1474,7 @@ async def test_list_instances_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_instances(request={}) ).pages: pages.append(page_) From fd96a8228de026e69fb5f02c24ea650b6a70571b Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 07:51:37 -0400 Subject: [PATCH 28/52] chore(gapic-generator): update goldens for redis_selective --- .../google/cloud/redis_v1/__init__.py | 19 +++---------------- .../goldens/redis_selective/noxfile.py | 1 - .../goldens/redis_selective/setup.py | 3 +-- .../testing/constraints-3.9.txt | 12 ------------ .../unit/gapic/redis_v1/test_cloud_redis.py | 12 +++--------- 5 files changed, 7 insertions(+), 40 deletions(-) delete mode 100755 packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.9.txt diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/__init__.py index 1f7bad3796c9..0586d7d5201e 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/__init__.py @@ -20,12 +20,7 @@ __version__ = package_version.__version__ -if sys.version_info >= (3, 8): # pragma: NO COVER - from importlib import metadata -else: # pragma: NO COVER - # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove - # this code path once we drop support for Python 3.7 - import importlib_metadata as metadata +from importlib import metadata from .services.cloud_redis import CloudRedisClient @@ -58,20 +53,12 @@ _py_version_str = sys.version.split()[0] _package_label = "google.cloud.redis_v1" - if sys.version_info < (3, 9): + if sys.version_info < (3, 10): warnings.warn("You are using a non-supported Python version " + f"({_py_version_str}). Google will not post any further " + f"updates to {_package_label} supporting this Python version. " + "Please upgrade to the latest Python version, or at " + - f"least to Python 3.9, and then update {_package_label}.", - FutureWarning) - if sys.version_info[:2] == (3, 9): - warnings.warn(f"You are using a Python version ({_py_version_str}) " + - f"which Google will stop supporting in {_package_label} in " + - "January 2026. Please " + - "upgrade to the latest Python version, or at " + - "least to Python 3.10, before then, and " + - f"then update {_package_label}.", + f"least to Python 3.10, and then update {_package_label}.", FutureWarning) def parse_version_to_tuple(version_string: str): diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/noxfile.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/noxfile.py index abaab5a4121d..8f69757517f1 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/noxfile.py @@ -32,7 +32,6 @@ LINT_PATHS.append("samples") ALL_PYTHON = [ - "3.9", "3.10", "3.11", "3.12", diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/setup.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/setup.py index e121207415e7..34c062d8462b 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/setup.py @@ -84,7 +84,6 @@ "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", @@ -95,7 +94,7 @@ ], platforms="Posix; MacOS X; Windows", packages=packages, - python_requires=">=3.9", + python_requires=">=3.10", install_requires=dependencies, extras_require=extras, include_package_data=True, diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.9.txt b/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.9.txt deleted file mode 100755 index 4fabf1676a51..000000000000 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.9.txt +++ /dev/null @@ -1,12 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file, -# pinning their versions to their lower bounds. -# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# then this file should have google-cloud-foo==1.14.0 -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py index 526046d104ec..0ae3649f7fda 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -14,12 +14,8 @@ # limitations under the License. # import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock +from unittest import mock +from unittest.mock import AsyncMock import grpc from grpc.experimental import aio @@ -1478,9 +1474,7 @@ async def test_list_instances_async_pages(): RuntimeError, ) pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( await client.list_instances(request={}) ).pages: pages.append(page_) From 486e4eea2beaa1974d9e3fec829bf26eff098c4f Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 08:35:40 -0400 Subject: [PATCH 29/52] chore(gapic-generator): remove leftover constraints file for redis_selective --- .../testing/constraints-3.9-async-rest.txt | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100755 packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.9-async-rest.txt diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.9-async-rest.txt b/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.9-async-rest.txt deleted file mode 100755 index 6b058713e3d3..000000000000 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.9-async-rest.txt +++ /dev/null @@ -1,12 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file, -# pinning their versions to their lower bounds. -# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# then this file should have google-cloud-foo==1.14.0 -google-api-core==2.21.0 -google-auth==2.35.0 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 From 43464e77e0326337571b79e3915738f1c45c85a8 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 08:36:23 -0400 Subject: [PATCH 30/52] fix(gapic-generator): handle empty constraints in noxfile template --- packages/gapic-generator/gapic/templates/noxfile.py.j2 | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/noxfile.py.j2 b/packages/gapic-generator/gapic/templates/noxfile.py.j2 index 244173b4b42d..f15cf897e639 100644 --- a/packages/gapic-generator/gapic/templates/noxfile.py.j2 +++ b/packages/gapic-generator/gapic/templates/noxfile.py.j2 @@ -493,7 +493,8 @@ def prerelease_deps(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) + if constraints_deps: + session.install(*constraints_deps) # Note: If a dependency is added to the `prerel_deps` list, # the `core_dependencies_from_source` list in the `core_deps_from_source` @@ -586,7 +587,8 @@ def core_deps_from_source(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) + if constraints_deps: + session.install(*constraints_deps) # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and # `grpcio-status` should be added to the list below so that they are installed from source, From 38160296cea15beef78e0cb8568c030c8798d40d Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 08:37:05 -0400 Subject: [PATCH 31/52] chore(gapic-generator): update noxfile in credentials golden --- .../tests/integration/goldens/credentials/noxfile.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py b/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py index 5d529145149f..4a80bbff927d 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py @@ -485,7 +485,8 @@ def prerelease_deps(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) + if constraints_deps: + session.install(*constraints_deps) # Note: If a dependency is added to the `prerel_deps` list, # the `core_dependencies_from_source` list in the `core_deps_from_source` @@ -578,7 +579,8 @@ def core_deps_from_source(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) + if constraints_deps: + session.install(*constraints_deps) # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and # `grpcio-status` should be added to the list below so that they are installed from source, From 25b4715f769c6c08c0e69d70df4424d3fbb3130a Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 08:37:05 -0400 Subject: [PATCH 32/52] chore(gapic-generator): update noxfile in eventarc golden --- .../tests/integration/goldens/eventarc/noxfile.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/noxfile.py b/packages/gapic-generator/tests/integration/goldens/eventarc/noxfile.py index 6d38b74914ff..85b491b22c9e 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/noxfile.py @@ -485,7 +485,8 @@ def prerelease_deps(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) + if constraints_deps: + session.install(*constraints_deps) # Note: If a dependency is added to the `prerel_deps` list, # the `core_dependencies_from_source` list in the `core_deps_from_source` @@ -578,7 +579,8 @@ def core_deps_from_source(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) + if constraints_deps: + session.install(*constraints_deps) # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and # `grpcio-status` should be added to the list below so that they are installed from source, From e5009471dad656945544ef31351ff283bed0f71b Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 08:37:06 -0400 Subject: [PATCH 33/52] chore(gapic-generator): update noxfile in logging golden --- .../tests/integration/goldens/logging/noxfile.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/noxfile.py b/packages/gapic-generator/tests/integration/goldens/logging/noxfile.py index e45a048b01af..40720f86d443 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/noxfile.py @@ -485,7 +485,8 @@ def prerelease_deps(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) + if constraints_deps: + session.install(*constraints_deps) # Note: If a dependency is added to the `prerel_deps` list, # the `core_dependencies_from_source` list in the `core_deps_from_source` @@ -578,7 +579,8 @@ def core_deps_from_source(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) + if constraints_deps: + session.install(*constraints_deps) # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and # `grpcio-status` should be added to the list below so that they are installed from source, From 22726f44aeb1891b2fa6e6b25134b3f12db20fe1 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 08:37:06 -0400 Subject: [PATCH 34/52] chore(gapic-generator): update noxfile in logging_internal golden --- .../tests/integration/goldens/logging_internal/noxfile.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/noxfile.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/noxfile.py index e45a048b01af..40720f86d443 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/noxfile.py @@ -485,7 +485,8 @@ def prerelease_deps(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) + if constraints_deps: + session.install(*constraints_deps) # Note: If a dependency is added to the `prerel_deps` list, # the `core_dependencies_from_source` list in the `core_deps_from_source` @@ -578,7 +579,8 @@ def core_deps_from_source(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) + if constraints_deps: + session.install(*constraints_deps) # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and # `grpcio-status` should be added to the list below so that they are installed from source, From af490d4e1e950001dac3d822a26653a995020be6 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 08:37:07 -0400 Subject: [PATCH 35/52] chore(gapic-generator): update noxfile in redis golden --- .../tests/integration/goldens/redis/noxfile.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/noxfile.py b/packages/gapic-generator/tests/integration/goldens/redis/noxfile.py index 8f69757517f1..e1158f47dad7 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/noxfile.py @@ -485,7 +485,8 @@ def prerelease_deps(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) + if constraints_deps: + session.install(*constraints_deps) # Note: If a dependency is added to the `prerel_deps` list, # the `core_dependencies_from_source` list in the `core_deps_from_source` @@ -578,7 +579,8 @@ def core_deps_from_source(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) + if constraints_deps: + session.install(*constraints_deps) # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and # `grpcio-status` should be added to the list below so that they are installed from source, From 75846ff829da5774a7e143318e3b6ccbcd41e269 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 08:37:07 -0400 Subject: [PATCH 36/52] chore(gapic-generator): update noxfile in redis_selective golden --- .../tests/integration/goldens/redis_selective/noxfile.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/noxfile.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/noxfile.py index 8f69757517f1..e1158f47dad7 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/noxfile.py @@ -485,7 +485,8 @@ def prerelease_deps(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) + if constraints_deps: + session.install(*constraints_deps) # Note: If a dependency is added to the `prerel_deps` list, # the `core_dependencies_from_source` list in the `core_deps_from_source` @@ -578,7 +579,8 @@ def core_deps_from_source(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) + if constraints_deps: + session.install(*constraints_deps) # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and # `grpcio-status` should be added to the list below so that they are installed from source, From 7b7de4f87d77073bac49d6bd2fcb952893d2f0d6 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 08:43:39 -0400 Subject: [PATCH 37/52] fix(gapic-generator): populate constraints files with versions in template --- .../gapic-generator/gapic/templates/noxfile.py.j2 | 6 ++---- .../gapic/templates/testing/_default_constraints.j2 | 12 ++++++------ 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/noxfile.py.j2 b/packages/gapic-generator/gapic/templates/noxfile.py.j2 index f15cf897e639..244173b4b42d 100644 --- a/packages/gapic-generator/gapic/templates/noxfile.py.j2 +++ b/packages/gapic-generator/gapic/templates/noxfile.py.j2 @@ -493,8 +493,7 @@ def prerelease_deps(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - if constraints_deps: - session.install(*constraints_deps) + session.install(*constraints_deps) # Note: If a dependency is added to the `prerel_deps` list, # the `core_dependencies_from_source` list in the `core_deps_from_source` @@ -587,8 +586,7 @@ def core_deps_from_source(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - if constraints_deps: - session.install(*constraints_deps) + session.install(*constraints_deps) # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and # `grpcio-status` should be added to the list below so that they are installed from source, diff --git a/packages/gapic-generator/gapic/templates/testing/_default_constraints.j2 b/packages/gapic-generator/gapic/templates/testing/_default_constraints.j2 index 85d819aaff23..a5e361c37f2e 100644 --- a/packages/gapic-generator/gapic/templates/testing/_default_constraints.j2 +++ b/packages/gapic-generator/gapic/templates/testing/_default_constraints.j2 @@ -1,18 +1,18 @@ {% from '_pypi_packages.j2' import pypi_packages %} # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography {% for package_tuple, package_info in pypi_packages.items() %} {# Quick check to make sure `package_info.package_name` is not the package being generated so we don't circularly include this package in its own constraints file. #} {% if api.naming.warehouse_package_name != package_info.package_name %} {% if api.requires_package(package_tuple) %} -{{ package_info.package_name }} +{{ package_info.package_name }}=={{ package_info.lower_bound }} {% endif %} {% endif %} {% endfor %} From 9ccb209ea1f4211dbc3d19382978c4ca30d12808 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 08:44:22 -0400 Subject: [PATCH 38/52] chore(gapic-generator): update goldens for credentials with versioned constraints --- .../tests/integration/goldens/credentials/noxfile.py | 6 ++---- .../goldens/credentials/testing/constraints-3.10.txt | 10 +++++----- .../goldens/credentials/testing/constraints-3.11.txt | 10 +++++----- .../goldens/credentials/testing/constraints-3.12.txt | 10 +++++----- 4 files changed, 17 insertions(+), 19 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py b/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py index 4a80bbff927d..5d529145149f 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py @@ -485,8 +485,7 @@ def prerelease_deps(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - if constraints_deps: - session.install(*constraints_deps) + session.install(*constraints_deps) # Note: If a dependency is added to the `prerel_deps` list, # the `core_dependencies_from_source` list in the `core_deps_from_source` @@ -579,8 +578,7 @@ def core_deps_from_source(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - if constraints_deps: - session.install(*constraints_deps) + session.install(*constraints_deps) # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and # `grpcio-status` should be added to the list below so that they are installed from source, diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.10.txt b/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.10.txt index 7599dea499ed..6ab3c3daf40e 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.10.txt +++ b/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.10.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.11.txt b/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.11.txt index 7599dea499ed..6ab3c3daf40e 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.11.txt +++ b/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.11.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.12.txt b/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.12.txt index 7599dea499ed..6ab3c3daf40e 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.12.txt +++ b/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.12.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography From 902da33102fd384364f46df83520431f69f9bf38 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 08:44:23 -0400 Subject: [PATCH 39/52] chore(gapic-generator): update goldens for eventarc with versioned constraints --- .../tests/integration/goldens/eventarc/noxfile.py | 6 ++---- .../goldens/eventarc/testing/constraints-3.10.txt | 12 ++++++------ .../goldens/eventarc/testing/constraints-3.11.txt | 12 ++++++------ .../goldens/eventarc/testing/constraints-3.12.txt | 12 ++++++------ 4 files changed, 20 insertions(+), 22 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/noxfile.py b/packages/gapic-generator/tests/integration/goldens/eventarc/noxfile.py index 85b491b22c9e..6d38b74914ff 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/noxfile.py @@ -485,8 +485,7 @@ def prerelease_deps(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - if constraints_deps: - session.install(*constraints_deps) + session.install(*constraints_deps) # Note: If a dependency is added to the `prerel_deps` list, # the `core_dependencies_from_source` list in the `core_deps_from_source` @@ -579,8 +578,7 @@ def core_deps_from_source(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - if constraints_deps: - session.install(*constraints_deps) + session.install(*constraints_deps) # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and # `grpcio-status` should be added to the list below so that they are installed from source, diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.10.txt b/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.10.txt index 1cd0c5a2c3d4..f30a91d003a7 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.10.txt +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.10.txt @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography -grpc-google-iam-v1 +grpc-google-iam-v1==0.14.0 diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.11.txt b/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.11.txt index 1cd0c5a2c3d4..f30a91d003a7 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.11.txt +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.11.txt @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography -grpc-google-iam-v1 +grpc-google-iam-v1==0.14.0 diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.12.txt b/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.12.txt index 1cd0c5a2c3d4..f30a91d003a7 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.12.txt +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.12.txt @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography -grpc-google-iam-v1 +grpc-google-iam-v1==0.14.0 From 645a7ff0abeeaee196b6827fd44de508536780c1 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 08:44:23 -0400 Subject: [PATCH 40/52] chore(gapic-generator): update goldens for logging with versioned constraints --- .../tests/integration/goldens/logging/noxfile.py | 6 ++---- .../goldens/logging/testing/constraints-3.10.txt | 10 +++++----- .../goldens/logging/testing/constraints-3.11.txt | 10 +++++----- .../goldens/logging/testing/constraints-3.12.txt | 10 +++++----- 4 files changed, 17 insertions(+), 19 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/logging/noxfile.py b/packages/gapic-generator/tests/integration/goldens/logging/noxfile.py index 40720f86d443..e45a048b01af 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/noxfile.py @@ -485,8 +485,7 @@ def prerelease_deps(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - if constraints_deps: - session.install(*constraints_deps) + session.install(*constraints_deps) # Note: If a dependency is added to the `prerel_deps` list, # the `core_dependencies_from_source` list in the `core_deps_from_source` @@ -579,8 +578,7 @@ def core_deps_from_source(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - if constraints_deps: - session.install(*constraints_deps) + session.install(*constraints_deps) # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and # `grpcio-status` should be added to the list below so that they are installed from source, diff --git a/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.10.txt b/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.10.txt index 7599dea499ed..6ab3c3daf40e 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.10.txt +++ b/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.10.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.11.txt b/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.11.txt index 7599dea499ed..6ab3c3daf40e 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.11.txt +++ b/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.11.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.12.txt b/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.12.txt index 7599dea499ed..6ab3c3daf40e 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.12.txt +++ b/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.12.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography From 2a7cd4ad04283efa8c14a3fc5d5c75eee32f6d2d Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 08:44:23 -0400 Subject: [PATCH 41/52] chore(gapic-generator): update goldens for logging_internal with versioned constraints --- .../integration/goldens/logging_internal/noxfile.py | 6 ++---- .../logging_internal/testing/constraints-3.10.txt | 10 +++++----- .../logging_internal/testing/constraints-3.11.txt | 10 +++++----- .../logging_internal/testing/constraints-3.12.txt | 10 +++++----- 4 files changed, 17 insertions(+), 19 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/noxfile.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/noxfile.py index 40720f86d443..e45a048b01af 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/noxfile.py @@ -485,8 +485,7 @@ def prerelease_deps(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - if constraints_deps: - session.install(*constraints_deps) + session.install(*constraints_deps) # Note: If a dependency is added to the `prerel_deps` list, # the `core_dependencies_from_source` list in the `core_deps_from_source` @@ -579,8 +578,7 @@ def core_deps_from_source(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - if constraints_deps: - session.install(*constraints_deps) + session.install(*constraints_deps) # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and # `grpcio-status` should be added to the list below so that they are installed from source, diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.10.txt b/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.10.txt index 7599dea499ed..6ab3c3daf40e 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.10.txt +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.10.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.11.txt b/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.11.txt index 7599dea499ed..6ab3c3daf40e 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.11.txt +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.11.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.12.txt b/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.12.txt index 7599dea499ed..6ab3c3daf40e 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.12.txt +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.12.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography From c3e96a6f40883eb0559737310e5fdd8f9e2a8665 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 08:44:24 -0400 Subject: [PATCH 42/52] chore(gapic-generator): update goldens for redis with versioned constraints --- .../tests/integration/goldens/redis/noxfile.py | 6 ++---- .../goldens/redis/testing/constraints-3.10.txt | 10 +++++----- .../goldens/redis/testing/constraints-3.11.txt | 10 +++++----- .../goldens/redis/testing/constraints-3.12.txt | 10 +++++----- 4 files changed, 17 insertions(+), 19 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/redis/noxfile.py b/packages/gapic-generator/tests/integration/goldens/redis/noxfile.py index e1158f47dad7..8f69757517f1 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/noxfile.py @@ -485,8 +485,7 @@ def prerelease_deps(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - if constraints_deps: - session.install(*constraints_deps) + session.install(*constraints_deps) # Note: If a dependency is added to the `prerel_deps` list, # the `core_dependencies_from_source` list in the `core_deps_from_source` @@ -579,8 +578,7 @@ def core_deps_from_source(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - if constraints_deps: - session.install(*constraints_deps) + session.install(*constraints_deps) # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and # `grpcio-status` should be added to the list below so that they are installed from source, diff --git a/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.10.txt b/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.10.txt index 7599dea499ed..6ab3c3daf40e 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.10.txt +++ b/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.10.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.11.txt b/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.11.txt index 7599dea499ed..6ab3c3daf40e 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.11.txt +++ b/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.11.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.12.txt b/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.12.txt index 7599dea499ed..6ab3c3daf40e 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.12.txt +++ b/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.12.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography From 5f1b6dcbf2e1f9a57b390702ac97d29397a8ac04 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 08:44:24 -0400 Subject: [PATCH 43/52] chore(gapic-generator): update goldens for redis_selective with versioned constraints --- .../integration/goldens/redis_selective/noxfile.py | 6 ++---- .../redis_selective/testing/constraints-3.10.txt | 10 +++++----- .../redis_selective/testing/constraints-3.11.txt | 10 +++++----- .../redis_selective/testing/constraints-3.12.txt | 10 +++++----- 4 files changed, 17 insertions(+), 19 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/noxfile.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/noxfile.py index e1158f47dad7..8f69757517f1 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/noxfile.py @@ -485,8 +485,7 @@ def prerelease_deps(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - if constraints_deps: - session.install(*constraints_deps) + session.install(*constraints_deps) # Note: If a dependency is added to the `prerel_deps` list, # the `core_dependencies_from_source` list in the `core_deps_from_source` @@ -579,8 +578,7 @@ def core_deps_from_source(session, protobuf_implementation): ] # Install dependencies specified in `testing/constraints-X.txt`. - if constraints_deps: - session.install(*constraints_deps) + session.install(*constraints_deps) # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and # `grpcio-status` should be added to the list below so that they are installed from source, diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.10.txt b/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.10.txt index 7599dea499ed..6ab3c3daf40e 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.10.txt +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.10.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.11.txt b/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.11.txt index 7599dea499ed..6ab3c3daf40e 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.11.txt +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.11.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.12.txt b/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.12.txt index 7599dea499ed..6ab3c3daf40e 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.12.txt +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.12.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 # cryptography is a direct dependency of google-auth cryptography From 12332fa6415036b0916191bd2c61db8d4b825a15 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 09:11:27 -0400 Subject: [PATCH 44/52] fix(gapic-generator): update constraints templates for Python 3.10 --- .../templates/testing/_default_constraints.j2 | 12 +++++----- .../constraints-3.10-async-rest.txt.j2 | 24 +++++++++++++++++++ .../templates/testing/constraints-3.10.txt.j2 | 24 +++++++++++++++---- 3 files changed, 50 insertions(+), 10 deletions(-) create mode 100644 packages/gapic-generator/gapic/templates/testing/constraints-3.10-async-rest.txt.j2 diff --git a/packages/gapic-generator/gapic/templates/testing/_default_constraints.j2 b/packages/gapic-generator/gapic/templates/testing/_default_constraints.j2 index a5e361c37f2e..85d819aaff23 100644 --- a/packages/gapic-generator/gapic/templates/testing/_default_constraints.j2 +++ b/packages/gapic-generator/gapic/templates/testing/_default_constraints.j2 @@ -1,18 +1,18 @@ {% from '_pypi_packages.j2' import pypi_packages %} # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 +google-api-core +google-auth +grpcio +proto-plus +protobuf # cryptography is a direct dependency of google-auth cryptography {% for package_tuple, package_info in pypi_packages.items() %} {# Quick check to make sure `package_info.package_name` is not the package being generated so we don't circularly include this package in its own constraints file. #} {% if api.naming.warehouse_package_name != package_info.package_name %} {% if api.requires_package(package_tuple) %} -{{ package_info.package_name }}=={{ package_info.lower_bound }} +{{ package_info.package_name }} {% endif %} {% endif %} {% endfor %} diff --git a/packages/gapic-generator/gapic/templates/testing/constraints-3.10-async-rest.txt.j2 b/packages/gapic-generator/gapic/templates/testing/constraints-3.10-async-rest.txt.j2 new file mode 100644 index 000000000000..3a1222949a04 --- /dev/null +++ b/packages/gapic-generator/gapic/templates/testing/constraints-3.10-async-rest.txt.j2 @@ -0,0 +1,24 @@ +{% set rest_async_io_enabled = api.all_library_settings[api.naming.proto_package].python_settings.experimental_features.rest_async_io_enabled %} +{% if rest_async_io_enabled %} +# -*- coding: utf-8 -*- +{% from '_pypi_packages.j2' import pypi_packages %} +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file, +# pinning their versions to their lower bounds. +# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# then this file should have google-cloud-foo==1.14.0 +google-api-core==2.21.0 +google-auth==2.35.0 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 +{% for package_tuple, package_info in pypi_packages.items() %} +{# Quick check to make sure `package_info.package_name` is not the package being generated so we don't circularly include this package in its own constraints file. #} +{% if api.naming.warehouse_package_name != package_info.package_name %} +{% if api.requires_package(package_tuple) %} +{{ package_info.package_name }}=={{ package_info.lower_bound }} +{% endif %} +{% endif %} +{% endfor %} +{% endif %} diff --git a/packages/gapic-generator/gapic/templates/testing/constraints-3.10.txt.j2 b/packages/gapic-generator/gapic/templates/testing/constraints-3.10.txt.j2 index e0f6dc759047..eb8dc323f481 100644 --- a/packages/gapic-generator/gapic/templates/testing/constraints-3.10.txt.j2 +++ b/packages/gapic-generator/gapic/templates/testing/constraints-3.10.txt.j2 @@ -1,4 +1,20 @@ -# -*- coding: utf-8 -*- -{% block constraints %} -{% include "testing/_default_constraints.j2" %} -{% endblock %} \ No newline at end of file +{% from '_pypi_packages.j2' import pypi_packages %} +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file, +# pinning their versions to their lower bounds. +# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# then this file should have google-cloud-foo==1.14.0 +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 +{% for package_tuple, package_info in pypi_packages.items() %} +{# Quick check to make sure `package_info.package_name` is not the package being generated so we don't circularly include this package in its own constraints file. #} +{% if api.naming.warehouse_package_name != package_info.package_name %} +{% if api.requires_package(package_tuple) %} +{{ package_info.package_name }}=={{ package_info.lower_bound }} +{% endif %} +{% endif %} +{% endfor %} \ No newline at end of file From d44cbe608da3a3e346fa400f0cbdbabe3f2fe564 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 09:11:29 -0400 Subject: [PATCH 45/52] chore(gapic-generator): update goldens for Python 3.10 constraints --- .../asset/testing/constraints-3.10.txt | 27 ++++++++++--------- .../credentials/testing/constraints-3.10.txt | 11 ++++---- .../credentials/testing/constraints-3.11.txt | 10 +++---- .../credentials/testing/constraints-3.12.txt | 10 +++---- .../eventarc/testing/constraints-3.10.txt | 11 ++++---- .../eventarc/testing/constraints-3.11.txt | 12 ++++----- .../eventarc/testing/constraints-3.12.txt | 12 ++++----- .../logging/testing/constraints-3.10.txt | 11 ++++---- .../logging/testing/constraints-3.11.txt | 10 +++---- .../logging/testing/constraints-3.12.txt | 10 +++---- .../testing/constraints-3.10.txt | 11 ++++---- .../testing/constraints-3.11.txt | 10 +++---- .../testing/constraints-3.12.txt | 10 +++---- ...st.txt => constraints-3.10-async-rest.txt} | 0 .../redis/testing/constraints-3.10.txt | 11 ++++---- .../redis/testing/constraints-3.11.txt | 10 +++---- .../redis/testing/constraints-3.12.txt | 10 +++---- .../testing/constraints-3.10-async-rest.txt | 12 +++++++++ .../testing/constraints-3.10.txt | 11 ++++---- .../testing/constraints-3.11.txt | 10 +++---- .../testing/constraints-3.12.txt | 10 +++---- 21 files changed, 124 insertions(+), 105 deletions(-) rename packages/gapic-generator/tests/integration/goldens/redis/testing/{constraints-3.9-async-rest.txt => constraints-3.10-async-rest.txt} (100%) create mode 100755 packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.10-async-rest.txt diff --git a/packages/gapic-generator/tests/integration/goldens/asset/testing/constraints-3.10.txt b/packages/gapic-generator/tests/integration/goldens/asset/testing/constraints-3.10.txt index c5602c5029bf..88ca48cac49d 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/testing/constraints-3.10.txt +++ b/packages/gapic-generator/tests/integration/goldens/asset/testing/constraints-3.10.txt @@ -1,13 +1,14 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -google-auth -grpcio -proto-plus -protobuf -# cryptography is a direct dependency of google-auth -cryptography -google-cloud-access-context-manager -google-cloud-os-config -grpc-google-iam-v1 +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file, +# pinning their versions to their lower bounds. +# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# then this file should have google-cloud-foo==1.14.0 +google-api-core==2.17.1 +google-auth==2.14.1 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 +google-cloud-access-context-manager==0.2.0 +google-cloud-os-config==1.13.0 +grpc-google-iam-v1==0.14.0 diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.10.txt b/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.10.txt index 6ab3c3daf40e..bac7ba85b4ee 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.10.txt +++ b/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.10.txt @@ -1,10 +1,11 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file, +# pinning their versions to their lower bounds. +# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# then this file should have google-cloud-foo==1.14.0 google-api-core==2.17.1 google-auth==2.14.1 grpcio==1.44.0 proto-plus==1.22.3 protobuf==4.25.8 -# cryptography is a direct dependency of google-auth -cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.11.txt b/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.11.txt index 6ab3c3daf40e..7599dea499ed 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.11.txt +++ b/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.11.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 +google-api-core +google-auth +grpcio +proto-plus +protobuf # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.12.txt b/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.12.txt index 6ab3c3daf40e..7599dea499ed 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.12.txt +++ b/packages/gapic-generator/tests/integration/goldens/credentials/testing/constraints-3.12.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 +google-api-core +google-auth +grpcio +proto-plus +protobuf # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.10.txt b/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.10.txt index f30a91d003a7..a92801e1c8e2 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.10.txt +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.10.txt @@ -1,11 +1,12 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file, +# pinning their versions to their lower bounds. +# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# then this file should have google-cloud-foo==1.14.0 google-api-core==2.17.1 google-auth==2.14.1 grpcio==1.44.0 proto-plus==1.22.3 protobuf==4.25.8 -# cryptography is a direct dependency of google-auth -cryptography grpc-google-iam-v1==0.14.0 diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.11.txt b/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.11.txt index f30a91d003a7..1cd0c5a2c3d4 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.11.txt +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.11.txt @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 +google-api-core +google-auth +grpcio +proto-plus +protobuf # cryptography is a direct dependency of google-auth cryptography -grpc-google-iam-v1==0.14.0 +grpc-google-iam-v1 diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.12.txt b/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.12.txt index f30a91d003a7..1cd0c5a2c3d4 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.12.txt +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/testing/constraints-3.12.txt @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 +google-api-core +google-auth +grpcio +proto-plus +protobuf # cryptography is a direct dependency of google-auth cryptography -grpc-google-iam-v1==0.14.0 +grpc-google-iam-v1 diff --git a/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.10.txt b/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.10.txt index 6ab3c3daf40e..bac7ba85b4ee 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.10.txt +++ b/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.10.txt @@ -1,10 +1,11 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file, +# pinning their versions to their lower bounds. +# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# then this file should have google-cloud-foo==1.14.0 google-api-core==2.17.1 google-auth==2.14.1 grpcio==1.44.0 proto-plus==1.22.3 protobuf==4.25.8 -# cryptography is a direct dependency of google-auth -cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.11.txt b/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.11.txt index 6ab3c3daf40e..7599dea499ed 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.11.txt +++ b/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.11.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 +google-api-core +google-auth +grpcio +proto-plus +protobuf # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.12.txt b/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.12.txt index 6ab3c3daf40e..7599dea499ed 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.12.txt +++ b/packages/gapic-generator/tests/integration/goldens/logging/testing/constraints-3.12.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 +google-api-core +google-auth +grpcio +proto-plus +protobuf # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.10.txt b/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.10.txt index 6ab3c3daf40e..bac7ba85b4ee 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.10.txt +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.10.txt @@ -1,10 +1,11 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file, +# pinning their versions to their lower bounds. +# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# then this file should have google-cloud-foo==1.14.0 google-api-core==2.17.1 google-auth==2.14.1 grpcio==1.44.0 proto-plus==1.22.3 protobuf==4.25.8 -# cryptography is a direct dependency of google-auth -cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.11.txt b/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.11.txt index 6ab3c3daf40e..7599dea499ed 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.11.txt +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.11.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 +google-api-core +google-auth +grpcio +proto-plus +protobuf # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.12.txt b/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.12.txt index 6ab3c3daf40e..7599dea499ed 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.12.txt +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/testing/constraints-3.12.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 +google-api-core +google-auth +grpcio +proto-plus +protobuf # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.9-async-rest.txt b/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.10-async-rest.txt similarity index 100% rename from packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.9-async-rest.txt rename to packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.10-async-rest.txt diff --git a/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.10.txt b/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.10.txt index 6ab3c3daf40e..bac7ba85b4ee 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.10.txt +++ b/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.10.txt @@ -1,10 +1,11 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file, +# pinning their versions to their lower bounds. +# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# then this file should have google-cloud-foo==1.14.0 google-api-core==2.17.1 google-auth==2.14.1 grpcio==1.44.0 proto-plus==1.22.3 protobuf==4.25.8 -# cryptography is a direct dependency of google-auth -cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.11.txt b/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.11.txt index 6ab3c3daf40e..7599dea499ed 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.11.txt +++ b/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.11.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 +google-api-core +google-auth +grpcio +proto-plus +protobuf # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.12.txt b/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.12.txt index 6ab3c3daf40e..7599dea499ed 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.12.txt +++ b/packages/gapic-generator/tests/integration/goldens/redis/testing/constraints-3.12.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 +google-api-core +google-auth +grpcio +proto-plus +protobuf # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.10-async-rest.txt b/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.10-async-rest.txt new file mode 100755 index 000000000000..6b058713e3d3 --- /dev/null +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.10-async-rest.txt @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file, +# pinning their versions to their lower bounds. +# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# then this file should have google-cloud-foo==1.14.0 +google-api-core==2.21.0 +google-auth==2.35.0 +grpcio==1.44.0 +proto-plus==1.22.3 +protobuf==4.25.8 diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.10.txt b/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.10.txt index 6ab3c3daf40e..bac7ba85b4ee 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.10.txt +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.10.txt @@ -1,10 +1,11 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file, +# pinning their versions to their lower bounds. +# For example, if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# then this file should have google-cloud-foo==1.14.0 google-api-core==2.17.1 google-auth==2.14.1 grpcio==1.44.0 proto-plus==1.22.3 protobuf==4.25.8 -# cryptography is a direct dependency of google-auth -cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.11.txt b/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.11.txt index 6ab3c3daf40e..7599dea499ed 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.11.txt +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.11.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 +google-api-core +google-auth +grpcio +proto-plus +protobuf # cryptography is a direct dependency of google-auth cryptography diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.12.txt b/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.12.txt index 6ab3c3daf40e..7599dea499ed 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.12.txt +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/testing/constraints-3.12.txt @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # This constraints file is required for unit tests. # List all library dependencies and extras in this file. -google-api-core==2.17.1 -google-auth==2.14.1 -grpcio==1.44.0 -proto-plus==1.22.3 -protobuf==4.25.8 +google-api-core +google-auth +grpcio +proto-plus +protobuf # cryptography is a direct dependency of google-auth cryptography From 1a68d5f880fe6aa95d8557d2208b5e37c75e0b84 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 09:20:51 -0400 Subject: [PATCH 46/52] chore(gapic-generator): format credentials golden files --- .../goldens/credentials/docs/conf.py | 12 +- .../google/iam/credentials/__init__.py | 48 +- .../google/iam/credentials_v1/__init__.py | 113 +- .../services/iam_credentials/__init__.py | 6 +- .../services/iam_credentials/async_client.py | 276 +- .../services/iam_credentials/client.py | 425 ++- .../iam_credentials/transports/__init__.py | 20 +- .../iam_credentials/transports/base.py | 141 +- .../iam_credentials/transports/grpc.py | 146 +- .../transports/grpc_asyncio.py | 157 +- .../iam_credentials/transports/rest.py | 625 ++-- .../iam_credentials/transports/rest_base.py | 198 +- .../iam/credentials_v1/types/__init__.py | 16 +- .../google/iam/credentials_v1/types/common.py | 22 +- .../credentials_v1/types/iamcredentials.py | 6 +- .../goldens/credentials/noxfile.py | 28 +- ...credentials_generate_access_token_async.py | 3 +- ..._credentials_generate_access_token_sync.py | 3 +- ...iam_credentials_generate_id_token_async.py | 1 + ..._iam_credentials_generate_id_token_sync.py | 1 + ...nerated_iam_credentials_sign_blob_async.py | 3 +- ...enerated_iam_credentials_sign_blob_sync.py | 3 +- ...enerated_iam_credentials_sign_jwt_async.py | 1 + ...generated_iam_credentials_sign_jwt_sync.py | 1 + .../integration/goldens/credentials/setup.py | 11 +- .../goldens/credentials/tests/__init__.py | 1 - .../credentials/tests/unit/__init__.py | 1 - .../credentials/tests/unit/gapic/__init__.py | 1 - .../unit/gapic/credentials_v1/__init__.py | 1 - .../credentials_v1/test_iam_credentials.py | 2634 +++++++++++------ 30 files changed, 3016 insertions(+), 1888 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/docs/conf.py b/packages/gapic-generator/tests/integration/goldens/credentials/docs/conf.py index b931406b0132..a6be00cae63c 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/docs/conf.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/docs/conf.py @@ -28,7 +28,6 @@ import os import shlex import sys -import logging from typing import Any # If extensions (or modules to document with autodoc) are in another directory, @@ -83,9 +82,9 @@ root_doc = "index" # General information about the project. -project = u"google-iam-credentials" -copyright = u"2025, Google, LLC" -author = u"Google APIs" +project = "google-iam-credentials" +copyright = "2025, Google, LLC" +author = "Google APIs" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -285,7 +284,7 @@ ( root_doc, "google-iam-credentials.tex", - u"google-iam-credentials Documentation", + "google-iam-credentials Documentation", author, "manual", ) @@ -386,6 +385,7 @@ napoleon_use_param = True napoleon_use_rtype = True + # Setup for sphinx behaviors such as warning filters. class UnexpectedUnindentFilter(logging.Filter): """Filter out warnings about unexpected unindentation following bullet lists.""" @@ -413,5 +413,5 @@ def setup(app: Any) -> None: """ # Sphinx's logger is hierarchical. Adding a filter to the # root 'sphinx' logger will catch warnings from all sub-loggers. - logger = logging.getLogger('sphinx') + logger = logging.getLogger("sphinx") logger.addFilter(UnexpectedUnindentFilter()) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials/__init__.py index 9c0382dd3319..1196554e01ee 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials/__init__.py @@ -18,26 +18,32 @@ __version__ = package_version.__version__ -from google.iam.credentials_v1.services.iam_credentials.client import IAMCredentialsClient -from google.iam.credentials_v1.services.iam_credentials.async_client import IAMCredentialsAsyncClient - -from google.iam.credentials_v1.types.common import GenerateAccessTokenRequest -from google.iam.credentials_v1.types.common import GenerateAccessTokenResponse -from google.iam.credentials_v1.types.common import GenerateIdTokenRequest -from google.iam.credentials_v1.types.common import GenerateIdTokenResponse -from google.iam.credentials_v1.types.common import SignBlobRequest -from google.iam.credentials_v1.types.common import SignBlobResponse -from google.iam.credentials_v1.types.common import SignJwtRequest -from google.iam.credentials_v1.types.common import SignJwtResponse +from google.iam.credentials_v1.services.iam_credentials.async_client import ( + IAMCredentialsAsyncClient, +) +from google.iam.credentials_v1.services.iam_credentials.client import ( + IAMCredentialsClient, +) +from google.iam.credentials_v1.types.common import ( + GenerateAccessTokenRequest, + GenerateAccessTokenResponse, + GenerateIdTokenRequest, + GenerateIdTokenResponse, + SignBlobRequest, + SignBlobResponse, + SignJwtRequest, + SignJwtResponse, +) -__all__ = ('IAMCredentialsClient', - 'IAMCredentialsAsyncClient', - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'GenerateIdTokenRequest', - 'GenerateIdTokenResponse', - 'SignBlobRequest', - 'SignBlobResponse', - 'SignJwtRequest', - 'SignJwtResponse', +__all__ = ( + "IAMCredentialsClient", + "IAMCredentialsAsyncClient", + "GenerateAccessTokenRequest", + "GenerateAccessTokenResponse", + "GenerateIdTokenRequest", + "GenerateIdTokenResponse", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", ) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/__init__.py index 44c85c1895f8..2e45666bac2a 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/__init__.py @@ -13,47 +13,50 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from google.iam.credentials_v1 import gapic_version as package_version +import sys import google.api_core as api_core -import sys + +from google.iam.credentials_v1 import gapic_version as package_version __version__ = package_version.__version__ from importlib import metadata +from .services.iam_credentials import IAMCredentialsAsyncClient, IAMCredentialsClient +from .types.common import ( + GenerateAccessTokenRequest, + GenerateAccessTokenResponse, + GenerateIdTokenRequest, + GenerateIdTokenResponse, + SignBlobRequest, + SignBlobResponse, + SignJwtRequest, + SignJwtResponse, +) -from .services.iam_credentials import IAMCredentialsClient -from .services.iam_credentials import IAMCredentialsAsyncClient - -from .types.common import GenerateAccessTokenRequest -from .types.common import GenerateAccessTokenResponse -from .types.common import GenerateIdTokenRequest -from .types.common import GenerateIdTokenResponse -from .types.common import SignBlobRequest -from .types.common import SignBlobResponse -from .types.common import SignJwtRequest -from .types.common import SignJwtResponse - -if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER - api_core.check_python_version("google.iam.credentials_v1") # type: ignore - api_core.check_dependency_versions("google.iam.credentials_v1") # type: ignore -else: # pragma: NO COVER +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.iam.credentials_v1") # type: ignore + api_core.check_dependency_versions("google.iam.credentials_v1") # type: ignore +else: # pragma: NO COVER # An older version of api_core is installed which does not define the # functions above. We do equivalent checks manually. try: import warnings - import sys _py_version_str = sys.version.split()[0] _package_label = "google.iam.credentials_v1" if sys.version_info < (3, 10): - warnings.warn("You are using a non-supported Python version " + - f"({_py_version_str}). Google will not post any further " + - f"updates to {_package_label} supporting this Python version. " + - "Please upgrade to the latest Python version, or at " + - f"least to Python 3.10, and then update {_package_label}.", - FutureWarning) + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.10, and then update {_package_label}.", + FutureWarning, + ) def parse_version_to_tuple(version_string: str): """Safely converts a semantic version string to a comparable tuple of integers. @@ -91,35 +94,39 @@ def _get_version(dependency_name): _recommendation = " (we recommend 6.x)" (_version_used, _version_used_string) = _get_version(_dependency_package) if _version_used and _version_used < _next_supported_version_tuple: - warnings.warn(f"Package {_package_label} depends on " + - f"{_dependency_package}, currently installed at version " + - f"{_version_used_string}. Future updates to " + - f"{_package_label} will require {_dependency_package} at " + - f"version {_next_supported_version} or higher{_recommendation}." + - " Please ensure " + - "that either (a) your Python environment doesn't pin the " + - f"version of {_dependency_package}, so that updates to " + - f"{_package_label} can require the higher version, or " + - "(b) you manually update your Python environment to use at " + - f"least version {_next_supported_version} of " + - f"{_dependency_package}.", - FutureWarning) + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) except Exception: - warnings.warn("Could not determine the version of Python " + - "currently being used. To continue receiving " + - "updates for {_package_label}, ensure you are " + - "using a supported version of Python; see " + - "https://devguide.python.org/versions/") + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) __all__ = ( - 'IAMCredentialsAsyncClient', -'GenerateAccessTokenRequest', -'GenerateAccessTokenResponse', -'GenerateIdTokenRequest', -'GenerateIdTokenResponse', -'IAMCredentialsClient', -'SignBlobRequest', -'SignBlobResponse', -'SignJwtRequest', -'SignJwtResponse', + "IAMCredentialsAsyncClient", + "GenerateAccessTokenRequest", + "GenerateAccessTokenResponse", + "GenerateIdTokenRequest", + "GenerateIdTokenResponse", + "IAMCredentialsClient", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", ) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/__init__.py index 988290706545..36b57fe4c555 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import IAMCredentialsClient from .async_client import IAMCredentialsAsyncClient +from .client import IAMCredentialsClient __all__ = ( - 'IAMCredentialsClient', - 'IAMCredentialsAsyncClient', + "IAMCredentialsClient", + "IAMCredentialsAsyncClient", ) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/async_client.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/async_client.py index 7852bfe5c199..9408ee9cb76a 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/async_client.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/async_client.py @@ -14,41 +14,55 @@ # limitations under the License. # import logging as std_logging -from collections import OrderedDict import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.iam.credentials_v1 import gapic_version as package_version +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) -from google.api_core.client_options import ClientOptions +import google.protobuf from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +from google.iam.credentials_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore -from google.iam.credentials_v1.types import common import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from .transports.base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport + +from google.iam.credentials_v1.types import common + from .client import IAMCredentialsClient +from .transports.base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport +from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) + class IAMCredentialsAsyncClient: """A service account is a special type of Google account that belongs to your application or a virtual machine (VM), instead @@ -72,17 +86,33 @@ class IAMCredentialsAsyncClient: _DEFAULT_UNIVERSE = IAMCredentialsClient._DEFAULT_UNIVERSE service_account_path = staticmethod(IAMCredentialsClient.service_account_path) - parse_service_account_path = staticmethod(IAMCredentialsClient.parse_service_account_path) - common_billing_account_path = staticmethod(IAMCredentialsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(IAMCredentialsClient.parse_common_billing_account_path) + parse_service_account_path = staticmethod( + IAMCredentialsClient.parse_service_account_path + ) + common_billing_account_path = staticmethod( + IAMCredentialsClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + IAMCredentialsClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(IAMCredentialsClient.common_folder_path) - parse_common_folder_path = staticmethod(IAMCredentialsClient.parse_common_folder_path) - common_organization_path = staticmethod(IAMCredentialsClient.common_organization_path) - parse_common_organization_path = staticmethod(IAMCredentialsClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + IAMCredentialsClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + IAMCredentialsClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + IAMCredentialsClient.parse_common_organization_path + ) common_project_path = staticmethod(IAMCredentialsClient.common_project_path) - parse_common_project_path = staticmethod(IAMCredentialsClient.parse_common_project_path) + parse_common_project_path = staticmethod( + IAMCredentialsClient.parse_common_project_path + ) common_location_path = staticmethod(IAMCredentialsClient.common_location_path) - parse_common_location_path = staticmethod(IAMCredentialsClient.parse_common_location_path) + parse_common_location_path = staticmethod( + IAMCredentialsClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -124,7 +154,9 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -187,12 +219,16 @@ def universe_domain(self) -> str: get_transport_class = IAMCredentialsClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the iam credentials async client. Args: @@ -250,34 +286,42 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.iam.credentials_v1.IAMCredentialsAsyncClient`.", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { "serviceName": "google.iam.credentials.v1.IAMCredentials", "credentialsType": None, - } + }, ) - async def generate_access_token(self, - request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - scope: Optional[MutableSequence[str]] = None, - lifetime: Optional[duration_pb2.Duration] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateAccessTokenResponse: + async def generate_access_token( + self, + request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + scope: Optional[MutableSequence[str]] = None, + lifetime: Optional[duration_pb2.Duration] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateAccessTokenResponse: r"""Generates an OAuth 2.0 access token for a service account. @@ -378,10 +422,14 @@ async def sample_generate_access_token(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, scope, lifetime] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -401,14 +449,14 @@ async def sample_generate_access_token(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.generate_access_token] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.generate_access_token + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -425,17 +473,18 @@ async def sample_generate_access_token(): # Done; return the response. return response - async def generate_id_token(self, - request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - audience: Optional[str] = None, - include_email: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateIdTokenResponse: + async def generate_id_token( + self, + request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + audience: Optional[str] = None, + include_email: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateIdTokenResponse: r"""Generates an OpenID Connect ID token for a service account. @@ -530,10 +579,14 @@ async def sample_generate_id_token(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, audience, include_email] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -553,14 +606,14 @@ async def sample_generate_id_token(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.generate_id_token] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.generate_id_token + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -577,16 +630,17 @@ async def sample_generate_id_token(): # Done; return the response. return response - async def sign_blob(self, - request: Optional[Union[common.SignBlobRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - payload: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignBlobResponse: + async def sign_blob( + self, + request: Optional[Union[common.SignBlobRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignBlobResponse: r"""Signs a blob using a service account's system-managed private key. @@ -670,10 +724,14 @@ async def sample_sign_blob(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, payload] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -691,14 +749,14 @@ async def sample_sign_blob(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.sign_blob] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.sign_blob + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -715,16 +773,17 @@ async def sample_sign_blob(): # Done; return the response. return response - async def sign_jwt(self, - request: Optional[Union[common.SignJwtRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - payload: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignJwtResponse: + async def sign_jwt( + self, + request: Optional[Union[common.SignJwtRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignJwtResponse: r"""Signs a JWT using a service account's system-managed private key. @@ -811,10 +870,14 @@ async def sample_sign_jwt(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, payload] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -837,9 +900,7 @@ async def sample_sign_jwt(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -862,12 +923,13 @@ async def __aenter__(self) -> "IAMCredentialsAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "IAMCredentialsAsyncClient", -) +__all__ = ("IAMCredentialsAsyncClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py index c55d4a2a44bb..b0e8785d118d 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py @@ -13,27 +13,39 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from collections import OrderedDict -from http import HTTPStatus import json import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) -from google.iam.credentials_v1 import gapic_version as package_version - +import google.protobuf from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.iam.credentials_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -42,16 +54,19 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) -from google.iam.credentials_v1.types import common import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from .transports.base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO + +from google.iam.credentials_v1.types import common + +from .transports.base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport from .transports.grpc import IAMCredentialsGrpcTransport from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport from .transports.rest import IAMCredentialsRestTransport @@ -64,14 +79,16 @@ class IAMCredentialsClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[IAMCredentialsTransport]] _transport_registry["grpc"] = IAMCredentialsGrpcTransport _transport_registry["grpc_asyncio"] = IAMCredentialsGrpcAsyncIOTransport _transport_registry["rest"] = IAMCredentialsRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[IAMCredentialsTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[IAMCredentialsTransport]: """Returns an appropriate transport class. Args: @@ -157,14 +174,16 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -203,8 +222,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: IAMCredentialsClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -221,73 +239,106 @@ def transport(self) -> IAMCredentialsTransport: return self._transport @staticmethod - def service_account_path(project: str,service_account: str,) -> str: + def service_account_path( + project: str, + service_account: str, + ) -> str: """Returns a fully-qualified service_account string.""" - return "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) + return "projects/{project}/serviceAccounts/{service_account}".format( + project=project, + service_account=service_account, + ) @staticmethod - def parse_service_account_path(path: str) -> Dict[str,str]: + def parse_service_account_path(path: str) -> Dict[str, str]: """Parses a service_account path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + def common_billing_account_path( + billing_account: str, + ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path(folder: str, ) -> str: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path(organization: str, ) -> str: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path(project: str, ) -> str: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str, ) -> str: + def common_location_path( + project: str, + location: str, + ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -319,14 +370,18 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = IAMCredentialsClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -339,7 +394,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -364,7 +421,9 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -387,7 +446,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: """Return the API endpoint used by the client. Args: @@ -403,17 +464,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = IAMCredentialsClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) api_endpoint = IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -449,15 +518,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -490,12 +562,16 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the iam credentials client. Args: @@ -553,13 +629,21 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = IAMCredentialsClient._read_environment_variables() - self._client_cert_source = IAMCredentialsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = IAMCredentialsClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + IAMCredentialsClient._read_environment_variables() + ) + self._client_cert_source = IAMCredentialsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = IAMCredentialsClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -571,7 +655,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -580,30 +666,40 @@ def __init__(self, *, if transport_provided: # transport is a IAMCredentialsTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." + "When providing a transport instance, provide its scopes directly." ) self._transport = cast(IAMCredentialsTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - IAMCredentialsClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or IAMCredentialsClient._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint)) + self._use_mtls_endpoint, + ) + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[IAMCredentialsTransport], Callable[..., IAMCredentialsTransport]] = ( + transport_init: Union[ + Type[IAMCredentialsTransport], Callable[..., IAMCredentialsTransport] + ] = ( IAMCredentialsClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., IAMCredentialsTransport], transport) @@ -622,31 +718,40 @@ def __init__(self, *, ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.iam.credentials_v1.IAMCredentialsClient`.", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.iam.credentials.v1.IAMCredentials", "credentialsType": None, - } + }, ) - def generate_access_token(self, - request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - scope: Optional[MutableSequence[str]] = None, - lifetime: Optional[duration_pb2.Duration] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateAccessTokenResponse: + def generate_access_token( + self, + request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + scope: Optional[MutableSequence[str]] = None, + lifetime: Optional[duration_pb2.Duration] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateAccessTokenResponse: r"""Generates an OAuth 2.0 access token for a service account. @@ -747,10 +852,14 @@ def sample_generate_access_token(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, scope, lifetime] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -774,9 +883,7 @@ def sample_generate_access_token(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -793,17 +900,18 @@ def sample_generate_access_token(): # Done; return the response. return response - def generate_id_token(self, - request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - audience: Optional[str] = None, - include_email: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateIdTokenResponse: + def generate_id_token( + self, + request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + audience: Optional[str] = None, + include_email: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateIdTokenResponse: r"""Generates an OpenID Connect ID token for a service account. @@ -898,10 +1006,14 @@ def sample_generate_id_token(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, audience, include_email] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -925,9 +1037,7 @@ def sample_generate_id_token(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -944,16 +1054,17 @@ def sample_generate_id_token(): # Done; return the response. return response - def sign_blob(self, - request: Optional[Union[common.SignBlobRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - payload: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignBlobResponse: + def sign_blob( + self, + request: Optional[Union[common.SignBlobRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignBlobResponse: r"""Signs a blob using a service account's system-managed private key. @@ -1037,10 +1148,14 @@ def sample_sign_blob(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, payload] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1062,9 +1177,7 @@ def sample_sign_blob(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1081,16 +1194,17 @@ def sample_sign_blob(): # Done; return the response. return response - def sign_jwt(self, - request: Optional[Union[common.SignJwtRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - payload: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignJwtResponse: + def sign_jwt( + self, + request: Optional[Union[common.SignJwtRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignJwtResponse: r"""Signs a JWT using a service account's system-managed private key. @@ -1177,10 +1291,14 @@ def sample_sign_jwt(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, payload] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1202,9 +1320,7 @@ def sample_sign_jwt(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1235,16 +1351,11 @@ def __exit__(self, type, value, traceback): self.transport.close() - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "IAMCredentialsClient", -) +__all__ = ("IAMCredentialsClient",) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/__init__.py index 0214f01a40ac..897cc6ef3890 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/__init__.py @@ -19,20 +19,18 @@ from .base import IAMCredentialsTransport from .grpc import IAMCredentialsGrpcTransport from .grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport -from .rest import IAMCredentialsRestTransport -from .rest import IAMCredentialsRestInterceptor - +from .rest import IAMCredentialsRestInterceptor, IAMCredentialsRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[IAMCredentialsTransport]] -_transport_registry['grpc'] = IAMCredentialsGrpcTransport -_transport_registry['grpc_asyncio'] = IAMCredentialsGrpcAsyncIOTransport -_transport_registry['rest'] = IAMCredentialsRestTransport +_transport_registry["grpc"] = IAMCredentialsGrpcTransport +_transport_registry["grpc_asyncio"] = IAMCredentialsGrpcAsyncIOTransport +_transport_registry["rest"] = IAMCredentialsRestTransport __all__ = ( - 'IAMCredentialsTransport', - 'IAMCredentialsGrpcTransport', - 'IAMCredentialsGrpcAsyncIOTransport', - 'IAMCredentialsRestTransport', - 'IAMCredentialsRestInterceptor', + "IAMCredentialsTransport", + "IAMCredentialsGrpcTransport", + "IAMCredentialsGrpcAsyncIOTransport", + "IAMCredentialsRestTransport", + "IAMCredentialsRestInterceptor", ) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py index 44e4910533ac..035401000120 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py @@ -16,20 +16,21 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.iam.credentials_v1 import gapic_version as package_version - -import google.auth # type: ignore import google.api_core +import google.auth # type: ignore +import google.protobuf from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf +from google.oauth2 import service_account # type: ignore +from google.iam.credentials_v1 import gapic_version as package_version from google.iam.credentials_v1.types import common -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -38,24 +39,23 @@ class IAMCredentialsTransport(abc.ABC): """Abstract transport class for IAMCredentials.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - DEFAULT_HOST: str = 'iamcredentials.googleapis.com' + DEFAULT_HOST: str = "iamcredentials.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -94,31 +94,43 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host self._wrapped_methods: Dict[Callable, Callable] = {} @@ -190,51 +202,56 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def generate_access_token(self) -> Callable[ - [common.GenerateAccessTokenRequest], - Union[ - common.GenerateAccessTokenResponse, - Awaitable[common.GenerateAccessTokenResponse] - ]]: + def generate_access_token( + self, + ) -> Callable[ + [common.GenerateAccessTokenRequest], + Union[ + common.GenerateAccessTokenResponse, + Awaitable[common.GenerateAccessTokenResponse], + ], + ]: raise NotImplementedError() @property - def generate_id_token(self) -> Callable[ - [common.GenerateIdTokenRequest], - Union[ - common.GenerateIdTokenResponse, - Awaitable[common.GenerateIdTokenResponse] - ]]: + def generate_id_token( + self, + ) -> Callable[ + [common.GenerateIdTokenRequest], + Union[ + common.GenerateIdTokenResponse, Awaitable[common.GenerateIdTokenResponse] + ], + ]: raise NotImplementedError() @property - def sign_blob(self) -> Callable[ - [common.SignBlobRequest], - Union[ - common.SignBlobResponse, - Awaitable[common.SignBlobResponse] - ]]: + def sign_blob( + self, + ) -> Callable[ + [common.SignBlobRequest], + Union[common.SignBlobResponse, Awaitable[common.SignBlobResponse]], + ]: raise NotImplementedError() @property - def sign_jwt(self) -> Callable[ - [common.SignJwtRequest], - Union[ - common.SignJwtResponse, - Awaitable[common.SignJwtResponse] - ]]: + def sign_jwt( + self, + ) -> Callable[ + [common.SignJwtRequest], + Union[common.SignJwtResponse, Awaitable[common.SignJwtResponse]], + ]: raise NotImplementedError() @property @@ -242,6 +259,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'IAMCredentialsTransport', -) +__all__ = ("IAMCredentialsTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py index 5979ede85cae..b14d1137b781 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py @@ -19,22 +19,22 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson +import google.auth # type: ignore import google.protobuf.message - import grpc # type: ignore import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson from google.iam.credentials_v1.types import common -from .base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,7 +44,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -65,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -76,7 +78,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -91,7 +97,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": client_call_details.method, "response": grpc_response, @@ -122,23 +128,26 @@ class IAMCredentialsGrpcTransport(IAMCredentialsTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] - def __init__(self, *, - host: str = 'iamcredentials.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "iamcredentials.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -265,19 +274,23 @@ def __init__(self, *, ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'iamcredentials.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "iamcredentials.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -313,19 +326,20 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property - def generate_access_token(self) -> Callable[ - [common.GenerateAccessTokenRequest], - common.GenerateAccessTokenResponse]: + def generate_access_token( + self, + ) -> Callable[ + [common.GenerateAccessTokenRequest], common.GenerateAccessTokenResponse + ]: r"""Return a callable for the generate access token method over gRPC. Generates an OAuth 2.0 access token for a service @@ -341,18 +355,18 @@ def generate_access_token(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'generate_access_token' not in self._stubs: - self._stubs['generate_access_token'] = self._logged_channel.unary_unary( - '/google.iam.credentials.v1.IAMCredentials/GenerateAccessToken', + if "generate_access_token" not in self._stubs: + self._stubs["generate_access_token"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/GenerateAccessToken", request_serializer=common.GenerateAccessTokenRequest.serialize, response_deserializer=common.GenerateAccessTokenResponse.deserialize, ) - return self._stubs['generate_access_token'] + return self._stubs["generate_access_token"] @property - def generate_id_token(self) -> Callable[ - [common.GenerateIdTokenRequest], - common.GenerateIdTokenResponse]: + def generate_id_token( + self, + ) -> Callable[[common.GenerateIdTokenRequest], common.GenerateIdTokenResponse]: r"""Return a callable for the generate id token method over gRPC. Generates an OpenID Connect ID token for a service @@ -368,18 +382,16 @@ def generate_id_token(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'generate_id_token' not in self._stubs: - self._stubs['generate_id_token'] = self._logged_channel.unary_unary( - '/google.iam.credentials.v1.IAMCredentials/GenerateIdToken', + if "generate_id_token" not in self._stubs: + self._stubs["generate_id_token"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/GenerateIdToken", request_serializer=common.GenerateIdTokenRequest.serialize, response_deserializer=common.GenerateIdTokenResponse.deserialize, ) - return self._stubs['generate_id_token'] + return self._stubs["generate_id_token"] @property - def sign_blob(self) -> Callable[ - [common.SignBlobRequest], - common.SignBlobResponse]: + def sign_blob(self) -> Callable[[common.SignBlobRequest], common.SignBlobResponse]: r"""Return a callable for the sign blob method over gRPC. Signs a blob using a service account's system-managed @@ -395,18 +407,16 @@ def sign_blob(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'sign_blob' not in self._stubs: - self._stubs['sign_blob'] = self._logged_channel.unary_unary( - '/google.iam.credentials.v1.IAMCredentials/SignBlob', + if "sign_blob" not in self._stubs: + self._stubs["sign_blob"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/SignBlob", request_serializer=common.SignBlobRequest.serialize, response_deserializer=common.SignBlobResponse.deserialize, ) - return self._stubs['sign_blob'] + return self._stubs["sign_blob"] @property - def sign_jwt(self) -> Callable[ - [common.SignJwtRequest], - common.SignJwtResponse]: + def sign_jwt(self) -> Callable[[common.SignJwtRequest], common.SignJwtResponse]: r"""Return a callable for the sign jwt method over gRPC. Signs a JWT using a service account's system-managed @@ -422,13 +432,13 @@ def sign_jwt(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'sign_jwt' not in self._stubs: - self._stubs['sign_jwt'] = self._logged_channel.unary_unary( - '/google.iam.credentials.v1.IAMCredentials/SignJwt', + if "sign_jwt" not in self._stubs: + self._stubs["sign_jwt"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/SignJwt", request_serializer=common.SignJwtRequest.serialize, response_deserializer=common.SignJwtResponse.deserialize, ) - return self._stubs['sign_jwt'] + return self._stubs["sign_jwt"] def close(self): self._logged_channel.close() @@ -438,6 +448,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'IAMCredentialsGrpcTransport', -) +__all__ = ("IAMCredentialsGrpcTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc_asyncio.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc_asyncio.py index fb3658d72b8d..2aba9527ad00 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc_asyncio.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # import inspect import json -import pickle import logging as std_logging +import pickle import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore from grpc.experimental import aio # type: ignore from google.iam.credentials_v1.types import common -from .base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport from .grpc import IAMCredentialsGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +46,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +73,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,7 +84,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -95,7 +103,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -131,13 +139,15 @@ class IAMCredentialsGrpcAsyncIOTransport(IAMCredentialsTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel(cls, - host: str = 'iamcredentials.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: + def create_channel( + cls, + host: str = "iamcredentials.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. @@ -168,24 +178,26 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) - def __init__(self, *, - host: str = 'iamcredentials.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "iamcredentials.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -314,7 +326,9 @@ def __init__(self, *, self._interceptor = _LoggingClientAIOInterceptor() self._grpc_channel._unary_unary_interceptors.append(self._interceptor) self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @@ -329,9 +343,12 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def generate_access_token(self) -> Callable[ - [common.GenerateAccessTokenRequest], - Awaitable[common.GenerateAccessTokenResponse]]: + def generate_access_token( + self, + ) -> Callable[ + [common.GenerateAccessTokenRequest], + Awaitable[common.GenerateAccessTokenResponse], + ]: r"""Return a callable for the generate access token method over gRPC. Generates an OAuth 2.0 access token for a service @@ -347,18 +364,20 @@ def generate_access_token(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'generate_access_token' not in self._stubs: - self._stubs['generate_access_token'] = self._logged_channel.unary_unary( - '/google.iam.credentials.v1.IAMCredentials/GenerateAccessToken', + if "generate_access_token" not in self._stubs: + self._stubs["generate_access_token"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/GenerateAccessToken", request_serializer=common.GenerateAccessTokenRequest.serialize, response_deserializer=common.GenerateAccessTokenResponse.deserialize, ) - return self._stubs['generate_access_token'] + return self._stubs["generate_access_token"] @property - def generate_id_token(self) -> Callable[ - [common.GenerateIdTokenRequest], - Awaitable[common.GenerateIdTokenResponse]]: + def generate_id_token( + self, + ) -> Callable[ + [common.GenerateIdTokenRequest], Awaitable[common.GenerateIdTokenResponse] + ]: r"""Return a callable for the generate id token method over gRPC. Generates an OpenID Connect ID token for a service @@ -374,18 +393,18 @@ def generate_id_token(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'generate_id_token' not in self._stubs: - self._stubs['generate_id_token'] = self._logged_channel.unary_unary( - '/google.iam.credentials.v1.IAMCredentials/GenerateIdToken', + if "generate_id_token" not in self._stubs: + self._stubs["generate_id_token"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/GenerateIdToken", request_serializer=common.GenerateIdTokenRequest.serialize, response_deserializer=common.GenerateIdTokenResponse.deserialize, ) - return self._stubs['generate_id_token'] + return self._stubs["generate_id_token"] @property - def sign_blob(self) -> Callable[ - [common.SignBlobRequest], - Awaitable[common.SignBlobResponse]]: + def sign_blob( + self, + ) -> Callable[[common.SignBlobRequest], Awaitable[common.SignBlobResponse]]: r"""Return a callable for the sign blob method over gRPC. Signs a blob using a service account's system-managed @@ -401,18 +420,18 @@ def sign_blob(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'sign_blob' not in self._stubs: - self._stubs['sign_blob'] = self._logged_channel.unary_unary( - '/google.iam.credentials.v1.IAMCredentials/SignBlob', + if "sign_blob" not in self._stubs: + self._stubs["sign_blob"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/SignBlob", request_serializer=common.SignBlobRequest.serialize, response_deserializer=common.SignBlobResponse.deserialize, ) - return self._stubs['sign_blob'] + return self._stubs["sign_blob"] @property - def sign_jwt(self) -> Callable[ - [common.SignJwtRequest], - Awaitable[common.SignJwtResponse]]: + def sign_jwt( + self, + ) -> Callable[[common.SignJwtRequest], Awaitable[common.SignJwtResponse]]: r"""Return a callable for the sign jwt method over gRPC. Signs a JWT using a service account's system-managed @@ -428,16 +447,16 @@ def sign_jwt(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'sign_jwt' not in self._stubs: - self._stubs['sign_jwt'] = self._logged_channel.unary_unary( - '/google.iam.credentials.v1.IAMCredentials/SignJwt', + if "sign_jwt" not in self._stubs: + self._stubs["sign_jwt"] = self._logged_channel.unary_unary( + "/google.iam.credentials.v1.IAMCredentials/SignJwt", request_serializer=common.SignJwtRequest.serialize, response_deserializer=common.SignJwtResponse.deserialize, ) - return self._stubs['sign_jwt'] + return self._stubs["sign_jwt"] def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { self.generate_access_token: self._wrap_method( self.generate_access_token, @@ -514,6 +533,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'IAMCredentialsGrpcAsyncIOTransport', -) +__all__ = ("IAMCredentialsGrpcAsyncIOTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest.py index b9aa3c4b6f94..f6c34807b6b8 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest.py @@ -13,31 +13,25 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging +import dataclasses import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.auth import credentials as ga_credentials # type: ignore +import google.protobuf from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 -import google.protobuf - +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore from google.protobuf import json_format - from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - from google.iam.credentials_v1.types import common - -from .rest_base import _BaseIAMCredentialsRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseIAMCredentialsRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +40,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -114,7 +109,14 @@ def post_sign_jwt(self, response): """ - def pre_generate_access_token(self, request: common.GenerateAccessTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.GenerateAccessTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_generate_access_token( + self, + request: common.GenerateAccessTokenRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + common.GenerateAccessTokenRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for generate_access_token Override in a subclass to manipulate the request or metadata @@ -122,7 +124,9 @@ def pre_generate_access_token(self, request: common.GenerateAccessTokenRequest, """ return request, metadata - def post_generate_access_token(self, response: common.GenerateAccessTokenResponse) -> common.GenerateAccessTokenResponse: + def post_generate_access_token( + self, response: common.GenerateAccessTokenResponse + ) -> common.GenerateAccessTokenResponse: """Post-rpc interceptor for generate_access_token DEPRECATED. Please use the `post_generate_access_token_with_metadata` @@ -135,7 +139,13 @@ def post_generate_access_token(self, response: common.GenerateAccessTokenRespons """ return response - def post_generate_access_token_with_metadata(self, response: common.GenerateAccessTokenResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.GenerateAccessTokenResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_generate_access_token_with_metadata( + self, + response: common.GenerateAccessTokenResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + common.GenerateAccessTokenResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for generate_access_token Override in a subclass to read or manipulate the response or metadata after it @@ -150,7 +160,11 @@ def post_generate_access_token_with_metadata(self, response: common.GenerateAcce """ return response, metadata - def pre_generate_id_token(self, request: common.GenerateIdTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.GenerateIdTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_generate_id_token( + self, + request: common.GenerateIdTokenRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.GenerateIdTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for generate_id_token Override in a subclass to manipulate the request or metadata @@ -158,7 +172,9 @@ def pre_generate_id_token(self, request: common.GenerateIdTokenRequest, metadata """ return request, metadata - def post_generate_id_token(self, response: common.GenerateIdTokenResponse) -> common.GenerateIdTokenResponse: + def post_generate_id_token( + self, response: common.GenerateIdTokenResponse + ) -> common.GenerateIdTokenResponse: """Post-rpc interceptor for generate_id_token DEPRECATED. Please use the `post_generate_id_token_with_metadata` @@ -171,7 +187,11 @@ def post_generate_id_token(self, response: common.GenerateIdTokenResponse) -> co """ return response - def post_generate_id_token_with_metadata(self, response: common.GenerateIdTokenResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.GenerateIdTokenResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_generate_id_token_with_metadata( + self, + response: common.GenerateIdTokenResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.GenerateIdTokenResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for generate_id_token Override in a subclass to read or manipulate the response or metadata after it @@ -186,7 +206,11 @@ def post_generate_id_token_with_metadata(self, response: common.GenerateIdTokenR """ return response, metadata - def pre_sign_blob(self, request: common.SignBlobRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.SignBlobRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_sign_blob( + self, + request: common.SignBlobRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.SignBlobRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for sign_blob Override in a subclass to manipulate the request or metadata @@ -194,7 +218,9 @@ def pre_sign_blob(self, request: common.SignBlobRequest, metadata: Sequence[Tupl """ return request, metadata - def post_sign_blob(self, response: common.SignBlobResponse) -> common.SignBlobResponse: + def post_sign_blob( + self, response: common.SignBlobResponse + ) -> common.SignBlobResponse: """Post-rpc interceptor for sign_blob DEPRECATED. Please use the `post_sign_blob_with_metadata` @@ -207,7 +233,11 @@ def post_sign_blob(self, response: common.SignBlobResponse) -> common.SignBlobRe """ return response - def post_sign_blob_with_metadata(self, response: common.SignBlobResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.SignBlobResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_sign_blob_with_metadata( + self, + response: common.SignBlobResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.SignBlobResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for sign_blob Override in a subclass to read or manipulate the response or metadata after it @@ -222,7 +252,11 @@ def post_sign_blob_with_metadata(self, response: common.SignBlobResponse, metada """ return response, metadata - def pre_sign_jwt(self, request: common.SignJwtRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.SignJwtRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_sign_jwt( + self, + request: common.SignJwtRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.SignJwtRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for sign_jwt Override in a subclass to manipulate the request or metadata @@ -243,7 +277,11 @@ def post_sign_jwt(self, response: common.SignJwtResponse) -> common.SignJwtRespo """ return response - def post_sign_jwt_with_metadata(self, response: common.SignJwtResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.SignJwtResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_sign_jwt_with_metadata( + self, + response: common.SignJwtResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[common.SignJwtResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for sign_jwt Override in a subclass to read or manipulate the response or metadata after it @@ -287,62 +325,63 @@ class IAMCredentialsRestTransport(_BaseIAMCredentialsRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, *, - host: str = 'iamcredentials.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[IAMCredentialsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "iamcredentials.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[IAMCredentialsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to (default: 'iamcredentials.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. This argument will be - removed in the next major version of this library. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - interceptor (Optional[IAMCredentialsRestInterceptor]): Interceptor used - to manipulate requests, request metadata, and responses. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iamcredentials.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[IAMCredentialsRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. """ # Run the base constructor # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. @@ -354,16 +393,20 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience + api_audience=api_audience, ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) + self._credentials, default_host=self.DEFAULT_HOST + ) if client_cert_source_for_mtls: self._session.configure_mtls_channel(client_cert_source_for_mtls) self._interceptor = interceptor or IAMCredentialsRestInterceptor() self._prep_wrapped_messages(client_info) - class _GenerateAccessToken(_BaseIAMCredentialsRestTransport._BaseGenerateAccessToken, IAMCredentialsRestStub): + class _GenerateAccessToken( + _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken, + IAMCredentialsRestStub, + ): def __hash__(self): return hash("IAMCredentialsRestTransport.GenerateAccessToken") @@ -375,27 +418,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: common.GenerateAccessTokenRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> common.GenerateAccessTokenResponse: + def __call__( + self, + request: common.GenerateAccessTokenRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateAccessTokenResponse: r"""Call the generate access token method over HTTP. Args: @@ -416,30 +461,42 @@ def __call__(self, http_options = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_http_options() - request, metadata = self._interceptor.pre_generate_access_token(request, metadata) - transcoded_request = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_generate_access_token( + request, metadata + ) + transcoded_request = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_transcoded_request( + http_options, request + ) - body = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_request_body_json(transcoded_request) + body = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.GenerateAccessToken", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "GenerateAccessToken", "httpRequest": http_request, @@ -448,7 +505,15 @@ def __call__(self, ) # Send the request - response = IAMCredentialsRestTransport._GenerateAccessToken._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = IAMCredentialsRestTransport._GenerateAccessToken._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -463,20 +528,26 @@ def __call__(self, resp = self._interceptor.post_generate_access_token(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_generate_access_token_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_generate_access_token_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = common.GenerateAccessTokenResponse.to_json(response) + response_payload = common.GenerateAccessTokenResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.iam.credentials_v1.IAMCredentialsClient.generate_access_token", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "GenerateAccessToken", "metadata": http_response["headers"], @@ -485,7 +556,9 @@ def __call__(self, ) return resp - class _GenerateIdToken(_BaseIAMCredentialsRestTransport._BaseGenerateIdToken, IAMCredentialsRestStub): + class _GenerateIdToken( + _BaseIAMCredentialsRestTransport._BaseGenerateIdToken, IAMCredentialsRestStub + ): def __hash__(self): return hash("IAMCredentialsRestTransport.GenerateIdToken") @@ -497,27 +570,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: common.GenerateIdTokenRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> common.GenerateIdTokenResponse: + def __call__( + self, + request: common.GenerateIdTokenRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateIdTokenResponse: r"""Call the generate id token method over HTTP. Args: @@ -538,30 +613,42 @@ def __call__(self, http_options = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_http_options() - request, metadata = self._interceptor.pre_generate_id_token(request, metadata) - transcoded_request = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_generate_id_token( + request, metadata + ) + transcoded_request = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_transcoded_request( + http_options, request + ) - body = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_request_body_json(transcoded_request) + body = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.GenerateIdToken", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "GenerateIdToken", "httpRequest": http_request, @@ -570,7 +657,15 @@ def __call__(self, ) # Send the request - response = IAMCredentialsRestTransport._GenerateIdToken._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = IAMCredentialsRestTransport._GenerateIdToken._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -585,20 +680,24 @@ def __call__(self, resp = self._interceptor.post_generate_id_token(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_generate_id_token_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_generate_id_token_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = common.GenerateIdTokenResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.iam.credentials_v1.IAMCredentialsClient.generate_id_token", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "GenerateIdToken", "metadata": http_response["headers"], @@ -607,7 +706,9 @@ def __call__(self, ) return resp - class _SignBlob(_BaseIAMCredentialsRestTransport._BaseSignBlob, IAMCredentialsRestStub): + class _SignBlob( + _BaseIAMCredentialsRestTransport._BaseSignBlob, IAMCredentialsRestStub + ): def __hash__(self): return hash("IAMCredentialsRestTransport.SignBlob") @@ -619,27 +720,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: common.SignBlobRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> common.SignBlobResponse: + def __call__( + self, + request: common.SignBlobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignBlobResponse: r"""Call the sign blob method over HTTP. Args: @@ -658,32 +761,50 @@ def __call__(self, """ - http_options = _BaseIAMCredentialsRestTransport._BaseSignBlob._get_http_options() + http_options = ( + _BaseIAMCredentialsRestTransport._BaseSignBlob._get_http_options() + ) request, metadata = self._interceptor.pre_sign_blob(request, metadata) - transcoded_request = _BaseIAMCredentialsRestTransport._BaseSignBlob._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseIAMCredentialsRestTransport._BaseSignBlob._get_transcoded_request( + http_options, request + ) + ) - body = _BaseIAMCredentialsRestTransport._BaseSignBlob._get_request_body_json(transcoded_request) + body = ( + _BaseIAMCredentialsRestTransport._BaseSignBlob._get_request_body_json( + transcoded_request + ) + ) # Jsonify the query params - query_params = _BaseIAMCredentialsRestTransport._BaseSignBlob._get_query_params_json(transcoded_request) + query_params = ( + _BaseIAMCredentialsRestTransport._BaseSignBlob._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.SignBlob", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "SignBlob", "httpRequest": http_request, @@ -692,7 +813,15 @@ def __call__(self, ) # Send the request - response = IAMCredentialsRestTransport._SignBlob._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = IAMCredentialsRestTransport._SignBlob._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -707,20 +836,24 @@ def __call__(self, resp = self._interceptor.post_sign_blob(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_sign_blob_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_sign_blob_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = common.SignBlobResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.iam.credentials_v1.IAMCredentialsClient.sign_blob", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "SignBlob", "metadata": http_response["headers"], @@ -729,7 +862,9 @@ def __call__(self, ) return resp - class _SignJwt(_BaseIAMCredentialsRestTransport._BaseSignJwt, IAMCredentialsRestStub): + class _SignJwt( + _BaseIAMCredentialsRestTransport._BaseSignJwt, IAMCredentialsRestStub + ): def __hash__(self): return hash("IAMCredentialsRestTransport.SignJwt") @@ -741,27 +876,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: common.SignJwtRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> common.SignJwtResponse: + def __call__( + self, + request: common.SignJwtRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignJwtResponse: r"""Call the sign jwt method over HTTP. Args: @@ -780,32 +917,48 @@ def __call__(self, """ - http_options = _BaseIAMCredentialsRestTransport._BaseSignJwt._get_http_options() + http_options = ( + _BaseIAMCredentialsRestTransport._BaseSignJwt._get_http_options() + ) request, metadata = self._interceptor.pre_sign_jwt(request, metadata) - transcoded_request = _BaseIAMCredentialsRestTransport._BaseSignJwt._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseIAMCredentialsRestTransport._BaseSignJwt._get_transcoded_request( + http_options, request + ) + ) - body = _BaseIAMCredentialsRestTransport._BaseSignJwt._get_request_body_json(transcoded_request) + body = _BaseIAMCredentialsRestTransport._BaseSignJwt._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseIAMCredentialsRestTransport._BaseSignJwt._get_query_params_json(transcoded_request) + query_params = ( + _BaseIAMCredentialsRestTransport._BaseSignJwt._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.SignJwt", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "SignJwt", "httpRequest": http_request, @@ -814,7 +967,15 @@ def __call__(self, ) # Send the request - response = IAMCredentialsRestTransport._SignJwt._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = IAMCredentialsRestTransport._SignJwt._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -829,20 +990,24 @@ def __call__(self, resp = self._interceptor.post_sign_jwt(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_sign_jwt_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_sign_jwt_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = common.SignJwtResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.iam.credentials_v1.IAMCredentialsClient.sign_jwt", - extra = { + extra={ "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "SignJwt", "metadata": http_response["headers"], @@ -852,36 +1017,34 @@ def __call__(self, return resp @property - def generate_access_token(self) -> Callable[ - [common.GenerateAccessTokenRequest], - common.GenerateAccessTokenResponse]: + def generate_access_token( + self, + ) -> Callable[ + [common.GenerateAccessTokenRequest], common.GenerateAccessTokenResponse + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore + return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore @property - def generate_id_token(self) -> Callable[ - [common.GenerateIdTokenRequest], - common.GenerateIdTokenResponse]: + def generate_id_token( + self, + ) -> Callable[[common.GenerateIdTokenRequest], common.GenerateIdTokenResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GenerateIdToken(self._session, self._host, self._interceptor) # type: ignore + return self._GenerateIdToken(self._session, self._host, self._interceptor) # type: ignore @property - def sign_blob(self) -> Callable[ - [common.SignBlobRequest], - common.SignBlobResponse]: + def sign_blob(self) -> Callable[[common.SignBlobRequest], common.SignBlobResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._SignBlob(self._session, self._host, self._interceptor) # type: ignore + return self._SignBlob(self._session, self._host, self._interceptor) # type: ignore @property - def sign_jwt(self) -> Callable[ - [common.SignJwtRequest], - common.SignJwtResponse]: + def sign_jwt(self) -> Callable[[common.SignJwtRequest], common.SignJwtResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._SignJwt(self._session, self._host, self._interceptor) # type: ignore + return self._SignJwt(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -891,6 +1054,4 @@ def close(self): self._session.close() -__all__=( - 'IAMCredentialsRestTransport', -) +__all__ = ("IAMCredentialsRestTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest_base.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest_base.py index a03907410f78..9ab06189f107 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest_base.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest_base.py @@ -14,18 +14,16 @@ # limitations under the License. # import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from .base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format from google.iam.credentials_v1.types import common +from .base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport + class _BaseIAMCredentialsRestTransport(IAMCredentialsTransport): """Base REST backend transport for IAMCredentials. @@ -40,14 +38,16 @@ class _BaseIAMCredentialsRestTransport(IAMCredentialsTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, *, - host: str = 'iamcredentials.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "iamcredentials.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: host (Optional[str]): @@ -71,7 +71,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -82,27 +84,31 @@ def __init__(self, *, credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience + api_audience=api_audience, ) class _BaseGenerateAccessToken: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/serviceAccounts/*}:generateAccessToken', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/serviceAccounts/*}:generateAccessToken", + "body": "*", + }, ] return http_options @@ -117,17 +123,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False + transcoded_request["body"], use_integers_for_enums=False ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_unset_required_fields( + query_params + ) + ) return query_params @@ -135,20 +147,24 @@ class _BaseGenerateIdToken: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/serviceAccounts/*}:generateIdToken', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/serviceAccounts/*}:generateIdToken", + "body": "*", + }, ] return http_options @@ -163,17 +179,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False + transcoded_request["body"], use_integers_for_enums=False ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_unset_required_fields( + query_params + ) + ) return query_params @@ -181,20 +203,24 @@ class _BaseSignBlob: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/serviceAccounts/*}:signBlob', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/serviceAccounts/*}:signBlob", + "body": "*", + }, ] return http_options @@ -209,17 +235,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False + transcoded_request["body"], use_integers_for_enums=False ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseIAMCredentialsRestTransport._BaseSignBlob._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseIAMCredentialsRestTransport._BaseSignBlob._get_unset_required_fields( + query_params + ) + ) return query_params @@ -227,20 +259,24 @@ class _BaseSignJwt: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/serviceAccounts/*}:signJwt', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/serviceAccounts/*}:signJwt", + "body": "*", + }, ] return http_options @@ -255,21 +291,25 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=False + transcoded_request["body"], use_integers_for_enums=False ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=False, - )) - query_params.update(_BaseIAMCredentialsRestTransport._BaseSignJwt._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseIAMCredentialsRestTransport._BaseSignJwt._get_unset_required_fields( + query_params + ) + ) return query_params -__all__=( - '_BaseIAMCredentialsRestTransport', -) +__all__ = ("_BaseIAMCredentialsRestTransport",) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/__init__.py index f257b889924c..e3846fefa8fb 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/__init__.py @@ -25,12 +25,12 @@ ) __all__ = ( - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'GenerateIdTokenRequest', - 'GenerateIdTokenResponse', - 'SignBlobRequest', - 'SignBlobResponse', - 'SignJwtRequest', - 'SignJwtResponse', + "GenerateAccessTokenRequest", + "GenerateAccessTokenResponse", + "GenerateIdTokenRequest", + "GenerateIdTokenResponse", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", ) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/common.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/common.py index 1acdee2180bc..f2f42dd93afe 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/common.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/common.py @@ -17,23 +17,21 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.iam.credentials.v1', + package="google.iam.credentials.v1", manifest={ - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'SignBlobRequest', - 'SignBlobResponse', - 'SignJwtRequest', - 'SignJwtResponse', - 'GenerateIdTokenRequest', - 'GenerateIdTokenResponse', + "GenerateAccessTokenRequest", + "GenerateAccessTokenResponse", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", + "GenerateIdTokenRequest", + "GenerateIdTokenResponse", }, ) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/iamcredentials.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/iamcredentials.py index 17d048bd5d33..1616a02036f5 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/iamcredentials.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/iamcredentials.py @@ -15,11 +15,9 @@ # import proto # type: ignore - __protobuf__ = proto.module( - package='google.iam.credentials.v1', - manifest={ - }, + package="google.iam.credentials.v1", + manifest={}, ) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py b/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py index 5d529145149f..46b2de6633e6 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py @@ -17,9 +17,8 @@ import pathlib import re import shutil - -from typing import Dict, List import warnings +from typing import Dict, List import nox @@ -153,7 +152,8 @@ def lint(session): # 2. Check formatting session.run( - "ruff", "format", + "ruff", + "format", "--check", f"--target-version=py{ALL_PYTHON[0].replace('.', '')}", "--line-length=88", @@ -166,12 +166,15 @@ def lint(session): @nox.session(python=DEFAULT_PYTHON_VERSION) def blacken(session): """(Deprecated) Legacy session. Please use 'nox -s format'.""" - session.log("WARNING: The 'blacken' session is deprecated and will be removed in a future release. Please use 'nox -s format' in the future.") + session.log( + "WARNING: The 'blacken' session is deprecated and will be removed in a future release. Please use 'nox -s format' in the future." + ) # Just run the ruff formatter (keeping legacy behavior of only formatting, not sorting imports) session.install(RUFF_VERSION) session.run( - "ruff", "format", + "ruff", + "format", f"--target-version=py{ALL_PYTHON[0].replace('.', '')}", "--line-length=88", *LINT_PATHS, @@ -190,8 +193,10 @@ def format(session): # check --select I: Enables strict import sorting # --fix: Applies the changes automatically session.run( - "ruff", "check", - "--select", "I", + "ruff", + "check", + "--select", + "I", "--fix", f"--target-version=py{ALL_PYTHON[0].replace('.', '')}", "--line-length=88", # Standard Black line length @@ -200,7 +205,8 @@ def format(session): # 3. Run Ruff to format code session.run( - "ruff", "format", + "ruff", + "format", f"--target-version=py{ALL_PYTHON[0].replace('.', '')}", "--line-length=88", # Standard Black line length *LINT_PATHS, @@ -385,8 +391,10 @@ def docs(session): "sphinx-build", "-T", # show full traceback on exception "-N", # no colors - "-b", "html", # builder - "-d", os.path.join("docs", "_build", "doctrees", ""), # cache directory + "-b", + "html", # builder + "-d", + os.path.join("docs", "_build", "doctrees", ""), # cache directory # paths to build: os.path.join("docs", ""), os.path.join("docs", "_build", "html", ""), diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_access_token_async.py b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_access_token_async.py index 23cdbcb65d98..05017303872a 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_access_token_async.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_access_token_async.py @@ -41,7 +41,7 @@ async def sample_generate_access_token(): # Initialize request argument(s) request = credentials_v1.GenerateAccessTokenRequest( name="name_value", - scope=['scope_value1', 'scope_value2'], + scope=["scope_value1", "scope_value2"], ) # Make the request @@ -50,4 +50,5 @@ async def sample_generate_access_token(): # Handle the response print(response) + # [END iamcredentials_v1_generated_IAMCredentials_GenerateAccessToken_async] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_access_token_sync.py b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_access_token_sync.py index b7890bd0106e..045e84d0e6e5 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_access_token_sync.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_access_token_sync.py @@ -41,7 +41,7 @@ def sample_generate_access_token(): # Initialize request argument(s) request = credentials_v1.GenerateAccessTokenRequest( name="name_value", - scope=['scope_value1', 'scope_value2'], + scope=["scope_value1", "scope_value2"], ) # Make the request @@ -50,4 +50,5 @@ def sample_generate_access_token(): # Handle the response print(response) + # [END iamcredentials_v1_generated_IAMCredentials_GenerateAccessToken_sync] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_id_token_async.py b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_id_token_async.py index 0215ccea7f69..6a7bf6b56b4d 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_id_token_async.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_id_token_async.py @@ -50,4 +50,5 @@ async def sample_generate_id_token(): # Handle the response print(response) + # [END iamcredentials_v1_generated_IAMCredentials_GenerateIdToken_async] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_id_token_sync.py b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_id_token_sync.py index cf2199eae2ca..664b7794a48e 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_id_token_sync.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_id_token_sync.py @@ -50,4 +50,5 @@ def sample_generate_id_token(): # Handle the response print(response) + # [END iamcredentials_v1_generated_IAMCredentials_GenerateIdToken_sync] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_blob_async.py b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_blob_async.py index 9dd1113be682..19218118f134 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_blob_async.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_blob_async.py @@ -41,7 +41,7 @@ async def sample_sign_blob(): # Initialize request argument(s) request = credentials_v1.SignBlobRequest( name="name_value", - payload=b'payload_blob', + payload=b"payload_blob", ) # Make the request @@ -50,4 +50,5 @@ async def sample_sign_blob(): # Handle the response print(response) + # [END iamcredentials_v1_generated_IAMCredentials_SignBlob_async] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_blob_sync.py b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_blob_sync.py index 62752da45472..715257d344a9 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_blob_sync.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_blob_sync.py @@ -41,7 +41,7 @@ def sample_sign_blob(): # Initialize request argument(s) request = credentials_v1.SignBlobRequest( name="name_value", - payload=b'payload_blob', + payload=b"payload_blob", ) # Make the request @@ -50,4 +50,5 @@ def sample_sign_blob(): # Handle the response print(response) + # [END iamcredentials_v1_generated_IAMCredentials_SignBlob_sync] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_jwt_async.py b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_jwt_async.py index 3022b82a96d2..5a01a1bfaf3c 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_jwt_async.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_jwt_async.py @@ -50,4 +50,5 @@ async def sample_sign_jwt(): # Handle the response print(response) + # [END iamcredentials_v1_generated_IAMCredentials_SignJwt_async] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_jwt_sync.py b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_jwt_sync.py index 3c6faea9b194..41115a20f45f 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_jwt_sync.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_jwt_sync.py @@ -50,4 +50,5 @@ def sample_sign_jwt(): # Handle the response print(response) + # [END iamcredentials_v1_generated_IAMCredentials_SignJwt_sync] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/setup.py b/packages/gapic-generator/tests/integration/goldens/credentials/setup.py index 74e94c582cc0..73ee574867e2 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/setup.py @@ -17,20 +17,20 @@ import os import re -import setuptools # type: ignore +import setuptools # type: ignore package_root = os.path.abspath(os.path.dirname(__file__)) -name = 'google-iam-credentials' +name = "google-iam-credentials" description = "Google Iam Credentials API client library" version = None -with open(os.path.join(package_root, 'google/iam/credentials/gapic_version.py')) as fp: +with open(os.path.join(package_root, "google/iam/credentials/gapic_version.py")) as fp: version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) + assert len(version_candidates) == 1 version = version_candidates[0] if version[0] == "0": @@ -49,8 +49,7 @@ "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", "protobuf >= 4.25.8, < 8.0.0", ] -extras = { -} +extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-iam-credentials" package_root = os.path.abspath(os.path.dirname(__file__)) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/__init__.py index 191773d5572d..cbf94b283c70 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/__init__.py @@ -1,4 +1,3 @@ - # -*- coding: utf-8 -*- # Copyright 2025 Google LLC # diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/__init__.py index 191773d5572d..cbf94b283c70 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/__init__.py @@ -1,4 +1,3 @@ - # -*- coding: utf-8 -*- # Copyright 2025 Google LLC # diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/__init__.py index 191773d5572d..cbf94b283c70 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/__init__.py @@ -1,4 +1,3 @@ - # -*- coding: utf-8 -*- # Copyright 2025 Google LLC # diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/__init__.py index 191773d5572d..cbf94b283c70 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/__init__.py @@ -1,4 +1,3 @@ - # -*- coding: utf-8 -*- # Copyright 2025 Google LLC # diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py index f890571724a9..36d38d23554a 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py @@ -13,51 +13,52 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import math import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence from unittest import mock from unittest.mock import AsyncMock import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math import pytest -from collections.abc import Sequence, Mapping from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule +from google.protobuf import json_format +from grpc.experimental import aio from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response from requests.sessions import Session -from google.protobuf import json_format try: from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER +except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -from google.api_core import client_options +import google.auth +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template from google.api_core import retry as retries from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -from google.iam.credentials_v1.services.iam_credentials import IAMCredentialsAsyncClient -from google.iam.credentials_v1.services.iam_credentials import IAMCredentialsClient -from google.iam.credentials_v1.services.iam_credentials import transports -from google.iam.credentials_v1.types import common from google.oauth2 import service_account -import google.auth -import google.protobuf.duration_pb2 as duration_pb2 # type: ignore -import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore - +from google.iam.credentials_v1.services.iam_credentials import ( + IAMCredentialsAsyncClient, + IAMCredentialsClient, + transports, +) +from google.iam.credentials_v1.types import common CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -72,9 +73,11 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") + def client_cert_source_callback(): return b"cert bytes", b"key bytes" + # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -82,17 +85,27 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) def test__get_default_mtls_endpoint(): @@ -104,21 +117,47 @@ def test__get_default_mtls_endpoint(): custom_endpoint = ".custom" assert IAMCredentialsClient._get_default_mtls_endpoint(None) is None - assert IAMCredentialsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert IAMCredentialsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert IAMCredentialsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert IAMCredentialsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert IAMCredentialsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - assert IAMCredentialsClient._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint + assert ( + IAMCredentialsClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + IAMCredentialsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + IAMCredentialsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + IAMCredentialsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + IAMCredentialsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + assert ( + IAMCredentialsClient._get_default_mtls_endpoint(custom_endpoint) + == custom_endpoint + ) + def test__read_environment_variables(): assert IAMCredentialsClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert IAMCredentialsClient._read_environment_variables() == (True, "auto", None) + assert IAMCredentialsClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert IAMCredentialsClient._read_environment_variables() == (False, "auto", None) + assert IAMCredentialsClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} @@ -132,27 +171,46 @@ def test__read_environment_variables(): ) else: assert IAMCredentialsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert IAMCredentialsClient._read_environment_variables() == ( False, - "auto", + "never", None, ) - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert IAMCredentialsClient._read_environment_variables() == (False, "never", None) - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert IAMCredentialsClient._read_environment_variables() == (False, "always", None) + assert IAMCredentialsClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert IAMCredentialsClient._read_environment_variables() == (False, "auto", None) + assert IAMCredentialsClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: IAMCredentialsClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert IAMCredentialsClient._read_environment_variables() == (False, "auto", "foo.com") + assert IAMCredentialsClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) def test_use_client_cert_effective(): @@ -161,7 +219,9 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=True): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): assert IAMCredentialsClient._use_client_cert_effective() is True # Test case 2: Test when `should_use_client_cert` returns False. @@ -169,7 +229,9 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should NOT be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=False): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): assert IAMCredentialsClient._use_client_cert_effective() is False # Test case 3: Test when `should_use_client_cert` is unavailable and the @@ -181,7 +243,9 @@ def test_use_client_cert_effective(): # Test case 4: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): assert IAMCredentialsClient._use_client_cert_effective() is False # Test case 5: Test when `should_use_client_cert` is unavailable and the @@ -193,7 +257,9 @@ def test_use_client_cert_effective(): # Test case 6: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): assert IAMCredentialsClient._use_client_cert_effective() is False # Test case 7: Test when `should_use_client_cert` is unavailable and the @@ -205,7 +271,9 @@ def test_use_client_cert_effective(): # Test case 8: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): assert IAMCredentialsClient._use_client_cert_effective() is False # Test case 9: Test when `should_use_client_cert` is unavailable and the @@ -220,83 +288,167 @@ def test_use_client_cert_effective(): # The method should raise a ValueError as the environment variable must be either # "true" or "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): with pytest.raises(ValueError): IAMCredentialsClient._use_client_cert_effective() # Test case 11: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. # The method should return False as the environment variable is set to an invalid value. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): assert IAMCredentialsClient._use_client_cert_effective() is False # Test case 12: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, # the GOOGLE_API_CONFIG environment variable is unset. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): assert IAMCredentialsClient._use_client_cert_effective() is False + def test__get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() assert IAMCredentialsClient._get_client_cert_source(None, False) is None - assert IAMCredentialsClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert IAMCredentialsClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + IAMCredentialsClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + IAMCredentialsClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert IAMCredentialsClient._get_client_cert_source(None, True) is mock_default_cert_source - assert IAMCredentialsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + IAMCredentialsClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + IAMCredentialsClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) -@mock.patch.object(IAMCredentialsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMCredentialsClient)) -@mock.patch.object(IAMCredentialsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMCredentialsAsyncClient)) + +@mock.patch.object( + IAMCredentialsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(IAMCredentialsClient), +) +@mock.patch.object( + IAMCredentialsAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(IAMCredentialsAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = IAMCredentialsClient._DEFAULT_UNIVERSE - default_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert IAMCredentialsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert IAMCredentialsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT - assert IAMCredentialsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert IAMCredentialsClient._get_api_endpoint(None, None, default_universe, "always") == IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT - assert IAMCredentialsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT - assert IAMCredentialsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert IAMCredentialsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + IAMCredentialsClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + IAMCredentialsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + IAMCredentialsClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + IAMCredentialsClient._get_api_endpoint(None, None, default_universe, "always") + == IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + IAMCredentialsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + IAMCredentialsClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + IAMCredentialsClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - IAMCredentialsClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + IAMCredentialsClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) def test__get_universe_domain(): client_universe_domain = "foo.com" universe_domain_env = "bar.com" - assert IAMCredentialsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert IAMCredentialsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert IAMCredentialsClient._get_universe_domain(None, None) == IAMCredentialsClient._DEFAULT_UNIVERSE + assert ( + IAMCredentialsClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + IAMCredentialsClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + IAMCredentialsClient._get_universe_domain(None, None) + == IAMCredentialsClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: IAMCredentialsClient._get_universe_domain("", None) assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False) -]) + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): cred = mock.Mock(["get_cred_info"]) cred.get_cred_info = mock.Mock(return_value=cred_info_json) @@ -312,7 +464,8 @@ def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_in else: assert error.details == ["foo"] -@pytest.mark.parametrize("error_code", [401,403,404,500]) + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): cred = mock.Mock([]) assert not hasattr(cred, "get_cred_info") @@ -325,14 +478,20 @@ def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): client._add_cred_info_for_auth_errors(error) assert error.details == [] -@pytest.mark.parametrize("client_class,transport_name", [ - (IAMCredentialsClient, "grpc"), - (IAMCredentialsAsyncClient, "grpc_asyncio"), - (IAMCredentialsClient, "rest"), -]) + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (IAMCredentialsClient, "grpc"), + (IAMCredentialsAsyncClient, "grpc_asyncio"), + (IAMCredentialsClient, "rest"), + ], +) def test_iam_credentials_client_from_service_account_info(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info, transport=transport_name) @@ -340,52 +499,68 @@ def test_iam_credentials_client_from_service_account_info(client_class, transpor assert isinstance(client, client_class) assert client.transport._host == ( - 'iamcredentials.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://iamcredentials.googleapis.com' + "iamcredentials.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://iamcredentials.googleapis.com" ) -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.IAMCredentialsGrpcTransport, "grpc"), - (transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.IAMCredentialsRestTransport, "rest"), -]) -def test_iam_credentials_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.IAMCredentialsGrpcTransport, "grpc"), + (transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.IAMCredentialsRestTransport, "rest"), + ], +) +def test_iam_credentials_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() -@pytest.mark.parametrize("client_class,transport_name", [ - (IAMCredentialsClient, "grpc"), - (IAMCredentialsAsyncClient, "grpc_asyncio"), - (IAMCredentialsClient, "rest"), -]) +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (IAMCredentialsClient, "grpc"), + (IAMCredentialsAsyncClient, "grpc_asyncio"), + (IAMCredentialsClient, "rest"), + ], +) def test_iam_credentials_client_from_service_account_file(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) assert client.transport._credentials == creds assert isinstance(client, client_class) - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == ( - 'iamcredentials.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://iamcredentials.googleapis.com' + "iamcredentials.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://iamcredentials.googleapis.com" ) @@ -401,30 +576,45 @@ def test_iam_credentials_client_get_transport_class(): assert transport == transports.IAMCredentialsGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc"), - (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio"), - (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest"), -]) -@mock.patch.object(IAMCredentialsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMCredentialsClient)) -@mock.patch.object(IAMCredentialsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMCredentialsAsyncClient)) -def test_iam_credentials_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc"), + ( + IAMCredentialsAsyncClient, + transports.IAMCredentialsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest"), + ], +) +@mock.patch.object( + IAMCredentialsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(IAMCredentialsClient), +) +@mock.patch.object( + IAMCredentialsAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(IAMCredentialsAsyncClient), +) +def test_iam_credentials_client_client_options( + client_class, transport_class, transport_name +): # Check that if channel is provided we won't create a new one. - with mock.patch.object(IAMCredentialsClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(IAMCredentialsClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() # Check that if channel is provided via str we will create a new one. - with mock.patch.object(IAMCredentialsClient, 'get_transport_class') as gtc: + with mock.patch.object(IAMCredentialsClient, "get_transport_class") as gtc: client = client_class(transport=transport_name) gtc.assert_called() # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( @@ -442,13 +632,15 @@ def test_iam_credentials_client_client_options(client_class, transport_class, tr # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -460,7 +652,7 @@ def test_iam_credentials_client_client_options(client_class, transport_class, tr # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -480,17 +672,22 @@ def test_iam_credentials_client_client_options(client_class, transport_class, tr with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id="octopus", @@ -499,48 +696,82 @@ def test_iam_credentials_client_client_options(client_class, transport_class, tr api_audience=None, ) # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc", "true"), - (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc", "false"), - (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest", "true"), - (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest", "false"), -]) -@mock.patch.object(IAMCredentialsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMCredentialsClient)) -@mock.patch.object(IAMCredentialsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMCredentialsAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc", "true"), + ( + IAMCredentialsAsyncClient, + transports.IAMCredentialsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc", "false"), + ( + IAMCredentialsAsyncClient, + transports.IAMCredentialsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest", "true"), + (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + IAMCredentialsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(IAMCredentialsClient), +) +@mock.patch.object( + IAMCredentialsAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(IAMCredentialsAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_iam_credentials_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_iam_credentials_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) else: expected_client_cert_source = client_cert_source_callback expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -559,12 +790,22 @@ def test_iam_credentials_client_mtls_env_auto(client_class, transport_class, tra # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -585,15 +826,22 @@ def test_iam_credentials_client_mtls_env_auto(client_class, transport_class, tra ) # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -603,19 +851,31 @@ def test_iam_credentials_client_mtls_env_auto(client_class, transport_class, tra ) -@pytest.mark.parametrize("client_class", [ - IAMCredentialsClient, IAMCredentialsAsyncClient -]) -@mock.patch.object(IAMCredentialsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IAMCredentialsClient)) -@mock.patch.object(IAMCredentialsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IAMCredentialsAsyncClient)) +@pytest.mark.parametrize( + "client_class", [IAMCredentialsClient, IAMCredentialsAsyncClient] +) +@mock.patch.object( + IAMCredentialsClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(IAMCredentialsClient), +) +@mock.patch.object( + IAMCredentialsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(IAMCredentialsAsyncClient), +) def test_iam_credentials_client_get_mtls_endpoint_and_cert_source(client_class): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) assert api_endpoint == mock_api_endpoint assert cert_source == mock_client_cert_source @@ -623,18 +883,25 @@ def test_iam_credentials_client_get_mtls_endpoint_and_cert_source(client_class): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) assert api_endpoint == mock_api_endpoint assert cert_source is None # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): if hasattr(google.auth.transport.mtls, "should_use_client_cert"): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options @@ -671,23 +938,23 @@ def test_iam_credentials_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). test_cases = [ @@ -718,23 +985,23 @@ def test_iam_credentials_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): @@ -750,16 +1017,27 @@ def test_iam_credentials_client_get_mtls_endpoint_and_cert_source(client_class): # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -769,27 +1047,50 @@ def test_iam_credentials_client_get_mtls_endpoint_and_cert_source(client_class): with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + -@pytest.mark.parametrize("client_class", [ - IAMCredentialsClient, IAMCredentialsAsyncClient -]) -@mock.patch.object(IAMCredentialsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMCredentialsClient)) -@mock.patch.object(IAMCredentialsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMCredentialsAsyncClient)) +@pytest.mark.parametrize( + "client_class", [IAMCredentialsClient, IAMCredentialsAsyncClient] +) +@mock.patch.object( + IAMCredentialsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(IAMCredentialsClient), +) +@mock.patch.object( + IAMCredentialsAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(IAMCredentialsAsyncClient), +) def test_iam_credentials_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = IAMCredentialsClient._DEFAULT_UNIVERSE - default_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", # use ClientOptions.api_endpoint as the api endpoint regardless. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) assert client.api_endpoint == api_override # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", @@ -812,11 +1113,19 @@ def test_iam_credentials_client_client_api_endpoint(client_class): universe_exists = hasattr(options, "universe_domain") if universe_exists: options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. @@ -824,27 +1133,40 @@ def test_iam_credentials_client_client_api_endpoint(client_class): if hasattr(options, "universe_domain"): delattr(options, "universe_domain") with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) assert client.api_endpoint == default_endpoint -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc"), - (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio"), - (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest"), -]) -def test_iam_credentials_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc"), + ( + IAMCredentialsAsyncClient, + transports.IAMCredentialsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest"), + ], +) +def test_iam_credentials_client_client_options_scopes( + client_class, transport_class, transport_name +): # Check the case scopes are provided. options = client_options.ClientOptions( scopes=["1", "2"], ) - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=["1", "2"], client_cert_source_for_mtls=None, quota_project_id=None, @@ -853,24 +1175,40 @@ def test_iam_credentials_client_client_options_scopes(client_class, transport_cl api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc", grpc_helpers), - (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest", None), -]) -def test_iam_credentials_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + IAMCredentialsClient, + transports.IAMCredentialsGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + IAMCredentialsAsyncClient, + transports.IAMCredentialsGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest", None), + ], +) +def test_iam_credentials_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) + options = client_options.ClientOptions(credentials_file="credentials.json") - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -879,11 +1217,14 @@ def test_iam_credentials_client_client_options_credentials_file(client_class, tr api_audience=None, ) + def test_iam_credentials_client_client_options_from_dict(): - with mock.patch('google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = IAMCredentialsClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -898,23 +1239,38 @@ def test_iam_credentials_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc", grpc_helpers), - (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_iam_credentials_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + IAMCredentialsClient, + transports.IAMCredentialsGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + IAMCredentialsAsyncClient, + transports.IAMCredentialsGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_iam_credentials_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) + options = client_options.ClientOptions(credentials_file="credentials.json") - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -924,13 +1280,13 @@ def test_iam_credentials_client_create_channel_credentials_file(client_class, tr ) # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): creds = ga_credentials.AnonymousCredentials() file_creds = ga_credentials.AnonymousCredentials() load_creds.return_value = (file_creds, None) @@ -941,9 +1297,7 @@ def test_iam_credentials_client_create_channel_credentials_file(client_class, tr credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), scopes=None, default_host="iamcredentials.googleapis.com", ssl_credentials=None, @@ -954,11 +1308,14 @@ def test_iam_credentials_client_create_channel_credentials_file(client_class, tr ) -@pytest.mark.parametrize("request_type", [ - common.GenerateAccessTokenRequest, - dict, -]) -def test_generate_access_token(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + common.GenerateAccessTokenRequest, + dict, + ], +) +def test_generate_access_token(request_type, transport: str = "grpc"): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -970,11 +1327,11 @@ def test_generate_access_token(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: + type(client.transport.generate_access_token), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = common.GenerateAccessTokenResponse( - access_token='access_token_value', + access_token="access_token_value", ) response = client.generate_access_token(request) @@ -986,7 +1343,7 @@ def test_generate_access_token(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, common.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' + assert response.access_token == "access_token_value" def test_generate_access_token_non_empty_request_with_auto_populated_field(): @@ -994,28 +1351,31 @@ def test_generate_access_token_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = common.GenerateAccessTokenRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.generate_access_token), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.generate_access_token(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == common.GenerateAccessTokenRequest( - name='name_value', + name="name_value", ) + def test_generate_access_token_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1030,12 +1390,19 @@ def test_generate_access_token_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.generate_access_token in client._transport._wrapped_methods + assert ( + client._transport.generate_access_token + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_access_token] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.generate_access_token] = ( + mock_rpc + ) request = {} client.generate_access_token(request) @@ -1048,8 +1415,11 @@ def test_generate_access_token_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_generate_access_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_generate_access_token_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1063,12 +1433,17 @@ async def test_generate_access_token_async_use_cached_wrapped_rpc(transport: str wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.generate_access_token in client._client._transport._wrapped_methods + assert ( + client._client._transport.generate_access_token + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.generate_access_token] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.generate_access_token + ] = mock_rpc request = {} await client.generate_access_token(request) @@ -1082,8 +1457,11 @@ async def test_generate_access_token_async_use_cached_wrapped_rpc(transport: str assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_generate_access_token_async(transport: str = 'grpc_asyncio', request_type=common.GenerateAccessTokenRequest): +async def test_generate_access_token_async( + transport: str = "grpc_asyncio", request_type=common.GenerateAccessTokenRequest +): client = IAMCredentialsAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1095,12 +1473,14 @@ async def test_generate_access_token_async(transport: str = 'grpc_asyncio', requ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: + type(client.transport.generate_access_token), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(common.GenerateAccessTokenResponse( - access_token='access_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.GenerateAccessTokenResponse( + access_token="access_token_value", + ) + ) response = await client.generate_access_token(request) # Establish that the underlying gRPC stub method was called. @@ -1111,13 +1491,14 @@ async def test_generate_access_token_async(transport: str = 'grpc_asyncio', requ # Establish that the response is the type that we expect. assert isinstance(response, common.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' + assert response.access_token == "access_token_value" @pytest.mark.asyncio async def test_generate_access_token_async_from_dict(): await test_generate_access_token_async(request_type=dict) + def test_generate_access_token_field_headers(): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1127,12 +1508,12 @@ def test_generate_access_token_field_headers(): # a field header. Set these to a non-empty value. request = common.GenerateAccessTokenRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: + type(client.transport.generate_access_token), "__call__" + ) as call: call.return_value = common.GenerateAccessTokenResponse() client.generate_access_token(request) @@ -1144,9 +1525,9 @@ def test_generate_access_token_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1159,13 +1540,15 @@ async def test_generate_access_token_field_headers_async(): # a field header. Set these to a non-empty value. request = common.GenerateAccessTokenRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.GenerateAccessTokenResponse()) + type(client.transport.generate_access_token), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.GenerateAccessTokenResponse() + ) await client.generate_access_token(request) # Establish that the underlying gRPC stub method was called. @@ -1176,9 +1559,9 @@ async def test_generate_access_token_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_generate_access_token_flattened(): @@ -1188,16 +1571,16 @@ def test_generate_access_token_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: + type(client.transport.generate_access_token), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = common.GenerateAccessTokenResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.generate_access_token( - name='name_value', - delegates=['delegates_value'], - scope=['scope_value'], + name="name_value", + delegates=["delegates_value"], + scope=["scope_value"], lifetime=duration_pb2.Duration(seconds=751), ) @@ -1206,15 +1589,17 @@ def test_generate_access_token_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val arg = args[0].delegates - mock_val = ['delegates_value'] + mock_val = ["delegates_value"] assert arg == mock_val arg = args[0].scope - mock_val = ['scope_value'] + mock_val = ["scope_value"] assert arg == mock_val - assert DurationRule().to_proto(args[0].lifetime) == duration_pb2.Duration(seconds=751) + assert DurationRule().to_proto(args[0].lifetime) == duration_pb2.Duration( + seconds=751 + ) def test_generate_access_token_flattened_error(): @@ -1227,12 +1612,13 @@ def test_generate_access_token_flattened_error(): with pytest.raises(ValueError): client.generate_access_token( common.GenerateAccessTokenRequest(), - name='name_value', - delegates=['delegates_value'], - scope=['scope_value'], + name="name_value", + delegates=["delegates_value"], + scope=["scope_value"], lifetime=duration_pb2.Duration(seconds=751), ) + @pytest.mark.asyncio async def test_generate_access_token_flattened_async(): client = IAMCredentialsAsyncClient( @@ -1241,18 +1627,20 @@ async def test_generate_access_token_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: + type(client.transport.generate_access_token), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = common.GenerateAccessTokenResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.GenerateAccessTokenResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.GenerateAccessTokenResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.generate_access_token( - name='name_value', - delegates=['delegates_value'], - scope=['scope_value'], + name="name_value", + delegates=["delegates_value"], + scope=["scope_value"], lifetime=duration_pb2.Duration(seconds=751), ) @@ -1261,15 +1649,18 @@ async def test_generate_access_token_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val arg = args[0].delegates - mock_val = ['delegates_value'] + mock_val = ["delegates_value"] assert arg == mock_val arg = args[0].scope - mock_val = ['scope_value'] + mock_val = ["scope_value"] assert arg == mock_val - assert DurationRule().to_proto(args[0].lifetime) == duration_pb2.Duration(seconds=751) + assert DurationRule().to_proto(args[0].lifetime) == duration_pb2.Duration( + seconds=751 + ) + @pytest.mark.asyncio async def test_generate_access_token_flattened_error_async(): @@ -1282,18 +1673,21 @@ async def test_generate_access_token_flattened_error_async(): with pytest.raises(ValueError): await client.generate_access_token( common.GenerateAccessTokenRequest(), - name='name_value', - delegates=['delegates_value'], - scope=['scope_value'], + name="name_value", + delegates=["delegates_value"], + scope=["scope_value"], lifetime=duration_pb2.Duration(seconds=751), ) -@pytest.mark.parametrize("request_type", [ - common.GenerateIdTokenRequest, - dict, -]) -def test_generate_id_token(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + common.GenerateIdTokenRequest, + dict, + ], +) +def test_generate_id_token(request_type, transport: str = "grpc"): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1305,11 +1699,11 @@ def test_generate_id_token(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), - '__call__') as call: + type(client.transport.generate_id_token), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = common.GenerateIdTokenResponse( - token='token_value', + token="token_value", ) response = client.generate_id_token(request) @@ -1321,7 +1715,7 @@ def test_generate_id_token(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, common.GenerateIdTokenResponse) - assert response.token == 'token_value' + assert response.token == "token_value" def test_generate_id_token_non_empty_request_with_auto_populated_field(): @@ -1329,30 +1723,33 @@ def test_generate_id_token_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = common.GenerateIdTokenRequest( - name='name_value', - audience='audience_value', + name="name_value", + audience="audience_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.generate_id_token), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.generate_id_token(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == common.GenerateIdTokenRequest( - name='name_value', - audience='audience_value', + name="name_value", + audience="audience_value", ) + def test_generate_id_token_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1371,8 +1768,12 @@ def test_generate_id_token_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_id_token] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.generate_id_token] = ( + mock_rpc + ) request = {} client.generate_id_token(request) @@ -1385,8 +1786,11 @@ def test_generate_id_token_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_generate_id_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_generate_id_token_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1400,12 +1804,17 @@ async def test_generate_id_token_async_use_cached_wrapped_rpc(transport: str = " wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.generate_id_token in client._client._transport._wrapped_methods + assert ( + client._client._transport.generate_id_token + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.generate_id_token] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.generate_id_token + ] = mock_rpc request = {} await client.generate_id_token(request) @@ -1419,8 +1828,11 @@ async def test_generate_id_token_async_use_cached_wrapped_rpc(transport: str = " assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_generate_id_token_async(transport: str = 'grpc_asyncio', request_type=common.GenerateIdTokenRequest): +async def test_generate_id_token_async( + transport: str = "grpc_asyncio", request_type=common.GenerateIdTokenRequest +): client = IAMCredentialsAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1432,12 +1844,14 @@ async def test_generate_id_token_async(transport: str = 'grpc_asyncio', request_ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), - '__call__') as call: + type(client.transport.generate_id_token), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(common.GenerateIdTokenResponse( - token='token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.GenerateIdTokenResponse( + token="token_value", + ) + ) response = await client.generate_id_token(request) # Establish that the underlying gRPC stub method was called. @@ -1448,13 +1862,14 @@ async def test_generate_id_token_async(transport: str = 'grpc_asyncio', request_ # Establish that the response is the type that we expect. assert isinstance(response, common.GenerateIdTokenResponse) - assert response.token == 'token_value' + assert response.token == "token_value" @pytest.mark.asyncio async def test_generate_id_token_async_from_dict(): await test_generate_id_token_async(request_type=dict) + def test_generate_id_token_field_headers(): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1464,12 +1879,12 @@ def test_generate_id_token_field_headers(): # a field header. Set these to a non-empty value. request = common.GenerateIdTokenRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), - '__call__') as call: + type(client.transport.generate_id_token), "__call__" + ) as call: call.return_value = common.GenerateIdTokenResponse() client.generate_id_token(request) @@ -1481,9 +1896,9 @@ def test_generate_id_token_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1496,13 +1911,15 @@ async def test_generate_id_token_field_headers_async(): # a field header. Set these to a non-empty value. request = common.GenerateIdTokenRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.GenerateIdTokenResponse()) + type(client.transport.generate_id_token), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.GenerateIdTokenResponse() + ) await client.generate_id_token(request) # Establish that the underlying gRPC stub method was called. @@ -1513,9 +1930,9 @@ async def test_generate_id_token_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_generate_id_token_flattened(): @@ -1525,16 +1942,16 @@ def test_generate_id_token_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), - '__call__') as call: + type(client.transport.generate_id_token), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = common.GenerateIdTokenResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.generate_id_token( - name='name_value', - delegates=['delegates_value'], - audience='audience_value', + name="name_value", + delegates=["delegates_value"], + audience="audience_value", include_email=True, ) @@ -1543,13 +1960,13 @@ def test_generate_id_token_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val arg = args[0].delegates - mock_val = ['delegates_value'] + mock_val = ["delegates_value"] assert arg == mock_val arg = args[0].audience - mock_val = 'audience_value' + mock_val = "audience_value" assert arg == mock_val arg = args[0].include_email mock_val = True @@ -1566,12 +1983,13 @@ def test_generate_id_token_flattened_error(): with pytest.raises(ValueError): client.generate_id_token( common.GenerateIdTokenRequest(), - name='name_value', - delegates=['delegates_value'], - audience='audience_value', + name="name_value", + delegates=["delegates_value"], + audience="audience_value", include_email=True, ) + @pytest.mark.asyncio async def test_generate_id_token_flattened_async(): client = IAMCredentialsAsyncClient( @@ -1580,18 +1998,20 @@ async def test_generate_id_token_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), - '__call__') as call: + type(client.transport.generate_id_token), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = common.GenerateIdTokenResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.GenerateIdTokenResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.GenerateIdTokenResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.generate_id_token( - name='name_value', - delegates=['delegates_value'], - audience='audience_value', + name="name_value", + delegates=["delegates_value"], + audience="audience_value", include_email=True, ) @@ -1600,18 +2020,19 @@ async def test_generate_id_token_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val arg = args[0].delegates - mock_val = ['delegates_value'] + mock_val = ["delegates_value"] assert arg == mock_val arg = args[0].audience - mock_val = 'audience_value' + mock_val = "audience_value" assert arg == mock_val arg = args[0].include_email mock_val = True assert arg == mock_val + @pytest.mark.asyncio async def test_generate_id_token_flattened_error_async(): client = IAMCredentialsAsyncClient( @@ -1623,18 +2044,21 @@ async def test_generate_id_token_flattened_error_async(): with pytest.raises(ValueError): await client.generate_id_token( common.GenerateIdTokenRequest(), - name='name_value', - delegates=['delegates_value'], - audience='audience_value', + name="name_value", + delegates=["delegates_value"], + audience="audience_value", include_email=True, ) -@pytest.mark.parametrize("request_type", [ - common.SignBlobRequest, - dict, -]) -def test_sign_blob(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + common.SignBlobRequest, + dict, + ], +) +def test_sign_blob(request_type, transport: str = "grpc"): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1645,13 +2069,11 @@ def test_sign_blob(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.sign_blob), - '__call__') as call: + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = common.SignBlobResponse( - key_id='key_id_value', - signed_blob=b'signed_blob_blob', + key_id="key_id_value", + signed_blob=b"signed_blob_blob", ) response = client.sign_blob(request) @@ -1663,8 +2085,8 @@ def test_sign_blob(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, common.SignBlobResponse) - assert response.key_id == 'key_id_value' - assert response.signed_blob == b'signed_blob_blob' + assert response.key_id == "key_id_value" + assert response.signed_blob == b"signed_blob_blob" def test_sign_blob_non_empty_request_with_auto_populated_field(): @@ -1672,28 +2094,29 @@ def test_sign_blob_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = common.SignBlobRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.sign_blob), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.sign_blob(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == common.SignBlobRequest( - name='name_value', + name="name_value", ) + def test_sign_blob_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1712,7 +2135,9 @@ def test_sign_blob_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.sign_blob] = mock_rpc request = {} client.sign_blob(request) @@ -1726,6 +2151,7 @@ def test_sign_blob_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio async def test_sign_blob_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1741,12 +2167,17 @@ async def test_sign_blob_async_use_cached_wrapped_rpc(transport: str = "grpc_asy wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.sign_blob in client._client._transport._wrapped_methods + assert ( + client._client._transport.sign_blob + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.sign_blob] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.sign_blob + ] = mock_rpc request = {} await client.sign_blob(request) @@ -1760,8 +2191,11 @@ async def test_sign_blob_async_use_cached_wrapped_rpc(transport: str = "grpc_asy assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_sign_blob_async(transport: str = 'grpc_asyncio', request_type=common.SignBlobRequest): +async def test_sign_blob_async( + transport: str = "grpc_asyncio", request_type=common.SignBlobRequest +): client = IAMCredentialsAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1772,14 +2206,14 @@ async def test_sign_blob_async(transport: str = 'grpc_asyncio', request_type=com request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.sign_blob), - '__call__') as call: + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(common.SignBlobResponse( - key_id='key_id_value', - signed_blob=b'signed_blob_blob', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.SignBlobResponse( + key_id="key_id_value", + signed_blob=b"signed_blob_blob", + ) + ) response = await client.sign_blob(request) # Establish that the underlying gRPC stub method was called. @@ -1790,14 +2224,15 @@ async def test_sign_blob_async(transport: str = 'grpc_asyncio', request_type=com # Establish that the response is the type that we expect. assert isinstance(response, common.SignBlobResponse) - assert response.key_id == 'key_id_value' - assert response.signed_blob == b'signed_blob_blob' + assert response.key_id == "key_id_value" + assert response.signed_blob == b"signed_blob_blob" @pytest.mark.asyncio async def test_sign_blob_async_from_dict(): await test_sign_blob_async(request_type=dict) + def test_sign_blob_field_headers(): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1807,12 +2242,10 @@ def test_sign_blob_field_headers(): # a field header. Set these to a non-empty value. request = common.SignBlobRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.sign_blob), - '__call__') as call: + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: call.return_value = common.SignBlobResponse() client.sign_blob(request) @@ -1824,9 +2257,9 @@ def test_sign_blob_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1839,13 +2272,13 @@ async def test_sign_blob_field_headers_async(): # a field header. Set these to a non-empty value. request = common.SignBlobRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.sign_blob), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SignBlobResponse()) + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.SignBlobResponse() + ) await client.sign_blob(request) # Establish that the underlying gRPC stub method was called. @@ -1856,9 +2289,9 @@ async def test_sign_blob_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_sign_blob_flattened(): @@ -1867,17 +2300,15 @@ def test_sign_blob_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.sign_blob), - '__call__') as call: + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = common.SignBlobResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.sign_blob( - name='name_value', - delegates=['delegates_value'], - payload=b'payload_blob', + name="name_value", + delegates=["delegates_value"], + payload=b"payload_blob", ) # Establish that the underlying call was made with the expected @@ -1885,13 +2316,13 @@ def test_sign_blob_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val arg = args[0].delegates - mock_val = ['delegates_value'] + mock_val = ["delegates_value"] assert arg == mock_val arg = args[0].payload - mock_val = b'payload_blob' + mock_val = b"payload_blob" assert arg == mock_val @@ -1905,11 +2336,12 @@ def test_sign_blob_flattened_error(): with pytest.raises(ValueError): client.sign_blob( common.SignBlobRequest(), - name='name_value', - delegates=['delegates_value'], - payload=b'payload_blob', + name="name_value", + delegates=["delegates_value"], + payload=b"payload_blob", ) + @pytest.mark.asyncio async def test_sign_blob_flattened_async(): client = IAMCredentialsAsyncClient( @@ -1917,19 +2349,19 @@ async def test_sign_blob_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.sign_blob), - '__call__') as call: + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = common.SignBlobResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SignBlobResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.SignBlobResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.sign_blob( - name='name_value', - delegates=['delegates_value'], - payload=b'payload_blob', + name="name_value", + delegates=["delegates_value"], + payload=b"payload_blob", ) # Establish that the underlying call was made with the expected @@ -1937,15 +2369,16 @@ async def test_sign_blob_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val arg = args[0].delegates - mock_val = ['delegates_value'] + mock_val = ["delegates_value"] assert arg == mock_val arg = args[0].payload - mock_val = b'payload_blob' + mock_val = b"payload_blob" assert arg == mock_val + @pytest.mark.asyncio async def test_sign_blob_flattened_error_async(): client = IAMCredentialsAsyncClient( @@ -1957,17 +2390,20 @@ async def test_sign_blob_flattened_error_async(): with pytest.raises(ValueError): await client.sign_blob( common.SignBlobRequest(), - name='name_value', - delegates=['delegates_value'], - payload=b'payload_blob', + name="name_value", + delegates=["delegates_value"], + payload=b"payload_blob", ) -@pytest.mark.parametrize("request_type", [ - common.SignJwtRequest, - dict, -]) -def test_sign_jwt(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + common.SignJwtRequest, + dict, + ], +) +def test_sign_jwt(request_type, transport: str = "grpc"): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1978,13 +2414,11 @@ def test_sign_jwt(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.sign_jwt), - '__call__') as call: + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = common.SignJwtResponse( - key_id='key_id_value', - signed_jwt='signed_jwt_value', + key_id="key_id_value", + signed_jwt="signed_jwt_value", ) response = client.sign_jwt(request) @@ -1996,8 +2430,8 @@ def test_sign_jwt(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, common.SignJwtResponse) - assert response.key_id == 'key_id_value' - assert response.signed_jwt == 'signed_jwt_value' + assert response.key_id == "key_id_value" + assert response.signed_jwt == "signed_jwt_value" def test_sign_jwt_non_empty_request_with_auto_populated_field(): @@ -2005,30 +2439,31 @@ def test_sign_jwt_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = common.SignJwtRequest( - name='name_value', - payload='payload_value', + name="name_value", + payload="payload_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.sign_jwt), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.sign_jwt(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == common.SignJwtRequest( - name='name_value', - payload='payload_value', + name="name_value", + payload="payload_value", ) + def test_sign_jwt_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2047,7 +2482,9 @@ def test_sign_jwt_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.sign_jwt] = mock_rpc request = {} client.sign_jwt(request) @@ -2061,6 +2498,7 @@ def test_sign_jwt_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio async def test_sign_jwt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -2076,12 +2514,17 @@ async def test_sign_jwt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.sign_jwt in client._client._transport._wrapped_methods + assert ( + client._client._transport.sign_jwt + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.sign_jwt] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.sign_jwt + ] = mock_rpc request = {} await client.sign_jwt(request) @@ -2095,8 +2538,11 @@ async def test_sign_jwt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_sign_jwt_async(transport: str = 'grpc_asyncio', request_type=common.SignJwtRequest): +async def test_sign_jwt_async( + transport: str = "grpc_asyncio", request_type=common.SignJwtRequest +): client = IAMCredentialsAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2107,14 +2553,14 @@ async def test_sign_jwt_async(transport: str = 'grpc_asyncio', request_type=comm request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.sign_jwt), - '__call__') as call: + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(common.SignJwtResponse( - key_id='key_id_value', - signed_jwt='signed_jwt_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.SignJwtResponse( + key_id="key_id_value", + signed_jwt="signed_jwt_value", + ) + ) response = await client.sign_jwt(request) # Establish that the underlying gRPC stub method was called. @@ -2125,14 +2571,15 @@ async def test_sign_jwt_async(transport: str = 'grpc_asyncio', request_type=comm # Establish that the response is the type that we expect. assert isinstance(response, common.SignJwtResponse) - assert response.key_id == 'key_id_value' - assert response.signed_jwt == 'signed_jwt_value' + assert response.key_id == "key_id_value" + assert response.signed_jwt == "signed_jwt_value" @pytest.mark.asyncio async def test_sign_jwt_async_from_dict(): await test_sign_jwt_async(request_type=dict) + def test_sign_jwt_field_headers(): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2142,12 +2589,10 @@ def test_sign_jwt_field_headers(): # a field header. Set these to a non-empty value. request = common.SignJwtRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.sign_jwt), - '__call__') as call: + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: call.return_value = common.SignJwtResponse() client.sign_jwt(request) @@ -2159,9 +2604,9 @@ def test_sign_jwt_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -2174,13 +2619,13 @@ async def test_sign_jwt_field_headers_async(): # a field header. Set these to a non-empty value. request = common.SignJwtRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.sign_jwt), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SignJwtResponse()) + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.SignJwtResponse() + ) await client.sign_jwt(request) # Establish that the underlying gRPC stub method was called. @@ -2191,9 +2636,9 @@ async def test_sign_jwt_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_sign_jwt_flattened(): @@ -2202,17 +2647,15 @@ def test_sign_jwt_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.sign_jwt), - '__call__') as call: + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = common.SignJwtResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.sign_jwt( - name='name_value', - delegates=['delegates_value'], - payload='payload_value', + name="name_value", + delegates=["delegates_value"], + payload="payload_value", ) # Establish that the underlying call was made with the expected @@ -2220,13 +2663,13 @@ def test_sign_jwt_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val arg = args[0].delegates - mock_val = ['delegates_value'] + mock_val = ["delegates_value"] assert arg == mock_val arg = args[0].payload - mock_val = 'payload_value' + mock_val = "payload_value" assert arg == mock_val @@ -2240,11 +2683,12 @@ def test_sign_jwt_flattened_error(): with pytest.raises(ValueError): client.sign_jwt( common.SignJwtRequest(), - name='name_value', - delegates=['delegates_value'], - payload='payload_value', + name="name_value", + delegates=["delegates_value"], + payload="payload_value", ) + @pytest.mark.asyncio async def test_sign_jwt_flattened_async(): client = IAMCredentialsAsyncClient( @@ -2252,19 +2696,19 @@ async def test_sign_jwt_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.sign_jwt), - '__call__') as call: + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = common.SignJwtResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SignJwtResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.SignJwtResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.sign_jwt( - name='name_value', - delegates=['delegates_value'], - payload='payload_value', + name="name_value", + delegates=["delegates_value"], + payload="payload_value", ) # Establish that the underlying call was made with the expected @@ -2272,15 +2716,16 @@ async def test_sign_jwt_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val arg = args[0].delegates - mock_val = ['delegates_value'] + mock_val = ["delegates_value"] assert arg == mock_val arg = args[0].payload - mock_val = 'payload_value' + mock_val = "payload_value" assert arg == mock_val + @pytest.mark.asyncio async def test_sign_jwt_flattened_error_async(): client = IAMCredentialsAsyncClient( @@ -2292,9 +2737,9 @@ async def test_sign_jwt_flattened_error_async(): with pytest.raises(ValueError): await client.sign_jwt( common.SignJwtRequest(), - name='name_value', - delegates=['delegates_value'], - payload='payload_value', + name="name_value", + delegates=["delegates_value"], + payload="payload_value", ) @@ -2312,12 +2757,19 @@ def test_generate_access_token_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.generate_access_token in client._transport._wrapped_methods + assert ( + client._transport.generate_access_token + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_access_token] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.generate_access_token] = ( + mock_rpc + ) request = {} client.generate_access_token(request) @@ -2332,7 +2784,9 @@ def test_generate_access_token_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_generate_access_token_rest_required_fields(request_type=common.GenerateAccessTokenRequest): +def test_generate_access_token_rest_required_fields( + request_type=common.GenerateAccessTokenRequest, +): transport_class = transports.IAMCredentialsRestTransport request_init = {} @@ -2340,53 +2794,56 @@ def test_generate_access_token_rest_required_fields(request_type=common.Generate request_init["scope"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_access_token._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' - jsonified_request["scope"] = 'scope_value' + jsonified_request["name"] = "name_value" + jsonified_request["scope"] = "scope_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_access_token._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" assert "scope" in jsonified_request - assert jsonified_request["scope"] == 'scope_value' + assert jsonified_request["scope"] == "scope_value" client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = common.GenerateAccessTokenResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -2396,23 +2853,32 @@ def test_generate_access_token_rest_required_fields(request_type=common.Generate return_value = common.GenerateAccessTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.generate_access_token(request) - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_generate_access_token_rest_unset_required_fields(): - transport = transports.IAMCredentialsRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.IAMCredentialsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.generate_access_token._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "scope", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "scope", + ) + ) + ) def test_generate_access_token_rest_flattened(): @@ -2422,18 +2888,18 @@ def test_generate_access_token_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = common.GenerateAccessTokenResponse() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/serviceAccounts/sample2'} + sample_request = {"name": "projects/sample1/serviceAccounts/sample2"} # get truthy value for each flattened field mock_args = dict( - name='name_value', - delegates=['delegates_value'], - scope=['scope_value'], + name="name_value", + delegates=["delegates_value"], + scope=["scope_value"], lifetime=duration_pb2.Duration(seconds=751), ) mock_args.update(sample_request) @@ -2444,7 +2910,7 @@ def test_generate_access_token_rest_flattened(): # Convert return value to protobuf type return_value = common.GenerateAccessTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2454,10 +2920,14 @@ def test_generate_access_token_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/serviceAccounts/*}:generateAccessToken" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{name=projects/*/serviceAccounts/*}:generateAccessToken" + % client.transport._host, + args[1], + ) -def test_generate_access_token_rest_flattened_error(transport: str = 'rest'): +def test_generate_access_token_rest_flattened_error(transport: str = "rest"): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2468,9 +2938,9 @@ def test_generate_access_token_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.generate_access_token( common.GenerateAccessTokenRequest(), - name='name_value', - delegates=['delegates_value'], - scope=['scope_value'], + name="name_value", + delegates=["delegates_value"], + scope=["scope_value"], lifetime=duration_pb2.Duration(seconds=751), ) @@ -2493,8 +2963,12 @@ def test_generate_id_token_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_id_token] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.generate_id_token] = ( + mock_rpc + ) request = {} client.generate_id_token(request) @@ -2509,7 +2983,9 @@ def test_generate_id_token_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_generate_id_token_rest_required_fields(request_type=common.GenerateIdTokenRequest): +def test_generate_id_token_rest_required_fields( + request_type=common.GenerateIdTokenRequest, +): transport_class = transports.IAMCredentialsRestTransport request_init = {} @@ -2517,53 +2993,56 @@ def test_generate_id_token_rest_required_fields(request_type=common.GenerateIdTo request_init["audience"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_id_token._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_id_token._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' - jsonified_request["audience"] = 'audience_value' + jsonified_request["name"] = "name_value" + jsonified_request["audience"] = "audience_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_id_token._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_id_token._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" assert "audience" in jsonified_request - assert jsonified_request["audience"] == 'audience_value' + assert jsonified_request["audience"] == "audience_value" client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = common.GenerateIdTokenResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -2573,23 +3052,32 @@ def test_generate_id_token_rest_required_fields(request_type=common.GenerateIdTo return_value = common.GenerateIdTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.generate_id_token(request) - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_generate_id_token_rest_unset_required_fields(): - transport = transports.IAMCredentialsRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.IAMCredentialsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.generate_id_token._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "audience", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "audience", + ) + ) + ) def test_generate_id_token_rest_flattened(): @@ -2599,18 +3087,18 @@ def test_generate_id_token_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = common.GenerateIdTokenResponse() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/serviceAccounts/sample2'} + sample_request = {"name": "projects/sample1/serviceAccounts/sample2"} # get truthy value for each flattened field mock_args = dict( - name='name_value', - delegates=['delegates_value'], - audience='audience_value', + name="name_value", + delegates=["delegates_value"], + audience="audience_value", include_email=True, ) mock_args.update(sample_request) @@ -2621,7 +3109,7 @@ def test_generate_id_token_rest_flattened(): # Convert return value to protobuf type return_value = common.GenerateIdTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2631,10 +3119,14 @@ def test_generate_id_token_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/serviceAccounts/*}:generateIdToken" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{name=projects/*/serviceAccounts/*}:generateIdToken" + % client.transport._host, + args[1], + ) -def test_generate_id_token_rest_flattened_error(transport: str = 'rest'): +def test_generate_id_token_rest_flattened_error(transport: str = "rest"): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2645,9 +3137,9 @@ def test_generate_id_token_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.generate_id_token( common.GenerateIdTokenRequest(), - name='name_value', - delegates=['delegates_value'], - audience='audience_value', + name="name_value", + delegates=["delegates_value"], + audience="audience_value", include_email=True, ) @@ -2670,7 +3162,9 @@ def test_sign_blob_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.sign_blob] = mock_rpc request = {} @@ -2691,56 +3185,59 @@ def test_sign_blob_rest_required_fields(request_type=common.SignBlobRequest): request_init = {} request_init["name"] = "" - request_init["payload"] = b'' + request_init["payload"] = b"" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).sign_blob._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).sign_blob._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' - jsonified_request["payload"] = b'payload_blob' + jsonified_request["name"] = "name_value" + jsonified_request["payload"] = b"payload_blob" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).sign_blob._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).sign_blob._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" assert "payload" in jsonified_request - assert jsonified_request["payload"] == b'payload_blob' + assert jsonified_request["payload"] == b"payload_blob" client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = common.SignBlobResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -2750,23 +3247,32 @@ def test_sign_blob_rest_required_fields(request_type=common.SignBlobRequest): return_value = common.SignBlobResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.sign_blob(request) - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_sign_blob_rest_unset_required_fields(): - transport = transports.IAMCredentialsRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.IAMCredentialsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.sign_blob._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "payload", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "payload", + ) + ) + ) def test_sign_blob_rest_flattened(): @@ -2776,18 +3282,18 @@ def test_sign_blob_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = common.SignBlobResponse() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/serviceAccounts/sample2'} + sample_request = {"name": "projects/sample1/serviceAccounts/sample2"} # get truthy value for each flattened field mock_args = dict( - name='name_value', - delegates=['delegates_value'], - payload=b'payload_blob', + name="name_value", + delegates=["delegates_value"], + payload=b"payload_blob", ) mock_args.update(sample_request) @@ -2797,7 +3303,7 @@ def test_sign_blob_rest_flattened(): # Convert return value to protobuf type return_value = common.SignBlobResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2807,10 +3313,14 @@ def test_sign_blob_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/serviceAccounts/*}:signBlob" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{name=projects/*/serviceAccounts/*}:signBlob" + % client.transport._host, + args[1], + ) -def test_sign_blob_rest_flattened_error(transport: str = 'rest'): +def test_sign_blob_rest_flattened_error(transport: str = "rest"): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2821,9 +3331,9 @@ def test_sign_blob_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.sign_blob( common.SignBlobRequest(), - name='name_value', - delegates=['delegates_value'], - payload=b'payload_blob', + name="name_value", + delegates=["delegates_value"], + payload=b"payload_blob", ) @@ -2845,7 +3355,9 @@ def test_sign_jwt_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.sign_jwt] = mock_rpc request = {} @@ -2869,53 +3381,56 @@ def test_sign_jwt_rest_required_fields(request_type=common.SignJwtRequest): request_init["payload"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).sign_jwt._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).sign_jwt._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' - jsonified_request["payload"] = 'payload_value' + jsonified_request["name"] = "name_value" + jsonified_request["payload"] = "payload_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).sign_jwt._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).sign_jwt._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" assert "payload" in jsonified_request - assert jsonified_request["payload"] == 'payload_value' + assert jsonified_request["payload"] == "payload_value" client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = common.SignJwtResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -2925,23 +3440,32 @@ def test_sign_jwt_rest_required_fields(request_type=common.SignJwtRequest): return_value = common.SignJwtResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.sign_jwt(request) - expected_params = [ - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_sign_jwt_rest_unset_required_fields(): - transport = transports.IAMCredentialsRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.IAMCredentialsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.sign_jwt._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "payload", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "payload", + ) + ) + ) def test_sign_jwt_rest_flattened(): @@ -2951,18 +3475,18 @@ def test_sign_jwt_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = common.SignJwtResponse() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/serviceAccounts/sample2'} + sample_request = {"name": "projects/sample1/serviceAccounts/sample2"} # get truthy value for each flattened field mock_args = dict( - name='name_value', - delegates=['delegates_value'], - payload='payload_value', + name="name_value", + delegates=["delegates_value"], + payload="payload_value", ) mock_args.update(sample_request) @@ -2972,7 +3496,7 @@ def test_sign_jwt_rest_flattened(): # Convert return value to protobuf type return_value = common.SignJwtResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2982,10 +3506,14 @@ def test_sign_jwt_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/serviceAccounts/*}:signJwt" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{name=projects/*/serviceAccounts/*}:signJwt" + % client.transport._host, + args[1], + ) -def test_sign_jwt_rest_flattened_error(transport: str = 'rest'): +def test_sign_jwt_rest_flattened_error(transport: str = "rest"): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2996,9 +3524,9 @@ def test_sign_jwt_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.sign_jwt( common.SignJwtRequest(), - name='name_value', - delegates=['delegates_value'], - payload='payload_value', + name="name_value", + delegates=["delegates_value"], + payload="payload_value", ) @@ -3040,8 +3568,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = IAMCredentialsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() + client_options=options, credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. @@ -3063,6 +3590,7 @@ def test_transport_instance(): client = IAMCredentialsClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.IAMCredentialsGrpcTransport( @@ -3077,18 +3605,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.IAMCredentialsGrpcTransport, - transports.IAMCredentialsGrpcAsyncIOTransport, - transports.IAMCredentialsRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.IAMCredentialsGrpcTransport, + transports.IAMCredentialsGrpcAsyncIOTransport, + transports.IAMCredentialsRestTransport, + ], +) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() + def test_transport_kind_grpc(): transport = IAMCredentialsClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -3098,8 +3631,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -3114,8 +3646,8 @@ def test_generate_access_token_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: + type(client.transport.generate_access_token), "__call__" + ) as call: call.return_value = common.GenerateAccessTokenResponse() client.generate_access_token(request=None) @@ -3137,8 +3669,8 @@ def test_generate_id_token_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), - '__call__') as call: + type(client.transport.generate_id_token), "__call__" + ) as call: call.return_value = common.GenerateIdTokenResponse() client.generate_id_token(request=None) @@ -3159,9 +3691,7 @@ def test_sign_blob_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.sign_blob), - '__call__') as call: + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: call.return_value = common.SignBlobResponse() client.sign_blob(request=None) @@ -3182,9 +3712,7 @@ def test_sign_jwt_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.sign_jwt), - '__call__') as call: + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: call.return_value = common.SignJwtResponse() client.sign_jwt(request=None) @@ -3205,8 +3733,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = IAMCredentialsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -3222,12 +3749,14 @@ async def test_generate_access_token_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: + type(client.transport.generate_access_token), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.GenerateAccessTokenResponse( - access_token='access_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.GenerateAccessTokenResponse( + access_token="access_token_value", + ) + ) await client.generate_access_token(request=None) # Establish that the underlying stub method was called. @@ -3249,12 +3778,14 @@ async def test_generate_id_token_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), - '__call__') as call: + type(client.transport.generate_id_token), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.GenerateIdTokenResponse( - token='token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.GenerateIdTokenResponse( + token="token_value", + ) + ) await client.generate_id_token(request=None) # Establish that the underlying stub method was called. @@ -3275,14 +3806,14 @@ async def test_sign_blob_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.sign_blob), - '__call__') as call: + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SignBlobResponse( - key_id='key_id_value', - signed_blob=b'signed_blob_blob', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.SignBlobResponse( + key_id="key_id_value", + signed_blob=b"signed_blob_blob", + ) + ) await client.sign_blob(request=None) # Establish that the underlying stub method was called. @@ -3303,14 +3834,14 @@ async def test_sign_jwt_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.sign_jwt), - '__call__') as call: + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SignJwtResponse( - key_id='key_id_value', - signed_jwt='signed_jwt_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + common.SignJwtResponse( + key_id="key_id_value", + signed_jwt="signed_jwt_value", + ) + ) await client.sign_jwt(request=None) # Establish that the underlying stub method was called. @@ -3328,20 +3859,24 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_generate_access_token_rest_bad_request(request_type=common.GenerateAccessTokenRequest): +def test_generate_access_token_rest_bad_request( + request_type=common.GenerateAccessTokenRequest, +): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/serviceAccounts/sample2'} + request_init = {"name": "projects/sample1/serviceAccounts/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -3350,25 +3885,27 @@ def test_generate_access_token_rest_bad_request(request_type=common.GenerateAcce client.generate_access_token(request) -@pytest.mark.parametrize("request_type", [ - common.GenerateAccessTokenRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + common.GenerateAccessTokenRequest, + dict, + ], +) def test_generate_access_token_rest_call_success(request_type): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/serviceAccounts/sample2'} + request_init = {"name": "projects/sample1/serviceAccounts/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = common.GenerateAccessTokenResponse( - access_token='access_token_value', + access_token="access_token_value", ) # Wrap the value into a proper Response obj @@ -3378,33 +3915,46 @@ def test_generate_access_token_rest_call_success(request_type): # Convert return value to protobuf type return_value = common.GenerateAccessTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.generate_access_token(request) # Establish that the response is the type that we expect. assert isinstance(response, common.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' + assert response.access_token == "access_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_generate_access_token_rest_interceptors(null_interceptor): transport = transports.IAMCredentialsRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IAMCredentialsRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.IAMCredentialsRestInterceptor(), + ) client = IAMCredentialsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.IAMCredentialsRestInterceptor, "post_generate_access_token") as post, \ - mock.patch.object(transports.IAMCredentialsRestInterceptor, "post_generate_access_token_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.IAMCredentialsRestInterceptor, "pre_generate_access_token") as pre: + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.IAMCredentialsRestInterceptor, "post_generate_access_token" + ) as post, + mock.patch.object( + transports.IAMCredentialsRestInterceptor, + "post_generate_access_token_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.IAMCredentialsRestInterceptor, "pre_generate_access_token" + ) as pre, + ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = common.GenerateAccessTokenRequest.pb(common.GenerateAccessTokenRequest()) + pb_message = common.GenerateAccessTokenRequest.pb( + common.GenerateAccessTokenRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3415,11 +3965,13 @@ def test_generate_access_token_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = common.GenerateAccessTokenResponse.to_json(common.GenerateAccessTokenResponse()) + return_value = common.GenerateAccessTokenResponse.to_json( + common.GenerateAccessTokenResponse() + ) req.return_value.content = return_value request = common.GenerateAccessTokenRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3427,7 +3979,13 @@ def test_generate_access_token_rest_interceptors(null_interceptor): post.return_value = common.GenerateAccessTokenResponse() post_with_metadata.return_value = common.GenerateAccessTokenResponse(), metadata - client.generate_access_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.generate_access_token( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -3436,18 +3994,20 @@ def test_generate_access_token_rest_interceptors(null_interceptor): def test_generate_id_token_rest_bad_request(request_type=common.GenerateIdTokenRequest): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/serviceAccounts/sample2'} + request_init = {"name": "projects/sample1/serviceAccounts/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -3456,25 +4016,27 @@ def test_generate_id_token_rest_bad_request(request_type=common.GenerateIdTokenR client.generate_id_token(request) -@pytest.mark.parametrize("request_type", [ - common.GenerateIdTokenRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + common.GenerateIdTokenRequest, + dict, + ], +) def test_generate_id_token_rest_call_success(request_type): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/serviceAccounts/sample2'} + request_init = {"name": "projects/sample1/serviceAccounts/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = common.GenerateIdTokenResponse( - token='token_value', + token="token_value", ) # Wrap the value into a proper Response obj @@ -3484,29 +4046,40 @@ def test_generate_id_token_rest_call_success(request_type): # Convert return value to protobuf type return_value = common.GenerateIdTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.generate_id_token(request) # Establish that the response is the type that we expect. assert isinstance(response, common.GenerateIdTokenResponse) - assert response.token == 'token_value' + assert response.token == "token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_generate_id_token_rest_interceptors(null_interceptor): transport = transports.IAMCredentialsRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IAMCredentialsRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.IAMCredentialsRestInterceptor(), + ) client = IAMCredentialsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.IAMCredentialsRestInterceptor, "post_generate_id_token") as post, \ - mock.patch.object(transports.IAMCredentialsRestInterceptor, "post_generate_id_token_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.IAMCredentialsRestInterceptor, "pre_generate_id_token") as pre: + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.IAMCredentialsRestInterceptor, "post_generate_id_token" + ) as post, + mock.patch.object( + transports.IAMCredentialsRestInterceptor, + "post_generate_id_token_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.IAMCredentialsRestInterceptor, "pre_generate_id_token" + ) as pre, + ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -3521,11 +4094,13 @@ def test_generate_id_token_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = common.GenerateIdTokenResponse.to_json(common.GenerateIdTokenResponse()) + return_value = common.GenerateIdTokenResponse.to_json( + common.GenerateIdTokenResponse() + ) req.return_value.content = return_value request = common.GenerateIdTokenRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3533,7 +4108,13 @@ def test_generate_id_token_rest_interceptors(null_interceptor): post.return_value = common.GenerateIdTokenResponse() post_with_metadata.return_value = common.GenerateIdTokenResponse(), metadata - client.generate_id_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.generate_id_token( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -3542,18 +4123,20 @@ def test_generate_id_token_rest_interceptors(null_interceptor): def test_sign_blob_rest_bad_request(request_type=common.SignBlobRequest): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/serviceAccounts/sample2'} + request_init = {"name": "projects/sample1/serviceAccounts/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -3562,26 +4145,28 @@ def test_sign_blob_rest_bad_request(request_type=common.SignBlobRequest): client.sign_blob(request) -@pytest.mark.parametrize("request_type", [ - common.SignBlobRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + common.SignBlobRequest, + dict, + ], +) def test_sign_blob_rest_call_success(request_type): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/serviceAccounts/sample2'} + request_init = {"name": "projects/sample1/serviceAccounts/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = common.SignBlobResponse( - key_id='key_id_value', - signed_blob=b'signed_blob_blob', + key_id="key_id_value", + signed_blob=b"signed_blob_blob", ) # Wrap the value into a proper Response obj @@ -3591,30 +4176,40 @@ def test_sign_blob_rest_call_success(request_type): # Convert return value to protobuf type return_value = common.SignBlobResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.sign_blob(request) # Establish that the response is the type that we expect. assert isinstance(response, common.SignBlobResponse) - assert response.key_id == 'key_id_value' - assert response.signed_blob == b'signed_blob_blob' + assert response.key_id == "key_id_value" + assert response.signed_blob == b"signed_blob_blob" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_sign_blob_rest_interceptors(null_interceptor): transport = transports.IAMCredentialsRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IAMCredentialsRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.IAMCredentialsRestInterceptor(), + ) client = IAMCredentialsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.IAMCredentialsRestInterceptor, "post_sign_blob") as post, \ - mock.patch.object(transports.IAMCredentialsRestInterceptor, "post_sign_blob_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.IAMCredentialsRestInterceptor, "pre_sign_blob") as pre: + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.IAMCredentialsRestInterceptor, "post_sign_blob" + ) as post, + mock.patch.object( + transports.IAMCredentialsRestInterceptor, "post_sign_blob_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.IAMCredentialsRestInterceptor, "pre_sign_blob" + ) as pre, + ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -3633,7 +4228,7 @@ def test_sign_blob_rest_interceptors(null_interceptor): req.return_value.content = return_value request = common.SignBlobRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3641,7 +4236,13 @@ def test_sign_blob_rest_interceptors(null_interceptor): post.return_value = common.SignBlobResponse() post_with_metadata.return_value = common.SignBlobResponse(), metadata - client.sign_blob(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.sign_blob( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -3650,18 +4251,20 @@ def test_sign_blob_rest_interceptors(null_interceptor): def test_sign_jwt_rest_bad_request(request_type=common.SignJwtRequest): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/serviceAccounts/sample2'} + request_init = {"name": "projects/sample1/serviceAccounts/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -3670,26 +4273,28 @@ def test_sign_jwt_rest_bad_request(request_type=common.SignJwtRequest): client.sign_jwt(request) -@pytest.mark.parametrize("request_type", [ - common.SignJwtRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + common.SignJwtRequest, + dict, + ], +) def test_sign_jwt_rest_call_success(request_type): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/serviceAccounts/sample2'} + request_init = {"name": "projects/sample1/serviceAccounts/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = common.SignJwtResponse( - key_id='key_id_value', - signed_jwt='signed_jwt_value', + key_id="key_id_value", + signed_jwt="signed_jwt_value", ) # Wrap the value into a proper Response obj @@ -3699,30 +4304,40 @@ def test_sign_jwt_rest_call_success(request_type): # Convert return value to protobuf type return_value = common.SignJwtResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.sign_jwt(request) # Establish that the response is the type that we expect. assert isinstance(response, common.SignJwtResponse) - assert response.key_id == 'key_id_value' - assert response.signed_jwt == 'signed_jwt_value' + assert response.key_id == "key_id_value" + assert response.signed_jwt == "signed_jwt_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_sign_jwt_rest_interceptors(null_interceptor): transport = transports.IAMCredentialsRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.IAMCredentialsRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.IAMCredentialsRestInterceptor(), + ) client = IAMCredentialsClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.IAMCredentialsRestInterceptor, "post_sign_jwt") as post, \ - mock.patch.object(transports.IAMCredentialsRestInterceptor, "post_sign_jwt_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.IAMCredentialsRestInterceptor, "pre_sign_jwt") as pre: + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.IAMCredentialsRestInterceptor, "post_sign_jwt" + ) as post, + mock.patch.object( + transports.IAMCredentialsRestInterceptor, "post_sign_jwt_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.IAMCredentialsRestInterceptor, "pre_sign_jwt" + ) as pre, + ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -3741,7 +4356,7 @@ def test_sign_jwt_rest_interceptors(null_interceptor): req.return_value.content = return_value request = common.SignJwtRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3749,16 +4364,22 @@ def test_sign_jwt_rest_interceptors(null_interceptor): post.return_value = common.SignJwtResponse() post_with_metadata.return_value = common.SignJwtResponse(), metadata - client.sign_jwt(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.sign_jwt( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -3773,8 +4394,8 @@ def test_generate_access_token_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: + type(client.transport.generate_access_token), "__call__" + ) as call: client.generate_access_token(request=None) # Establish that the underlying stub method was called. @@ -3795,8 +4416,8 @@ def test_generate_id_token_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), - '__call__') as call: + type(client.transport.generate_id_token), "__call__" + ) as call: client.generate_id_token(request=None) # Establish that the underlying stub method was called. @@ -3816,9 +4437,7 @@ def test_sign_blob_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.sign_blob), - '__call__') as call: + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: client.sign_blob(request=None) # Establish that the underlying stub method was called. @@ -3838,9 +4457,7 @@ def test_sign_jwt_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.sign_jwt), - '__call__') as call: + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: client.sign_jwt(request=None) # Establish that the underlying stub method was called. @@ -3861,18 +4478,21 @@ def test_transport_grpc_default(): transports.IAMCredentialsGrpcTransport, ) + def test_iam_credentials_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.IAMCredentialsTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_iam_credentials_base_transport(): # Instantiate the base transport. - with mock.patch('google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsTransport.__init__') as Transport: + with mock.patch( + "google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.IAMCredentialsTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -3881,10 +4501,10 @@ def test_iam_credentials_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'generate_access_token', - 'generate_id_token', - 'sign_blob', - 'sign_jwt', + "generate_access_token", + "generate_id_token", + "sign_blob", + "sign_jwt", ) for method in methods: with pytest.raises(NotImplementedError): @@ -3895,7 +4515,7 @@ def test_iam_credentials_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -3904,25 +4524,36 @@ def test_iam_credentials_base_transport(): def test_iam_credentials_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsTransport._prep_wrapped_messages') as Transport: + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsTransport._prep_wrapped_messages" + ) as Transport, + ): Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.IAMCredentialsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with("credentials.json", + load_creds.assert_called_once_with( + "credentials.json", scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) def test_iam_credentials_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsTransport._prep_wrapped_messages') as Transport: + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsTransport._prep_wrapped_messages" + ) as Transport, + ): Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.IAMCredentialsTransport() @@ -3931,14 +4562,12 @@ def test_iam_credentials_base_transport_with_adc(): def test_iam_credentials_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) IAMCredentialsClient() adc.assert_called_once_with( scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id=None, ) @@ -3953,12 +4582,12 @@ def test_iam_credentials_auth_adc(): def test_iam_credentials_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class(quota_project_id="octopus", scopes=["1", "2"]) adc.assert_called_once_with( scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) @@ -3972,48 +4601,46 @@ def test_iam_credentials_transport_auth_adc(transport_class): ], ) def test_iam_credentials_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + with mock.patch.object(google.auth, "default", autospec=True) as adc: gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) adc.return_value = (gdch_mock, None) transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) + gdch_mock.with_gdch_audience.assert_called_once_with(e) @pytest.mark.parametrize( "transport_class,grpc_helpers", [ (transports.IAMCredentialsGrpcTransport, grpc_helpers), - (transports.IAMCredentialsGrpcAsyncIOTransport, grpc_helpers_async) + (transports.IAMCredentialsGrpcAsyncIOTransport, grpc_helpers_async), ], ) def test_iam_credentials_transport_create_channel(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel, + ): creds = ga_credentials.AnonymousCredentials() adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( "iamcredentials.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), scopes=["1", "2"], default_host="iamcredentials.googleapis.com", ssl_credentials=None, @@ -4024,10 +4651,14 @@ def test_iam_credentials_transport_create_channel(transport_class, grpc_helpers) ) -@pytest.mark.parametrize("transport_class", [transports.IAMCredentialsGrpcTransport, transports.IAMCredentialsGrpcAsyncIOTransport]) -def test_iam_credentials_grpc_transport_client_cert_source_for_mtls( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.IAMCredentialsGrpcTransport, + transports.IAMCredentialsGrpcAsyncIOTransport, + ], +) +def test_iam_credentials_grpc_transport_client_cert_source_for_mtls(transport_class): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -4036,7 +4667,7 @@ def test_iam_credentials_grpc_transport_client_cert_source_for_mtls( transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds + ssl_channel_credentials=mock_ssl_channel_creds, ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", @@ -4057,61 +4688,77 @@ def test_iam_credentials_grpc_transport_client_cert_source_for_mtls( with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback + client_cert_source_for_mtls=client_cert_source_callback, ) expected_cert, expected_key = client_cert_source_callback() mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key + certificate_chain=expected_cert, private_key=expected_key ) + def test_iam_credentials_http_transport_client_cert_source_for_mtls(): cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.IAMCredentialsRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.IAMCredentialsRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) def test_iam_credentials_host_no_port(transport_name): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='iamcredentials.googleapis.com'), - transport=transport_name, + client_options=client_options.ClientOptions( + api_endpoint="iamcredentials.googleapis.com" + ), + transport=transport_name, ) assert client.transport._host == ( - 'iamcredentials.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://iamcredentials.googleapis.com' + "iamcredentials.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://iamcredentials.googleapis.com" ) -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) def test_iam_credentials_host_with_port(transport_name): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='iamcredentials.googleapis.com:8000'), + client_options=client_options.ClientOptions( + api_endpoint="iamcredentials.googleapis.com:8000" + ), transport=transport_name, ) assert client.transport._host == ( - 'iamcredentials.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://iamcredentials.googleapis.com:8000' + "iamcredentials.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://iamcredentials.googleapis.com:8000" ) -@pytest.mark.parametrize("transport_name", [ - "rest", -]) + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) def test_iam_credentials_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -4135,8 +4782,10 @@ def test_iam_credentials_client_transport_session_collision(transport_name): session1 = client1.transport.sign_jwt._session session2 = client2.transport.sign_jwt._session assert session1 != session2 + + def test_iam_credentials_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.IAMCredentialsGrpcTransport( @@ -4149,7 +4798,7 @@ def test_iam_credentials_grpc_transport_channel(): def test_iam_credentials_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.IAMCredentialsGrpcAsyncIOTransport( @@ -4164,12 +4813,22 @@ def test_iam_credentials_grpc_asyncio_transport_channel(): # Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are # removed from grpc/grpc_asyncio transport constructor. @pytest.mark.filterwarnings("ignore::FutureWarning") -@pytest.mark.parametrize("transport_class", [transports.IAMCredentialsGrpcTransport, transports.IAMCredentialsGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.IAMCredentialsGrpcTransport, + transports.IAMCredentialsGrpcAsyncIOTransport, + ], +) def test_iam_credentials_transport_channel_mtls_with_client_cert_source( - transport_class + transport_class, ): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: mock_ssl_cred = mock.Mock() grpc_ssl_channel_cred.return_value = mock_ssl_cred @@ -4178,7 +4837,7 @@ def test_iam_credentials_transport_channel_mtls_with_client_cert_source( cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -4208,17 +4867,23 @@ def test_iam_credentials_transport_channel_mtls_with_client_cert_source( # Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are # removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.IAMCredentialsGrpcTransport, transports.IAMCredentialsGrpcAsyncIOTransport]) -def test_iam_credentials_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.IAMCredentialsGrpcTransport, + transports.IAMCredentialsGrpcAsyncIOTransport, + ], +) +def test_iam_credentials_transport_channel_mtls_with_adc(transport_class): mock_ssl_cred = mock.Mock() with mock.patch.multiple( "google.auth.transport.grpc.SslCredentials", __init__=mock.Mock(return_value=None), ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel mock_cred = mock.Mock() @@ -4249,7 +4914,10 @@ def test_iam_credentials_transport_channel_mtls_with_adc( def test_service_account_path(): project = "squid" service_account = "clam" - expected = "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) + expected = "projects/{project}/serviceAccounts/{service_account}".format( + project=project, + service_account=service_account, + ) actual = IAMCredentialsClient.service_account_path(project, service_account) assert expected == actual @@ -4265,9 +4933,12 @@ def test_parse_service_account_path(): actual = IAMCredentialsClient.parse_service_account_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = IAMCredentialsClient.common_billing_account_path(billing_account) assert expected == actual @@ -4282,9 +4953,12 @@ def test_parse_common_billing_account_path(): actual = IAMCredentialsClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = IAMCredentialsClient.common_folder_path(folder) assert expected == actual @@ -4299,9 +4973,12 @@ def test_parse_common_folder_path(): actual = IAMCredentialsClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = IAMCredentialsClient.common_organization_path(organization) assert expected == actual @@ -4316,9 +4993,12 @@ def test_parse_common_organization_path(): actual = IAMCredentialsClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = IAMCredentialsClient.common_project_path(project) assert expected == actual @@ -4333,10 +5013,14 @@ def test_parse_common_project_path(): actual = IAMCredentialsClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = IAMCredentialsClient.common_location_path(project, location) assert expected == actual @@ -4356,14 +5040,18 @@ def test_parse_common_location_path(): def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object(transports.IAMCredentialsTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.IAMCredentialsTransport, "_prep_wrapped_messages" + ) as prep: client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.IAMCredentialsTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.IAMCredentialsTransport, "_prep_wrapped_messages" + ) as prep: transport_class = IAMCredentialsClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -4374,10 +5062,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: with client: close.assert_not_called() close.assert_called_once() @@ -4386,10 +5075,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = IAMCredentialsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: async with client: close.assert_not_called() close.assert_called_once() @@ -4397,10 +5087,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: with client: close.assert_not_called() close.assert_called_once() @@ -4408,13 +5099,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport + credentials=ga_credentials.AnonymousCredentials(), transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -4423,10 +5113,14 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport), - (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport), + (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -4441,7 +5135,9 @@ def test_api_key_credentials(client_class, transport_class): patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, From a8bbee54a3a4d2fc3d10c70363ba482960442708 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 09:36:39 -0400 Subject: [PATCH 47/52] fix(gapic-generator): remove duplicate import of sys in __init__.py template --- .../templates/%namespace/%name_%version/%sub/__init__.py.j2 | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/__init__.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/__init__.py.j2 index 8b80bec9281a..c1e5c715cf71 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/__init__.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/__init__.py.j2 @@ -56,7 +56,6 @@ else: # pragma: NO COVER # functions above. We do equivalent checks manually. try: import warnings - import sys _py_version_str = sys.version.split()[0] _package_label = "{{package_path}}" From 8132257ea6ca141e97087a460fa13dfbd92859eb Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 09:36:41 -0400 Subject: [PATCH 48/52] chore(gapic-generator): update goldens to remove duplicate import of sys --- .../goldens/eventarc/google/cloud/eventarc_v1/__init__.py | 1 - .../goldens/logging/google/cloud/logging_v2/__init__.py | 1 - .../goldens/logging_internal/google/cloud/logging_v2/__init__.py | 1 - .../integration/goldens/redis/google/cloud/redis_v1/__init__.py | 1 - .../goldens/redis_selective/google/cloud/redis_v1/__init__.py | 1 - 5 files changed, 5 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/__init__.py index 8bb9d3e0d187..c8e8e8f8e116 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/__init__.py @@ -72,7 +72,6 @@ # functions above. We do equivalent checks manually. try: import warnings - import sys _py_version_str = sys.version.split()[0] _package_label = "google.cloud.eventarc_v1" diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/__init__.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/__init__.py index 321ade08f204..3fd47a6026e0 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/__init__.py @@ -115,7 +115,6 @@ # functions above. We do equivalent checks manually. try: import warnings - import sys _py_version_str = sys.version.split()[0] _package_label = "google.cloud.logging_v2" diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/__init__.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/__init__.py index 6e70f5a50377..bd9c64ab7ad0 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/__init__.py @@ -115,7 +115,6 @@ # functions above. We do equivalent checks manually. try: import warnings - import sys _py_version_str = sys.version.split()[0] _package_label = "google.cloud.logging_v2" diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/__init__.py index a17533fce850..fe9027cea092 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/__init__.py @@ -62,7 +62,6 @@ # functions above. We do equivalent checks manually. try: import warnings - import sys _py_version_str = sys.version.split()[0] _package_label = "google.cloud.redis_v1" diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/__init__.py index 0586d7d5201e..e459366dcf10 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/__init__.py @@ -49,7 +49,6 @@ # functions above. We do equivalent checks manually. try: import warnings - import sys _py_version_str = sys.version.split()[0] _package_label = "google.cloud.redis_v1" From dcdc8a1c92d58abcb46c62ff06e58ed79b91530b Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 09:40:39 -0400 Subject: [PATCH 49/52] chore(gapic-generator): revert formatting in credentials golden to match generator --- .../goldens/credentials/docs/conf.py | 12 +- .../google/iam/credentials/__init__.py | 48 +- .../google/iam/credentials_v1/__init__.py | 112 +- .../services/iam_credentials/__init__.py | 6 +- .../services/iam_credentials/async_client.py | 276 +- .../services/iam_credentials/client.py | 425 +-- .../iam_credentials/transports/__init__.py | 20 +- .../iam_credentials/transports/base.py | 141 +- .../iam_credentials/transports/grpc.py | 146 +- .../transports/grpc_asyncio.py | 157 +- .../iam_credentials/transports/rest.py | 625 ++-- .../iam_credentials/transports/rest_base.py | 198 +- .../iam/credentials_v1/types/__init__.py | 16 +- .../google/iam/credentials_v1/types/common.py | 22 +- .../credentials_v1/types/iamcredentials.py | 6 +- .../goldens/credentials/noxfile.py | 28 +- ...credentials_generate_access_token_async.py | 3 +- ..._credentials_generate_access_token_sync.py | 3 +- ...iam_credentials_generate_id_token_async.py | 1 - ..._iam_credentials_generate_id_token_sync.py | 1 - ...nerated_iam_credentials_sign_blob_async.py | 3 +- ...enerated_iam_credentials_sign_blob_sync.py | 3 +- ...enerated_iam_credentials_sign_jwt_async.py | 1 - ...generated_iam_credentials_sign_jwt_sync.py | 1 - .../integration/goldens/credentials/setup.py | 11 +- .../goldens/credentials/tests/__init__.py | 1 + .../credentials/tests/unit/__init__.py | 1 + .../credentials/tests/unit/gapic/__init__.py | 1 + .../unit/gapic/credentials_v1/__init__.py | 1 + .../credentials_v1/test_iam_credentials.py | 2634 ++++++----------- 30 files changed, 1887 insertions(+), 3016 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/docs/conf.py b/packages/gapic-generator/tests/integration/goldens/credentials/docs/conf.py index a6be00cae63c..b931406b0132 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/docs/conf.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/docs/conf.py @@ -28,6 +28,7 @@ import os import shlex import sys +import logging from typing import Any # If extensions (or modules to document with autodoc) are in another directory, @@ -82,9 +83,9 @@ root_doc = "index" # General information about the project. -project = "google-iam-credentials" -copyright = "2025, Google, LLC" -author = "Google APIs" +project = u"google-iam-credentials" +copyright = u"2025, Google, LLC" +author = u"Google APIs" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -284,7 +285,7 @@ ( root_doc, "google-iam-credentials.tex", - "google-iam-credentials Documentation", + u"google-iam-credentials Documentation", author, "manual", ) @@ -385,7 +386,6 @@ napoleon_use_param = True napoleon_use_rtype = True - # Setup for sphinx behaviors such as warning filters. class UnexpectedUnindentFilter(logging.Filter): """Filter out warnings about unexpected unindentation following bullet lists.""" @@ -413,5 +413,5 @@ def setup(app: Any) -> None: """ # Sphinx's logger is hierarchical. Adding a filter to the # root 'sphinx' logger will catch warnings from all sub-loggers. - logger = logging.getLogger("sphinx") + logger = logging.getLogger('sphinx') logger.addFilter(UnexpectedUnindentFilter()) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials/__init__.py index 1196554e01ee..9c0382dd3319 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials/__init__.py @@ -18,32 +18,26 @@ __version__ = package_version.__version__ -from google.iam.credentials_v1.services.iam_credentials.async_client import ( - IAMCredentialsAsyncClient, -) -from google.iam.credentials_v1.services.iam_credentials.client import ( - IAMCredentialsClient, -) -from google.iam.credentials_v1.types.common import ( - GenerateAccessTokenRequest, - GenerateAccessTokenResponse, - GenerateIdTokenRequest, - GenerateIdTokenResponse, - SignBlobRequest, - SignBlobResponse, - SignJwtRequest, - SignJwtResponse, -) +from google.iam.credentials_v1.services.iam_credentials.client import IAMCredentialsClient +from google.iam.credentials_v1.services.iam_credentials.async_client import IAMCredentialsAsyncClient + +from google.iam.credentials_v1.types.common import GenerateAccessTokenRequest +from google.iam.credentials_v1.types.common import GenerateAccessTokenResponse +from google.iam.credentials_v1.types.common import GenerateIdTokenRequest +from google.iam.credentials_v1.types.common import GenerateIdTokenResponse +from google.iam.credentials_v1.types.common import SignBlobRequest +from google.iam.credentials_v1.types.common import SignBlobResponse +from google.iam.credentials_v1.types.common import SignJwtRequest +from google.iam.credentials_v1.types.common import SignJwtResponse -__all__ = ( - "IAMCredentialsClient", - "IAMCredentialsAsyncClient", - "GenerateAccessTokenRequest", - "GenerateAccessTokenResponse", - "GenerateIdTokenRequest", - "GenerateIdTokenResponse", - "SignBlobRequest", - "SignBlobResponse", - "SignJwtRequest", - "SignJwtResponse", +__all__ = ('IAMCredentialsClient', + 'IAMCredentialsAsyncClient', + 'GenerateAccessTokenRequest', + 'GenerateAccessTokenResponse', + 'GenerateIdTokenRequest', + 'GenerateIdTokenResponse', + 'SignBlobRequest', + 'SignBlobResponse', + 'SignJwtRequest', + 'SignJwtResponse', ) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/__init__.py index 2e45666bac2a..c4a6ecb27594 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/__init__.py @@ -13,34 +13,32 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import sys +from google.iam.credentials_v1 import gapic_version as package_version import google.api_core as api_core - -from google.iam.credentials_v1 import gapic_version as package_version +import sys __version__ = package_version.__version__ from importlib import metadata -from .services.iam_credentials import IAMCredentialsAsyncClient, IAMCredentialsClient -from .types.common import ( - GenerateAccessTokenRequest, - GenerateAccessTokenResponse, - GenerateIdTokenRequest, - GenerateIdTokenResponse, - SignBlobRequest, - SignBlobResponse, - SignJwtRequest, - SignJwtResponse, -) -if hasattr(api_core, "check_python_version") and hasattr( - api_core, "check_dependency_versions" -): # pragma: NO COVER - api_core.check_python_version("google.iam.credentials_v1") # type: ignore - api_core.check_dependency_versions("google.iam.credentials_v1") # type: ignore -else: # pragma: NO COVER +from .services.iam_credentials import IAMCredentialsClient +from .services.iam_credentials import IAMCredentialsAsyncClient + +from .types.common import GenerateAccessTokenRequest +from .types.common import GenerateAccessTokenResponse +from .types.common import GenerateIdTokenRequest +from .types.common import GenerateIdTokenResponse +from .types.common import SignBlobRequest +from .types.common import SignBlobResponse +from .types.common import SignJwtRequest +from .types.common import SignJwtResponse + +if hasattr(api_core, "check_python_version") and hasattr(api_core, "check_dependency_versions"): # pragma: NO COVER + api_core.check_python_version("google.iam.credentials_v1") # type: ignore + api_core.check_dependency_versions("google.iam.credentials_v1") # type: ignore +else: # pragma: NO COVER # An older version of api_core is installed which does not define the # functions above. We do equivalent checks manually. try: @@ -49,14 +47,12 @@ _py_version_str = sys.version.split()[0] _package_label = "google.iam.credentials_v1" if sys.version_info < (3, 10): - warnings.warn( - "You are using a non-supported Python version " - + f"({_py_version_str}). Google will not post any further " - + f"updates to {_package_label} supporting this Python version. " - + "Please upgrade to the latest Python version, or at " - + f"least to Python 3.10, and then update {_package_label}.", - FutureWarning, - ) + warnings.warn("You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.10, and then update {_package_label}.", + FutureWarning) def parse_version_to_tuple(version_string: str): """Safely converts a semantic version string to a comparable tuple of integers. @@ -94,39 +90,35 @@ def _get_version(dependency_name): _recommendation = " (we recommend 6.x)" (_version_used, _version_used_string) = _get_version(_dependency_package) if _version_used and _version_used < _next_supported_version_tuple: - warnings.warn( - f"Package {_package_label} depends on " - + f"{_dependency_package}, currently installed at version " - + f"{_version_used_string}. Future updates to " - + f"{_package_label} will require {_dependency_package} at " - + f"version {_next_supported_version} or higher{_recommendation}." - + " Please ensure " - + "that either (a) your Python environment doesn't pin the " - + f"version of {_dependency_package}, so that updates to " - + f"{_package_label} can require the higher version, or " - + "(b) you manually update your Python environment to use at " - + f"least version {_next_supported_version} of " - + f"{_dependency_package}.", - FutureWarning, - ) + warnings.warn(f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning) except Exception: - warnings.warn( - "Could not determine the version of Python " - + "currently being used. To continue receiving " - + "updates for {_package_label}, ensure you are " - + "using a supported version of Python; see " - + "https://devguide.python.org/versions/" - ) + warnings.warn("Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/") __all__ = ( - "IAMCredentialsAsyncClient", - "GenerateAccessTokenRequest", - "GenerateAccessTokenResponse", - "GenerateIdTokenRequest", - "GenerateIdTokenResponse", - "IAMCredentialsClient", - "SignBlobRequest", - "SignBlobResponse", - "SignJwtRequest", - "SignJwtResponse", + 'IAMCredentialsAsyncClient', +'GenerateAccessTokenRequest', +'GenerateAccessTokenResponse', +'GenerateIdTokenRequest', +'GenerateIdTokenResponse', +'IAMCredentialsClient', +'SignBlobRequest', +'SignBlobResponse', +'SignJwtRequest', +'SignJwtResponse', ) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/__init__.py index 36b57fe4c555..988290706545 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .async_client import IAMCredentialsAsyncClient from .client import IAMCredentialsClient +from .async_client import IAMCredentialsAsyncClient __all__ = ( - "IAMCredentialsClient", - "IAMCredentialsAsyncClient", + 'IAMCredentialsClient', + 'IAMCredentialsAsyncClient', ) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/async_client.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/async_client.py index 9408ee9cb76a..7852bfe5c199 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/async_client.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/async_client.py @@ -14,55 +14,41 @@ # limitations under the License. # import logging as std_logging -import re from collections import OrderedDict -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, -) +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union -import google.protobuf +from google.iam.credentials_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.api_core.client_options import ClientOptions -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf -from google.iam.credentials_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore +from google.iam.credentials_v1.types import common import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore - -from google.iam.credentials_v1.types import common - -from .client import IAMCredentialsClient -from .transports.base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport +from .transports.base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport +from .client import IAMCredentialsClient try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) - class IAMCredentialsAsyncClient: """A service account is a special type of Google account that belongs to your application or a virtual machine (VM), instead @@ -86,33 +72,17 @@ class IAMCredentialsAsyncClient: _DEFAULT_UNIVERSE = IAMCredentialsClient._DEFAULT_UNIVERSE service_account_path = staticmethod(IAMCredentialsClient.service_account_path) - parse_service_account_path = staticmethod( - IAMCredentialsClient.parse_service_account_path - ) - common_billing_account_path = staticmethod( - IAMCredentialsClient.common_billing_account_path - ) - parse_common_billing_account_path = staticmethod( - IAMCredentialsClient.parse_common_billing_account_path - ) + parse_service_account_path = staticmethod(IAMCredentialsClient.parse_service_account_path) + common_billing_account_path = staticmethod(IAMCredentialsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(IAMCredentialsClient.parse_common_billing_account_path) common_folder_path = staticmethod(IAMCredentialsClient.common_folder_path) - parse_common_folder_path = staticmethod( - IAMCredentialsClient.parse_common_folder_path - ) - common_organization_path = staticmethod( - IAMCredentialsClient.common_organization_path - ) - parse_common_organization_path = staticmethod( - IAMCredentialsClient.parse_common_organization_path - ) + parse_common_folder_path = staticmethod(IAMCredentialsClient.parse_common_folder_path) + common_organization_path = staticmethod(IAMCredentialsClient.common_organization_path) + parse_common_organization_path = staticmethod(IAMCredentialsClient.parse_common_organization_path) common_project_path = staticmethod(IAMCredentialsClient.common_project_path) - parse_common_project_path = staticmethod( - IAMCredentialsClient.parse_common_project_path - ) + parse_common_project_path = staticmethod(IAMCredentialsClient.parse_common_project_path) common_location_path = staticmethod(IAMCredentialsClient.common_location_path) - parse_common_location_path = staticmethod( - IAMCredentialsClient.parse_common_location_path - ) + parse_common_location_path = staticmethod(IAMCredentialsClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -154,9 +124,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -219,16 +187,12 @@ def universe_domain(self) -> str: get_transport_class = IAMCredentialsClient.get_transport_class - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]] - ] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the iam credentials async client. Args: @@ -286,42 +250,34 @@ def __init__( transport=transport, client_options=client_options, client_info=client_info, + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.iam.credentials_v1.IAMCredentialsAsyncClient`.", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", - "universeDomain": getattr( - self._client._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._client._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { "serviceName": "google.iam.credentials.v1.IAMCredentials", "credentialsType": None, - }, + } ) - async def generate_access_token( - self, - request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - scope: Optional[MutableSequence[str]] = None, - lifetime: Optional[duration_pb2.Duration] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateAccessTokenResponse: + async def generate_access_token(self, + request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + scope: Optional[MutableSequence[str]] = None, + lifetime: Optional[duration_pb2.Duration] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateAccessTokenResponse: r"""Generates an OAuth 2.0 access token for a service account. @@ -422,14 +378,10 @@ async def sample_generate_access_token(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, scope, lifetime] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -449,14 +401,14 @@ async def sample_generate_access_token(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.generate_access_token - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.generate_access_token] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -473,18 +425,17 @@ async def sample_generate_access_token(): # Done; return the response. return response - async def generate_id_token( - self, - request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - audience: Optional[str] = None, - include_email: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateIdTokenResponse: + async def generate_id_token(self, + request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + audience: Optional[str] = None, + include_email: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateIdTokenResponse: r"""Generates an OpenID Connect ID token for a service account. @@ -579,14 +530,10 @@ async def sample_generate_id_token(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, audience, include_email] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -606,14 +553,14 @@ async def sample_generate_id_token(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.generate_id_token - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.generate_id_token] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -630,17 +577,16 @@ async def sample_generate_id_token(): # Done; return the response. return response - async def sign_blob( - self, - request: Optional[Union[common.SignBlobRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - payload: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignBlobResponse: + async def sign_blob(self, + request: Optional[Union[common.SignBlobRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignBlobResponse: r"""Signs a blob using a service account's system-managed private key. @@ -724,14 +670,10 @@ async def sample_sign_blob(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, payload] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -749,14 +691,14 @@ async def sample_sign_blob(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.sign_blob - ] + rpc = self._client._transport._wrapped_methods[self._client._transport.sign_blob] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -773,17 +715,16 @@ async def sample_sign_blob(): # Done; return the response. return response - async def sign_jwt( - self, - request: Optional[Union[common.SignJwtRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - payload: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignJwtResponse: + async def sign_jwt(self, + request: Optional[Union[common.SignJwtRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignJwtResponse: r"""Signs a JWT using a service account's system-managed private key. @@ -870,14 +811,10 @@ async def sample_sign_jwt(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, payload] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -900,7 +837,9 @@ async def sample_sign_jwt(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -923,13 +862,12 @@ async def __aenter__(self) -> "IAMCredentialsAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("IAMCredentialsAsyncClient",) +__all__ = ( + "IAMCredentialsAsyncClient", +) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py index b0e8785d118d..c55d4a2a44bb 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py @@ -13,39 +13,27 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from collections import OrderedDict +from http import HTTPStatus import json import logging as std_logging import os import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast import warnings -from collections import OrderedDict -from http import HTTPStatus -from typing import ( - Callable, - Dict, - Mapping, - MutableMapping, - MutableSequence, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) -import google.protobuf +from google.iam.credentials_v1 import gapic_version as package_version + from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.iam.credentials_v1 import gapic_version as package_version +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -54,19 +42,16 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) +from google.iam.credentials_v1.types import common import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore - -from google.iam.credentials_v1.types import common - -from .transports.base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport +from .transports.base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import IAMCredentialsGrpcTransport from .transports.grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport from .transports.rest import IAMCredentialsRestTransport @@ -79,16 +64,14 @@ class IAMCredentialsClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[IAMCredentialsTransport]] _transport_registry["grpc"] = IAMCredentialsGrpcTransport _transport_registry["grpc_asyncio"] = IAMCredentialsGrpcAsyncIOTransport _transport_registry["rest"] = IAMCredentialsRestTransport - def get_transport_class( - cls, - label: Optional[str] = None, - ) -> Type[IAMCredentialsTransport]: + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[IAMCredentialsTransport]: """Returns an appropriate transport class. Args: @@ -174,16 +157,14 @@ def _use_client_cert_effective(): bool: whether client certificate should be used for mTLS Raises: ValueError: (If using a version of google-auth without should_use_client_cert and - GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) """ # check if google-auth version supports should_use_client_cert for automatic mTLS enablement if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER return mtls.should_use_client_cert() - else: # pragma: NO COVER + else: # pragma: NO COVER # if unsupported, fallback to reading from env var - use_client_cert_str = os.getenv( - "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" - ).lower() + use_client_cert_str = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() if use_client_cert_str not in ("true", "false"): raise ValueError( "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" @@ -222,7 +203,8 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: IAMCredentialsClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file(filename) + credentials = service_account.Credentials.from_service_account_file( + filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -239,106 +221,73 @@ def transport(self) -> IAMCredentialsTransport: return self._transport @staticmethod - def service_account_path( - project: str, - service_account: str, - ) -> str: + def service_account_path(project: str,service_account: str,) -> str: """Returns a fully-qualified service_account string.""" - return "projects/{project}/serviceAccounts/{service_account}".format( - project=project, - service_account=service_account, - ) + return "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) @staticmethod - def parse_service_account_path(path: str) -> Dict[str, str]: + def parse_service_account_path(path: str) -> Dict[str,str]: """Parses a service_account path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", - path, - ) + m = re.match(r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path( - billing_account: str, - ) -> str: + def common_billing_account_path(billing_account: str, ) -> str: """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: + def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_folder_path( - folder: str, - ) -> str: + def common_folder_path(folder: str, ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format( - folder=folder, - ) + return "folders/{folder}".format(folder=folder, ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: + def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_organization_path( - organization: str, - ) -> str: + def common_organization_path(organization: str, ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format( - organization=organization, - ) + return "organizations/{organization}".format(organization=organization, ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: + def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_project_path( - project: str, - ) -> str: + def common_project_path(project: str, ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format( - project=project, - ) + return "projects/{project}".format(project=project, ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: + def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def common_location_path( - project: str, - location: str, - ) -> str: + def common_location_path(project: str, location: str, ) -> str: """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: + def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source( - cls, client_options: Optional[client_options_lib.ClientOptions] = None - ): + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -370,18 +319,14 @@ def get_mtls_endpoint_and_cert_source( google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn( - "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning, - ) + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = IAMCredentialsClient._use_client_cert_effective() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. client_cert_source = None @@ -394,9 +339,7 @@ def get_mtls_endpoint_and_cert_source( # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -421,9 +364,7 @@ def _read_environment_variables(): use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError( - "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env @staticmethod @@ -446,9 +387,7 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint( - api_override, client_cert_source, universe_domain, use_mtls_endpoint - ) -> str: + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint) -> str: """Return the API endpoint used by the client. Args: @@ -464,25 +403,17 @@ def _get_api_endpoint( """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or ( - use_mtls_endpoint == "auto" and client_cert_source - ): + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): _default_universe = IAMCredentialsClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError( - f"mTLS is not supported in any universe other than {_default_universe}." - ) + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") api_endpoint = IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=universe_domain - ) + api_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) return api_endpoint @staticmethod - def _get_universe_domain( - client_universe_domain: Optional[str], universe_domain_env: Optional[str] - ) -> str: + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: """Return the universe domain used by the client. Args: @@ -518,18 +449,15 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, error: core_exceptions.GoogleAPICallError + self, + error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [ - HTTPStatus.UNAUTHORIZED, - HTTPStatus.FORBIDDEN, - HTTPStatus.NOT_FOUND, - ]: + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: return cred = self._transport._credentials @@ -562,16 +490,12 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__( - self, - *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[ - Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]] - ] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, IAMCredentialsTransport, Callable[..., IAMCredentialsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the iam credentials client. Args: @@ -629,21 +553,13 @@ def __init__( self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast( - client_options_lib.ClientOptions, self._client_options - ) + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - universe_domain_opt = getattr(self._client_options, "universe_domain", None) + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( - IAMCredentialsClient._read_environment_variables() - ) - self._client_cert_source = IAMCredentialsClient._get_client_cert_source( - self._client_options.client_cert_source, self._use_client_cert - ) - self._universe_domain = IAMCredentialsClient._get_universe_domain( - universe_domain_opt, self._universe_domain_env - ) + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = IAMCredentialsClient._read_environment_variables() + self._client_cert_source = IAMCredentialsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = IAMCredentialsClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` # Initialize the universe domain validation. @@ -655,9 +571,7 @@ def __init__( api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError( - "client_options.api_key and credentials are mutually exclusive" - ) + raise ValueError("client_options.api_key and credentials are mutually exclusive") # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -666,40 +580,30 @@ def __init__( if transport_provided: # transport is a IAMCredentialsTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") if self._client_options.scopes: raise ValueError( - "When providing a transport instance, provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = cast(IAMCredentialsTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = ( - self._api_endpoint - or IAMCredentialsClient._get_api_endpoint( + self._api_endpoint = (self._api_endpoint or + IAMCredentialsClient._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint, - ) - ) + self._use_mtls_endpoint)) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr( - google.auth._default, "get_api_key_credentials" - ): - credentials = google.auth._default.get_api_key_credentials( - api_key_value - ) + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) - transport_init: Union[ - Type[IAMCredentialsTransport], Callable[..., IAMCredentialsTransport] - ] = ( + transport_init: Union[Type[IAMCredentialsTransport], Callable[..., IAMCredentialsTransport]] = ( IAMCredentialsClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., IAMCredentialsTransport], transport) @@ -718,40 +622,31 @@ def __init__( ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER _LOGGER.debug( "Created client `google.iam.credentials_v1.IAMCredentialsClient`.", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", - "universeDomain": getattr( - self._transport._credentials, "universe_domain", "" - ), + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._transport, "_credentials") - else { + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { "serviceName": "google.iam.credentials.v1.IAMCredentials", "credentialsType": None, - }, + } ) - def generate_access_token( - self, - request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - scope: Optional[MutableSequence[str]] = None, - lifetime: Optional[duration_pb2.Duration] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateAccessTokenResponse: + def generate_access_token(self, + request: Optional[Union[common.GenerateAccessTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + scope: Optional[MutableSequence[str]] = None, + lifetime: Optional[duration_pb2.Duration] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateAccessTokenResponse: r"""Generates an OAuth 2.0 access token for a service account. @@ -852,14 +747,10 @@ def sample_generate_access_token(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, scope, lifetime] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -883,7 +774,9 @@ def sample_generate_access_token(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -900,18 +793,17 @@ def sample_generate_access_token(): # Done; return the response. return response - def generate_id_token( - self, - request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - audience: Optional[str] = None, - include_email: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateIdTokenResponse: + def generate_id_token(self, + request: Optional[Union[common.GenerateIdTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + audience: Optional[str] = None, + include_email: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.GenerateIdTokenResponse: r"""Generates an OpenID Connect ID token for a service account. @@ -1006,14 +898,10 @@ def sample_generate_id_token(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, audience, include_email] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1037,7 +925,9 @@ def sample_generate_id_token(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1054,17 +944,16 @@ def sample_generate_id_token(): # Done; return the response. return response - def sign_blob( - self, - request: Optional[Union[common.SignBlobRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - payload: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignBlobResponse: + def sign_blob(self, + request: Optional[Union[common.SignBlobRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignBlobResponse: r"""Signs a blob using a service account's system-managed private key. @@ -1148,14 +1037,10 @@ def sample_sign_blob(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, payload] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1177,7 +1062,9 @@ def sample_sign_blob(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1194,17 +1081,16 @@ def sample_sign_blob(): # Done; return the response. return response - def sign_jwt( - self, - request: Optional[Union[common.SignJwtRequest, dict]] = None, - *, - name: Optional[str] = None, - delegates: Optional[MutableSequence[str]] = None, - payload: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignJwtResponse: + def sign_jwt(self, + request: Optional[Union[common.SignJwtRequest, dict]] = None, + *, + name: Optional[str] = None, + delegates: Optional[MutableSequence[str]] = None, + payload: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> common.SignJwtResponse: r"""Signs a JWT using a service account's system-managed private key. @@ -1291,14 +1177,10 @@ def sample_sign_jwt(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name, delegates, payload] - has_flattened_params = ( - len([param for param in flattened_params if param is not None]) > 0 - ) + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1320,7 +1202,9 @@ def sample_sign_jwt(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), ) # Validate the universe domain. @@ -1351,11 +1235,16 @@ def __exit__(self, type, value, traceback): self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ("IAMCredentialsClient",) +__all__ = ( + "IAMCredentialsClient", +) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/__init__.py index 897cc6ef3890..0214f01a40ac 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/__init__.py @@ -19,18 +19,20 @@ from .base import IAMCredentialsTransport from .grpc import IAMCredentialsGrpcTransport from .grpc_asyncio import IAMCredentialsGrpcAsyncIOTransport -from .rest import IAMCredentialsRestInterceptor, IAMCredentialsRestTransport +from .rest import IAMCredentialsRestTransport +from .rest import IAMCredentialsRestInterceptor + # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[IAMCredentialsTransport]] -_transport_registry["grpc"] = IAMCredentialsGrpcTransport -_transport_registry["grpc_asyncio"] = IAMCredentialsGrpcAsyncIOTransport -_transport_registry["rest"] = IAMCredentialsRestTransport +_transport_registry['grpc'] = IAMCredentialsGrpcTransport +_transport_registry['grpc_asyncio'] = IAMCredentialsGrpcAsyncIOTransport +_transport_registry['rest'] = IAMCredentialsRestTransport __all__ = ( - "IAMCredentialsTransport", - "IAMCredentialsGrpcTransport", - "IAMCredentialsGrpcAsyncIOTransport", - "IAMCredentialsRestTransport", - "IAMCredentialsRestInterceptor", + 'IAMCredentialsTransport', + 'IAMCredentialsGrpcTransport', + 'IAMCredentialsGrpcAsyncIOTransport', + 'IAMCredentialsRestTransport', + 'IAMCredentialsRestInterceptor', ) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py index 035401000120..44e4910533ac 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py @@ -16,21 +16,20 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import google.api_core +from google.iam.credentials_v1 import gapic_version as package_version + import google.auth # type: ignore -import google.protobuf +import google.api_core from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf -from google.iam.credentials_v1 import gapic_version as package_version from google.iam.credentials_v1.types import common -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=package_version.__version__ -) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -39,23 +38,24 @@ class IAMCredentialsTransport(abc.ABC): """Abstract transport class for IAMCredentials.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) - DEFAULT_HOST: str = "iamcredentials.googleapis.com" + DEFAULT_HOST: str = 'iamcredentials.googleapis.com' def __init__( - self, - *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -94,43 +94,31 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default( - scopes=scopes, - quota_project_id=quota_project_id, - default_scopes=self.AUTH_SCOPES, - ) + credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id, default_scopes=self.AUTH_SCOPES) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience( - api_audience if api_audience else host - ) + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) # If the credentials are service account credentials, then always try to use self signed JWT. - if ( - always_use_jwt_access - and isinstance(credentials, service_account.Credentials) - and hasattr(service_account.Credentials, "with_always_use_jwt_access") - ): + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" + if ':' not in host: + host += ':443' self._host = host self._wrapped_methods: Dict[Callable, Callable] = {} @@ -202,56 +190,51 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property - def generate_access_token( - self, - ) -> Callable[ - [common.GenerateAccessTokenRequest], - Union[ - common.GenerateAccessTokenResponse, - Awaitable[common.GenerateAccessTokenResponse], - ], - ]: + def generate_access_token(self) -> Callable[ + [common.GenerateAccessTokenRequest], + Union[ + common.GenerateAccessTokenResponse, + Awaitable[common.GenerateAccessTokenResponse] + ]]: raise NotImplementedError() @property - def generate_id_token( - self, - ) -> Callable[ - [common.GenerateIdTokenRequest], - Union[ - common.GenerateIdTokenResponse, Awaitable[common.GenerateIdTokenResponse] - ], - ]: + def generate_id_token(self) -> Callable[ + [common.GenerateIdTokenRequest], + Union[ + common.GenerateIdTokenResponse, + Awaitable[common.GenerateIdTokenResponse] + ]]: raise NotImplementedError() @property - def sign_blob( - self, - ) -> Callable[ - [common.SignBlobRequest], - Union[common.SignBlobResponse, Awaitable[common.SignBlobResponse]], - ]: + def sign_blob(self) -> Callable[ + [common.SignBlobRequest], + Union[ + common.SignBlobResponse, + Awaitable[common.SignBlobResponse] + ]]: raise NotImplementedError() @property - def sign_jwt( - self, - ) -> Callable[ - [common.SignJwtRequest], - Union[common.SignJwtResponse, Awaitable[common.SignJwtResponse]], - ]: + def sign_jwt(self) -> Callable[ + [common.SignJwtRequest], + Union[ + common.SignJwtResponse, + Awaitable[common.SignJwtResponse] + ]]: raise NotImplementedError() @property @@ -259,4 +242,6 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ("IAMCredentialsTransport",) +__all__ = ( + 'IAMCredentialsTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py index b14d1137b781..5979ede85cae 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc.py @@ -19,22 +19,22 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -import google.auth # type: ignore -import google.protobuf.message -import grpc # type: ignore -import proto # type: ignore -from google.api_core import gapic_v1, grpc_helpers +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message -from google.iam.credentials_v1.types import common +import grpc # type: ignore +import proto # type: ignore -from .base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport +from google.iam.credentials_v1.types import common +from .base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,9 +44,7 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -67,7 +65,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -78,11 +76,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -97,7 +91,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": client_call_details.method, "response": grpc_response, @@ -128,26 +122,23 @@ class IAMCredentialsGrpcTransport(IAMCredentialsTransport): It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """ - _stubs: Dict[str, Callable] - def __init__( - self, - *, - host: str = "iamcredentials.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'iamcredentials.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -274,23 +265,19 @@ def __init__( ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel( - self._grpc_channel, self._interceptor - ) + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel( - cls, - host: str = "iamcredentials.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: + def create_channel(cls, + host: str = 'iamcredentials.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -326,20 +313,19 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service.""" + """Return the channel designed to connect to this service. + """ return self._grpc_channel @property - def generate_access_token( - self, - ) -> Callable[ - [common.GenerateAccessTokenRequest], common.GenerateAccessTokenResponse - ]: + def generate_access_token(self) -> Callable[ + [common.GenerateAccessTokenRequest], + common.GenerateAccessTokenResponse]: r"""Return a callable for the generate access token method over gRPC. Generates an OAuth 2.0 access token for a service @@ -355,18 +341,18 @@ def generate_access_token( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "generate_access_token" not in self._stubs: - self._stubs["generate_access_token"] = self._logged_channel.unary_unary( - "/google.iam.credentials.v1.IAMCredentials/GenerateAccessToken", + if 'generate_access_token' not in self._stubs: + self._stubs['generate_access_token'] = self._logged_channel.unary_unary( + '/google.iam.credentials.v1.IAMCredentials/GenerateAccessToken', request_serializer=common.GenerateAccessTokenRequest.serialize, response_deserializer=common.GenerateAccessTokenResponse.deserialize, ) - return self._stubs["generate_access_token"] + return self._stubs['generate_access_token'] @property - def generate_id_token( - self, - ) -> Callable[[common.GenerateIdTokenRequest], common.GenerateIdTokenResponse]: + def generate_id_token(self) -> Callable[ + [common.GenerateIdTokenRequest], + common.GenerateIdTokenResponse]: r"""Return a callable for the generate id token method over gRPC. Generates an OpenID Connect ID token for a service @@ -382,16 +368,18 @@ def generate_id_token( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "generate_id_token" not in self._stubs: - self._stubs["generate_id_token"] = self._logged_channel.unary_unary( - "/google.iam.credentials.v1.IAMCredentials/GenerateIdToken", + if 'generate_id_token' not in self._stubs: + self._stubs['generate_id_token'] = self._logged_channel.unary_unary( + '/google.iam.credentials.v1.IAMCredentials/GenerateIdToken', request_serializer=common.GenerateIdTokenRequest.serialize, response_deserializer=common.GenerateIdTokenResponse.deserialize, ) - return self._stubs["generate_id_token"] + return self._stubs['generate_id_token'] @property - def sign_blob(self) -> Callable[[common.SignBlobRequest], common.SignBlobResponse]: + def sign_blob(self) -> Callable[ + [common.SignBlobRequest], + common.SignBlobResponse]: r"""Return a callable for the sign blob method over gRPC. Signs a blob using a service account's system-managed @@ -407,16 +395,18 @@ def sign_blob(self) -> Callable[[common.SignBlobRequest], common.SignBlobRespons # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "sign_blob" not in self._stubs: - self._stubs["sign_blob"] = self._logged_channel.unary_unary( - "/google.iam.credentials.v1.IAMCredentials/SignBlob", + if 'sign_blob' not in self._stubs: + self._stubs['sign_blob'] = self._logged_channel.unary_unary( + '/google.iam.credentials.v1.IAMCredentials/SignBlob', request_serializer=common.SignBlobRequest.serialize, response_deserializer=common.SignBlobResponse.deserialize, ) - return self._stubs["sign_blob"] + return self._stubs['sign_blob'] @property - def sign_jwt(self) -> Callable[[common.SignJwtRequest], common.SignJwtResponse]: + def sign_jwt(self) -> Callable[ + [common.SignJwtRequest], + common.SignJwtResponse]: r"""Return a callable for the sign jwt method over gRPC. Signs a JWT using a service account's system-managed @@ -432,13 +422,13 @@ def sign_jwt(self) -> Callable[[common.SignJwtRequest], common.SignJwtResponse]: # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "sign_jwt" not in self._stubs: - self._stubs["sign_jwt"] = self._logged_channel.unary_unary( - "/google.iam.credentials.v1.IAMCredentials/SignJwt", + if 'sign_jwt' not in self._stubs: + self._stubs['sign_jwt'] = self._logged_channel.unary_unary( + '/google.iam.credentials.v1.IAMCredentials/SignJwt', request_serializer=common.SignJwtRequest.serialize, response_deserializer=common.SignJwtResponse.deserialize, ) - return self._stubs["sign_jwt"] + return self._stubs['sign_jwt'] def close(self): self._logged_channel.close() @@ -448,4 +438,6 @@ def kind(self) -> str: return "grpc" -__all__ = ("IAMCredentialsGrpcTransport",) +__all__ = ( + 'IAMCredentialsGrpcTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc_asyncio.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc_asyncio.py index 2aba9527ad00..fb3658d72b8d 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc_asyncio.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # import inspect import json -import logging as std_logging import pickle +import logging as std_logging import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union -import google.protobuf.message -import grpc # type: ignore -import proto # type: ignore +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, grpc_helpers_async from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore from grpc.experimental import aio # type: ignore from google.iam.credentials_v1.types import common - -from .base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport +from .base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO from .grpc import IAMCredentialsGrpcTransport try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,13 +46,9 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor( - grpc.aio.UnaryUnaryClientInterceptor -): # pragma: NO COVER +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -73,7 +69,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -84,11 +80,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = ( - dict([(k, str(v)) for k, v in response_metadata]) - if response_metadata - else None - ) + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -103,7 +95,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -139,15 +131,13 @@ class IAMCredentialsGrpcAsyncIOTransport(IAMCredentialsTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel( - cls, - host: str = "iamcredentials.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> aio.Channel: + def create_channel(cls, + host: str = 'iamcredentials.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. @@ -178,26 +168,24 @@ def create_channel( default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs, + **kwargs ) - def __init__( - self, - *, - host: str = "iamcredentials.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'iamcredentials.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -326,9 +314,7 @@ def __init__( self._interceptor = _LoggingClientAIOInterceptor() self._grpc_channel._unary_unary_interceptors.append(self._interceptor) self._logged_channel = self._grpc_channel - self._wrap_with_kind = ( - "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - ) + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @@ -343,12 +329,9 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def generate_access_token( - self, - ) -> Callable[ - [common.GenerateAccessTokenRequest], - Awaitable[common.GenerateAccessTokenResponse], - ]: + def generate_access_token(self) -> Callable[ + [common.GenerateAccessTokenRequest], + Awaitable[common.GenerateAccessTokenResponse]]: r"""Return a callable for the generate access token method over gRPC. Generates an OAuth 2.0 access token for a service @@ -364,20 +347,18 @@ def generate_access_token( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "generate_access_token" not in self._stubs: - self._stubs["generate_access_token"] = self._logged_channel.unary_unary( - "/google.iam.credentials.v1.IAMCredentials/GenerateAccessToken", + if 'generate_access_token' not in self._stubs: + self._stubs['generate_access_token'] = self._logged_channel.unary_unary( + '/google.iam.credentials.v1.IAMCredentials/GenerateAccessToken', request_serializer=common.GenerateAccessTokenRequest.serialize, response_deserializer=common.GenerateAccessTokenResponse.deserialize, ) - return self._stubs["generate_access_token"] + return self._stubs['generate_access_token'] @property - def generate_id_token( - self, - ) -> Callable[ - [common.GenerateIdTokenRequest], Awaitable[common.GenerateIdTokenResponse] - ]: + def generate_id_token(self) -> Callable[ + [common.GenerateIdTokenRequest], + Awaitable[common.GenerateIdTokenResponse]]: r"""Return a callable for the generate id token method over gRPC. Generates an OpenID Connect ID token for a service @@ -393,18 +374,18 @@ def generate_id_token( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "generate_id_token" not in self._stubs: - self._stubs["generate_id_token"] = self._logged_channel.unary_unary( - "/google.iam.credentials.v1.IAMCredentials/GenerateIdToken", + if 'generate_id_token' not in self._stubs: + self._stubs['generate_id_token'] = self._logged_channel.unary_unary( + '/google.iam.credentials.v1.IAMCredentials/GenerateIdToken', request_serializer=common.GenerateIdTokenRequest.serialize, response_deserializer=common.GenerateIdTokenResponse.deserialize, ) - return self._stubs["generate_id_token"] + return self._stubs['generate_id_token'] @property - def sign_blob( - self, - ) -> Callable[[common.SignBlobRequest], Awaitable[common.SignBlobResponse]]: + def sign_blob(self) -> Callable[ + [common.SignBlobRequest], + Awaitable[common.SignBlobResponse]]: r"""Return a callable for the sign blob method over gRPC. Signs a blob using a service account's system-managed @@ -420,18 +401,18 @@ def sign_blob( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "sign_blob" not in self._stubs: - self._stubs["sign_blob"] = self._logged_channel.unary_unary( - "/google.iam.credentials.v1.IAMCredentials/SignBlob", + if 'sign_blob' not in self._stubs: + self._stubs['sign_blob'] = self._logged_channel.unary_unary( + '/google.iam.credentials.v1.IAMCredentials/SignBlob', request_serializer=common.SignBlobRequest.serialize, response_deserializer=common.SignBlobResponse.deserialize, ) - return self._stubs["sign_blob"] + return self._stubs['sign_blob'] @property - def sign_jwt( - self, - ) -> Callable[[common.SignJwtRequest], Awaitable[common.SignJwtResponse]]: + def sign_jwt(self) -> Callable[ + [common.SignJwtRequest], + Awaitable[common.SignJwtResponse]]: r"""Return a callable for the sign jwt method over gRPC. Signs a JWT using a service account's system-managed @@ -447,16 +428,16 @@ def sign_jwt( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "sign_jwt" not in self._stubs: - self._stubs["sign_jwt"] = self._logged_channel.unary_unary( - "/google.iam.credentials.v1.IAMCredentials/SignJwt", + if 'sign_jwt' not in self._stubs: + self._stubs['sign_jwt'] = self._logged_channel.unary_unary( + '/google.iam.credentials.v1.IAMCredentials/SignJwt', request_serializer=common.SignJwtRequest.serialize, response_deserializer=common.SignJwtResponse.deserialize, ) - return self._stubs["sign_jwt"] + return self._stubs['sign_jwt'] def _prep_wrapped_messages(self, client_info): - """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { self.generate_access_token: self._wrap_method( self.generate_access_token, @@ -533,4 +514,6 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ("IAMCredentialsGrpcAsyncIOTransport",) +__all__ = ( + 'IAMCredentialsGrpcAsyncIOTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest.py index f6c34807b6b8..b9aa3c4b6f94 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest.py @@ -13,25 +13,31 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import dataclasses -import json # type: ignore import logging -import warnings -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import json # type: ignore -import google.protobuf +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1, rest_helpers, rest_streaming from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 +import google.protobuf + from google.protobuf import json_format + from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + from google.iam.credentials_v1.types import common -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + from .rest_base import _BaseIAMCredentialsRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -40,7 +46,6 @@ try: from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -109,14 +114,7 @@ def post_sign_jwt(self, response): """ - - def pre_generate_access_token( - self, - request: common.GenerateAccessTokenRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - common.GenerateAccessTokenRequest, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def pre_generate_access_token(self, request: common.GenerateAccessTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.GenerateAccessTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for generate_access_token Override in a subclass to manipulate the request or metadata @@ -124,9 +122,7 @@ def pre_generate_access_token( """ return request, metadata - def post_generate_access_token( - self, response: common.GenerateAccessTokenResponse - ) -> common.GenerateAccessTokenResponse: + def post_generate_access_token(self, response: common.GenerateAccessTokenResponse) -> common.GenerateAccessTokenResponse: """Post-rpc interceptor for generate_access_token DEPRECATED. Please use the `post_generate_access_token_with_metadata` @@ -139,13 +135,7 @@ def post_generate_access_token( """ return response - def post_generate_access_token_with_metadata( - self, - response: common.GenerateAccessTokenResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - common.GenerateAccessTokenResponse, Sequence[Tuple[str, Union[str, bytes]]] - ]: + def post_generate_access_token_with_metadata(self, response: common.GenerateAccessTokenResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.GenerateAccessTokenResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for generate_access_token Override in a subclass to read or manipulate the response or metadata after it @@ -160,11 +150,7 @@ def post_generate_access_token_with_metadata( """ return response, metadata - def pre_generate_id_token( - self, - request: common.GenerateIdTokenRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[common.GenerateIdTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_generate_id_token(self, request: common.GenerateIdTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.GenerateIdTokenRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for generate_id_token Override in a subclass to manipulate the request or metadata @@ -172,9 +158,7 @@ def pre_generate_id_token( """ return request, metadata - def post_generate_id_token( - self, response: common.GenerateIdTokenResponse - ) -> common.GenerateIdTokenResponse: + def post_generate_id_token(self, response: common.GenerateIdTokenResponse) -> common.GenerateIdTokenResponse: """Post-rpc interceptor for generate_id_token DEPRECATED. Please use the `post_generate_id_token_with_metadata` @@ -187,11 +171,7 @@ def post_generate_id_token( """ return response - def post_generate_id_token_with_metadata( - self, - response: common.GenerateIdTokenResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[common.GenerateIdTokenResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_generate_id_token_with_metadata(self, response: common.GenerateIdTokenResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.GenerateIdTokenResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for generate_id_token Override in a subclass to read or manipulate the response or metadata after it @@ -206,11 +186,7 @@ def post_generate_id_token_with_metadata( """ return response, metadata - def pre_sign_blob( - self, - request: common.SignBlobRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[common.SignBlobRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_sign_blob(self, request: common.SignBlobRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.SignBlobRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for sign_blob Override in a subclass to manipulate the request or metadata @@ -218,9 +194,7 @@ def pre_sign_blob( """ return request, metadata - def post_sign_blob( - self, response: common.SignBlobResponse - ) -> common.SignBlobResponse: + def post_sign_blob(self, response: common.SignBlobResponse) -> common.SignBlobResponse: """Post-rpc interceptor for sign_blob DEPRECATED. Please use the `post_sign_blob_with_metadata` @@ -233,11 +207,7 @@ def post_sign_blob( """ return response - def post_sign_blob_with_metadata( - self, - response: common.SignBlobResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[common.SignBlobResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_sign_blob_with_metadata(self, response: common.SignBlobResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.SignBlobResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for sign_blob Override in a subclass to read or manipulate the response or metadata after it @@ -252,11 +222,7 @@ def post_sign_blob_with_metadata( """ return response, metadata - def pre_sign_jwt( - self, - request: common.SignJwtRequest, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[common.SignJwtRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_sign_jwt(self, request: common.SignJwtRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.SignJwtRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for sign_jwt Override in a subclass to manipulate the request or metadata @@ -277,11 +243,7 @@ def post_sign_jwt(self, response: common.SignJwtResponse) -> common.SignJwtRespo """ return response - def post_sign_jwt_with_metadata( - self, - response: common.SignJwtResponse, - metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[common.SignJwtResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_sign_jwt_with_metadata(self, response: common.SignJwtResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[common.SignJwtResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for sign_jwt Override in a subclass to read or manipulate the response or metadata after it @@ -325,63 +287,62 @@ class IAMCredentialsRestTransport(_BaseIAMCredentialsRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "iamcredentials.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - interceptor: Optional[IAMCredentialsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'iamcredentials.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[IAMCredentialsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. - NOTE: This REST transport functionality is currently in a beta - state (preview). We welcome your feedback via a GitHub issue in - this library's repository. Thank you! - - Args: - host (Optional[str]): - The hostname to connect to (default: 'iamcredentials.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. This argument will be - removed in the next major version of this library. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - interceptor (Optional[IAMCredentialsRestInterceptor]): Interceptor used - to manipulate requests, request metadata, and responses. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iamcredentials.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[IAMCredentialsRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. """ # Run the base constructor # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. @@ -393,20 +354,16 @@ def __init__( client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience, + api_audience=api_audience ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST - ) + self._credentials, default_host=self.DEFAULT_HOST) if client_cert_source_for_mtls: self._session.configure_mtls_channel(client_cert_source_for_mtls) self._interceptor = interceptor or IAMCredentialsRestInterceptor() self._prep_wrapped_messages(client_info) - class _GenerateAccessToken( - _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken, - IAMCredentialsRestStub, - ): + class _GenerateAccessToken(_BaseIAMCredentialsRestTransport._BaseGenerateAccessToken, IAMCredentialsRestStub): def __hash__(self): return hash("IAMCredentialsRestTransport.GenerateAccessToken") @@ -418,29 +375,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: common.GenerateAccessTokenRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateAccessTokenResponse: + def __call__(self, + request: common.GenerateAccessTokenRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> common.GenerateAccessTokenResponse: r"""Call the generate access token method over HTTP. Args: @@ -461,42 +416,30 @@ def __call__( http_options = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_http_options() - request, metadata = self._interceptor.pre_generate_access_token( - request, metadata - ) - transcoded_request = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_generate_access_token(request, metadata) + transcoded_request = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_transcoded_request(http_options, request) - body = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_request_body_json( - transcoded_request - ) + body = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.GenerateAccessToken", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "GenerateAccessToken", "httpRequest": http_request, @@ -505,15 +448,7 @@ def __call__( ) # Send the request - response = IAMCredentialsRestTransport._GenerateAccessToken._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = IAMCredentialsRestTransport._GenerateAccessToken._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -528,26 +463,20 @@ def __call__( resp = self._interceptor.post_generate_access_token(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_generate_access_token_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_generate_access_token_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: - response_payload = common.GenerateAccessTokenResponse.to_json( - response - ) + response_payload = common.GenerateAccessTokenResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.iam.credentials_v1.IAMCredentialsClient.generate_access_token", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "GenerateAccessToken", "metadata": http_response["headers"], @@ -556,9 +485,7 @@ def __call__( ) return resp - class _GenerateIdToken( - _BaseIAMCredentialsRestTransport._BaseGenerateIdToken, IAMCredentialsRestStub - ): + class _GenerateIdToken(_BaseIAMCredentialsRestTransport._BaseGenerateIdToken, IAMCredentialsRestStub): def __hash__(self): return hash("IAMCredentialsRestTransport.GenerateIdToken") @@ -570,29 +497,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: common.GenerateIdTokenRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.GenerateIdTokenResponse: + def __call__(self, + request: common.GenerateIdTokenRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> common.GenerateIdTokenResponse: r"""Call the generate id token method over HTTP. Args: @@ -613,42 +538,30 @@ def __call__( http_options = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_http_options() - request, metadata = self._interceptor.pre_generate_id_token( - request, metadata - ) - transcoded_request = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_generate_id_token(request, metadata) + transcoded_request = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_transcoded_request(http_options, request) - body = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_request_body_json( - transcoded_request - ) + body = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_query_params_json( - transcoded_request - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + query_params = _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.GenerateIdToken", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "GenerateIdToken", "httpRequest": http_request, @@ -657,15 +570,7 @@ def __call__( ) # Send the request - response = IAMCredentialsRestTransport._GenerateIdToken._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = IAMCredentialsRestTransport._GenerateIdToken._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -680,24 +585,20 @@ def __call__( resp = self._interceptor.post_generate_id_token(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_generate_id_token_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_generate_id_token_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = common.GenerateIdTokenResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.iam.credentials_v1.IAMCredentialsClient.generate_id_token", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "GenerateIdToken", "metadata": http_response["headers"], @@ -706,9 +607,7 @@ def __call__( ) return resp - class _SignBlob( - _BaseIAMCredentialsRestTransport._BaseSignBlob, IAMCredentialsRestStub - ): + class _SignBlob(_BaseIAMCredentialsRestTransport._BaseSignBlob, IAMCredentialsRestStub): def __hash__(self): return hash("IAMCredentialsRestTransport.SignBlob") @@ -720,29 +619,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: common.SignBlobRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignBlobResponse: + def __call__(self, + request: common.SignBlobRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> common.SignBlobResponse: r"""Call the sign blob method over HTTP. Args: @@ -761,50 +658,32 @@ def __call__( """ - http_options = ( - _BaseIAMCredentialsRestTransport._BaseSignBlob._get_http_options() - ) + http_options = _BaseIAMCredentialsRestTransport._BaseSignBlob._get_http_options() request, metadata = self._interceptor.pre_sign_blob(request, metadata) - transcoded_request = ( - _BaseIAMCredentialsRestTransport._BaseSignBlob._get_transcoded_request( - http_options, request - ) - ) + transcoded_request = _BaseIAMCredentialsRestTransport._BaseSignBlob._get_transcoded_request(http_options, request) - body = ( - _BaseIAMCredentialsRestTransport._BaseSignBlob._get_request_body_json( - transcoded_request - ) - ) + body = _BaseIAMCredentialsRestTransport._BaseSignBlob._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = ( - _BaseIAMCredentialsRestTransport._BaseSignBlob._get_query_params_json( - transcoded_request - ) - ) + query_params = _BaseIAMCredentialsRestTransport._BaseSignBlob._get_query_params_json(transcoded_request) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.SignBlob", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "SignBlob", "httpRequest": http_request, @@ -813,15 +692,7 @@ def __call__( ) # Send the request - response = IAMCredentialsRestTransport._SignBlob._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = IAMCredentialsRestTransport._SignBlob._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -836,24 +707,20 @@ def __call__( resp = self._interceptor.post_sign_blob(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_sign_blob_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_sign_blob_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = common.SignBlobResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.iam.credentials_v1.IAMCredentialsClient.sign_blob", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "SignBlob", "metadata": http_response["headers"], @@ -862,9 +729,7 @@ def __call__( ) return resp - class _SignJwt( - _BaseIAMCredentialsRestTransport._BaseSignJwt, IAMCredentialsRestStub - ): + class _SignJwt(_BaseIAMCredentialsRestTransport._BaseSignJwt, IAMCredentialsRestStub): def __hash__(self): return hash("IAMCredentialsRestTransport.SignJwt") @@ -876,29 +741,27 @@ def _get_response( session, timeout, transcoded_request, - body=None, - ): - uri = transcoded_request["uri"] - method = transcoded_request["method"] + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] headers = dict(metadata) - headers["Content-Type"] = "application/json" + headers['Content-Type'] = 'application/json' response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__( - self, - request: common.SignJwtRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> common.SignJwtResponse: + def __call__(self, + request: common.SignJwtRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> common.SignJwtResponse: r"""Call the sign jwt method over HTTP. Args: @@ -917,48 +780,32 @@ def __call__( """ - http_options = ( - _BaseIAMCredentialsRestTransport._BaseSignJwt._get_http_options() - ) + http_options = _BaseIAMCredentialsRestTransport._BaseSignJwt._get_http_options() request, metadata = self._interceptor.pre_sign_jwt(request, metadata) - transcoded_request = ( - _BaseIAMCredentialsRestTransport._BaseSignJwt._get_transcoded_request( - http_options, request - ) - ) + transcoded_request = _BaseIAMCredentialsRestTransport._BaseSignJwt._get_transcoded_request(http_options, request) - body = _BaseIAMCredentialsRestTransport._BaseSignJwt._get_request_body_json( - transcoded_request - ) + body = _BaseIAMCredentialsRestTransport._BaseSignJwt._get_request_body_json(transcoded_request) # Jsonify the query params - query_params = ( - _BaseIAMCredentialsRestTransport._BaseSignJwt._get_query_params_json( - transcoded_request - ) - ) + query_params = _BaseIAMCredentialsRestTransport._BaseSignJwt._get_query_params_json(transcoded_request) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER - request_url = "{host}{uri}".format( - host=self._host, uri=transcoded_request["uri"] - ) - method = transcoded_request["method"] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.iam.credentials_v1.IAMCredentialsClient.SignJwt", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "SignJwt", "httpRequest": http_request, @@ -967,15 +814,7 @@ def __call__( ) # Send the request - response = IAMCredentialsRestTransport._SignJwt._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = IAMCredentialsRestTransport._SignJwt._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -990,24 +829,20 @@ def __call__( resp = self._interceptor.post_sign_jwt(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_sign_jwt_with_metadata( - resp, response_metadata - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - logging.DEBUG - ): # pragma: NO COVER + resp, _ = self._interceptor.post_sign_jwt_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER try: response_payload = common.SignJwtResponse.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.iam.credentials_v1.IAMCredentialsClient.sign_jwt", - extra={ + extra = { "serviceName": "google.iam.credentials.v1.IAMCredentials", "rpcName": "SignJwt", "metadata": http_response["headers"], @@ -1017,34 +852,36 @@ def __call__( return resp @property - def generate_access_token( - self, - ) -> Callable[ - [common.GenerateAccessTokenRequest], common.GenerateAccessTokenResponse - ]: + def generate_access_token(self) -> Callable[ + [common.GenerateAccessTokenRequest], + common.GenerateAccessTokenResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore + return self._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore @property - def generate_id_token( - self, - ) -> Callable[[common.GenerateIdTokenRequest], common.GenerateIdTokenResponse]: + def generate_id_token(self) -> Callable[ + [common.GenerateIdTokenRequest], + common.GenerateIdTokenResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GenerateIdToken(self._session, self._host, self._interceptor) # type: ignore + return self._GenerateIdToken(self._session, self._host, self._interceptor) # type: ignore @property - def sign_blob(self) -> Callable[[common.SignBlobRequest], common.SignBlobResponse]: + def sign_blob(self) -> Callable[ + [common.SignBlobRequest], + common.SignBlobResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._SignBlob(self._session, self._host, self._interceptor) # type: ignore + return self._SignBlob(self._session, self._host, self._interceptor) # type: ignore @property - def sign_jwt(self) -> Callable[[common.SignJwtRequest], common.SignJwtResponse]: + def sign_jwt(self) -> Callable[ + [common.SignJwtRequest], + common.SignJwtResponse]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._SignJwt(self._session, self._host, self._interceptor) # type: ignore + return self._SignJwt(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -1054,4 +891,6 @@ def close(self): self._session.close() -__all__ = ("IAMCredentialsRestTransport",) +__all__=( + 'IAMCredentialsRestTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest_base.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest_base.py index 9ab06189f107..a03907410f78 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest_base.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/rest_base.py @@ -14,16 +14,18 @@ # limitations under the License. # import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import IAMCredentialsTransport, DEFAULT_CLIENT_INFO + import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1, path_template -from google.protobuf import json_format from google.iam.credentials_v1.types import common -from .base import DEFAULT_CLIENT_INFO, IAMCredentialsTransport - class _BaseIAMCredentialsRestTransport(IAMCredentialsTransport): """Base REST backend transport for IAMCredentials. @@ -38,16 +40,14 @@ class _BaseIAMCredentialsRestTransport(IAMCredentialsTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__( - self, - *, - host: str = "iamcredentials.googleapis.com", - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - api_audience: Optional[str] = None, - ) -> None: + def __init__(self, *, + host: str = 'iamcredentials.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: host (Optional[str]): @@ -71,9 +71,7 @@ def __init__( # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError( - f"Unexpected hostname structure: {host}" - ) # pragma: NO COVER + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -84,31 +82,27 @@ def __init__( credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, + api_audience=api_audience ) class _BaseGenerateAccessToken: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/serviceAccounts/*}:generateAccessToken", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/serviceAccounts/*}:generateAccessToken', + 'body': '*', + }, ] return http_options @@ -123,23 +117,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=False + transcoded_request['body'], + use_integers_for_enums=False ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=False, - ) - ) - query_params.update( - _BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseIAMCredentialsRestTransport._BaseGenerateAccessToken._get_unset_required_fields(query_params)) return query_params @@ -147,24 +135,20 @@ class _BaseGenerateIdToken: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/serviceAccounts/*}:generateIdToken", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/serviceAccounts/*}:generateIdToken', + 'body': '*', + }, ] return http_options @@ -179,23 +163,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=False + transcoded_request['body'], + use_integers_for_enums=False ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=False, - ) - ) - query_params.update( - _BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseIAMCredentialsRestTransport._BaseGenerateIdToken._get_unset_required_fields(query_params)) return query_params @@ -203,24 +181,20 @@ class _BaseSignBlob: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/serviceAccounts/*}:signBlob", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/serviceAccounts/*}:signBlob', + 'body': '*', + }, ] return http_options @@ -235,23 +209,17 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=False + transcoded_request['body'], + use_integers_for_enums=False ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=False, - ) - ) - query_params.update( - _BaseIAMCredentialsRestTransport._BaseSignBlob._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseIAMCredentialsRestTransport._BaseSignBlob._get_unset_required_fields(query_params)) return query_params @@ -259,24 +227,20 @@ class _BaseSignJwt: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } @classmethod def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1/{name=projects/*/serviceAccounts/*}:signJwt", - "body": "*", - }, + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/serviceAccounts/*}:signJwt', + 'body': '*', + }, ] return http_options @@ -291,25 +255,21 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=False + transcoded_request['body'], + use_integers_for_enums=False ) return body - @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=False, - ) - ) - query_params.update( - _BaseIAMCredentialsRestTransport._BaseSignJwt._get_unset_required_fields( - query_params - ) - ) + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=False, + )) + query_params.update(_BaseIAMCredentialsRestTransport._BaseSignJwt._get_unset_required_fields(query_params)) return query_params -__all__ = ("_BaseIAMCredentialsRestTransport",) +__all__=( + '_BaseIAMCredentialsRestTransport', +) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/__init__.py index e3846fefa8fb..f257b889924c 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/__init__.py @@ -25,12 +25,12 @@ ) __all__ = ( - "GenerateAccessTokenRequest", - "GenerateAccessTokenResponse", - "GenerateIdTokenRequest", - "GenerateIdTokenResponse", - "SignBlobRequest", - "SignBlobResponse", - "SignJwtRequest", - "SignJwtResponse", + 'GenerateAccessTokenRequest', + 'GenerateAccessTokenResponse', + 'GenerateIdTokenRequest', + 'GenerateIdTokenResponse', + 'SignBlobRequest', + 'SignBlobResponse', + 'SignJwtRequest', + 'SignJwtResponse', ) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/common.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/common.py index f2f42dd93afe..1acdee2180bc 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/common.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/common.py @@ -17,21 +17,23 @@ from typing import MutableMapping, MutableSequence +import proto # type: ignore + import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -import proto # type: ignore + __protobuf__ = proto.module( - package="google.iam.credentials.v1", + package='google.iam.credentials.v1', manifest={ - "GenerateAccessTokenRequest", - "GenerateAccessTokenResponse", - "SignBlobRequest", - "SignBlobResponse", - "SignJwtRequest", - "SignJwtResponse", - "GenerateIdTokenRequest", - "GenerateIdTokenResponse", + 'GenerateAccessTokenRequest', + 'GenerateAccessTokenResponse', + 'SignBlobRequest', + 'SignBlobResponse', + 'SignJwtRequest', + 'SignJwtResponse', + 'GenerateIdTokenRequest', + 'GenerateIdTokenResponse', }, ) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/iamcredentials.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/iamcredentials.py index 1616a02036f5..17d048bd5d33 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/iamcredentials.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/types/iamcredentials.py @@ -15,9 +15,11 @@ # import proto # type: ignore + __protobuf__ = proto.module( - package="google.iam.credentials.v1", - manifest={}, + package='google.iam.credentials.v1', + manifest={ + }, ) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py b/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py index 46b2de6633e6..5d529145149f 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/noxfile.py @@ -17,8 +17,9 @@ import pathlib import re import shutil -import warnings + from typing import Dict, List +import warnings import nox @@ -152,8 +153,7 @@ def lint(session): # 2. Check formatting session.run( - "ruff", - "format", + "ruff", "format", "--check", f"--target-version=py{ALL_PYTHON[0].replace('.', '')}", "--line-length=88", @@ -166,15 +166,12 @@ def lint(session): @nox.session(python=DEFAULT_PYTHON_VERSION) def blacken(session): """(Deprecated) Legacy session. Please use 'nox -s format'.""" - session.log( - "WARNING: The 'blacken' session is deprecated and will be removed in a future release. Please use 'nox -s format' in the future." - ) + session.log("WARNING: The 'blacken' session is deprecated and will be removed in a future release. Please use 'nox -s format' in the future.") # Just run the ruff formatter (keeping legacy behavior of only formatting, not sorting imports) session.install(RUFF_VERSION) session.run( - "ruff", - "format", + "ruff", "format", f"--target-version=py{ALL_PYTHON[0].replace('.', '')}", "--line-length=88", *LINT_PATHS, @@ -193,10 +190,8 @@ def format(session): # check --select I: Enables strict import sorting # --fix: Applies the changes automatically session.run( - "ruff", - "check", - "--select", - "I", + "ruff", "check", + "--select", "I", "--fix", f"--target-version=py{ALL_PYTHON[0].replace('.', '')}", "--line-length=88", # Standard Black line length @@ -205,8 +200,7 @@ def format(session): # 3. Run Ruff to format code session.run( - "ruff", - "format", + "ruff", "format", f"--target-version=py{ALL_PYTHON[0].replace('.', '')}", "--line-length=88", # Standard Black line length *LINT_PATHS, @@ -391,10 +385,8 @@ def docs(session): "sphinx-build", "-T", # show full traceback on exception "-N", # no colors - "-b", - "html", # builder - "-d", - os.path.join("docs", "_build", "doctrees", ""), # cache directory + "-b", "html", # builder + "-d", os.path.join("docs", "_build", "doctrees", ""), # cache directory # paths to build: os.path.join("docs", ""), os.path.join("docs", "_build", "html", ""), diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_access_token_async.py b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_access_token_async.py index 05017303872a..23cdbcb65d98 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_access_token_async.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_access_token_async.py @@ -41,7 +41,7 @@ async def sample_generate_access_token(): # Initialize request argument(s) request = credentials_v1.GenerateAccessTokenRequest( name="name_value", - scope=["scope_value1", "scope_value2"], + scope=['scope_value1', 'scope_value2'], ) # Make the request @@ -50,5 +50,4 @@ async def sample_generate_access_token(): # Handle the response print(response) - # [END iamcredentials_v1_generated_IAMCredentials_GenerateAccessToken_async] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_access_token_sync.py b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_access_token_sync.py index 045e84d0e6e5..b7890bd0106e 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_access_token_sync.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_access_token_sync.py @@ -41,7 +41,7 @@ def sample_generate_access_token(): # Initialize request argument(s) request = credentials_v1.GenerateAccessTokenRequest( name="name_value", - scope=["scope_value1", "scope_value2"], + scope=['scope_value1', 'scope_value2'], ) # Make the request @@ -50,5 +50,4 @@ def sample_generate_access_token(): # Handle the response print(response) - # [END iamcredentials_v1_generated_IAMCredentials_GenerateAccessToken_sync] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_id_token_async.py b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_id_token_async.py index 6a7bf6b56b4d..0215ccea7f69 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_id_token_async.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_id_token_async.py @@ -50,5 +50,4 @@ async def sample_generate_id_token(): # Handle the response print(response) - # [END iamcredentials_v1_generated_IAMCredentials_GenerateIdToken_async] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_id_token_sync.py b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_id_token_sync.py index 664b7794a48e..cf2199eae2ca 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_id_token_sync.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_generate_id_token_sync.py @@ -50,5 +50,4 @@ def sample_generate_id_token(): # Handle the response print(response) - # [END iamcredentials_v1_generated_IAMCredentials_GenerateIdToken_sync] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_blob_async.py b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_blob_async.py index 19218118f134..9dd1113be682 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_blob_async.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_blob_async.py @@ -41,7 +41,7 @@ async def sample_sign_blob(): # Initialize request argument(s) request = credentials_v1.SignBlobRequest( name="name_value", - payload=b"payload_blob", + payload=b'payload_blob', ) # Make the request @@ -50,5 +50,4 @@ async def sample_sign_blob(): # Handle the response print(response) - # [END iamcredentials_v1_generated_IAMCredentials_SignBlob_async] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_blob_sync.py b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_blob_sync.py index 715257d344a9..62752da45472 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_blob_sync.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_blob_sync.py @@ -41,7 +41,7 @@ def sample_sign_blob(): # Initialize request argument(s) request = credentials_v1.SignBlobRequest( name="name_value", - payload=b"payload_blob", + payload=b'payload_blob', ) # Make the request @@ -50,5 +50,4 @@ def sample_sign_blob(): # Handle the response print(response) - # [END iamcredentials_v1_generated_IAMCredentials_SignBlob_sync] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_jwt_async.py b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_jwt_async.py index 5a01a1bfaf3c..3022b82a96d2 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_jwt_async.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_jwt_async.py @@ -50,5 +50,4 @@ async def sample_sign_jwt(): # Handle the response print(response) - # [END iamcredentials_v1_generated_IAMCredentials_SignJwt_async] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_jwt_sync.py b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_jwt_sync.py index 41115a20f45f..3c6faea9b194 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_jwt_sync.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/samples/generated_samples/iamcredentials_v1_generated_iam_credentials_sign_jwt_sync.py @@ -50,5 +50,4 @@ def sample_sign_jwt(): # Handle the response print(response) - # [END iamcredentials_v1_generated_IAMCredentials_SignJwt_sync] diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/setup.py b/packages/gapic-generator/tests/integration/goldens/credentials/setup.py index 73ee574867e2..74e94c582cc0 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/setup.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/setup.py @@ -17,20 +17,20 @@ import os import re -import setuptools # type: ignore +import setuptools # type: ignore package_root = os.path.abspath(os.path.dirname(__file__)) -name = "google-iam-credentials" +name = 'google-iam-credentials' description = "Google Iam Credentials API client library" version = None -with open(os.path.join(package_root, "google/iam/credentials/gapic_version.py")) as fp: +with open(os.path.join(package_root, 'google/iam/credentials/gapic_version.py')) as fp: version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert len(version_candidates) == 1 + assert (len(version_candidates) == 1) version = version_candidates[0] if version[0] == "0": @@ -49,7 +49,8 @@ "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", "protobuf >= 4.25.8, < 8.0.0", ] -extras = {} +extras = { +} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-iam-credentials" package_root = os.path.abspath(os.path.dirname(__file__)) diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/__init__.py index cbf94b283c70..191773d5572d 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/__init__.py @@ -1,3 +1,4 @@ + # -*- coding: utf-8 -*- # Copyright 2025 Google LLC # diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/__init__.py index cbf94b283c70..191773d5572d 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/__init__.py @@ -1,3 +1,4 @@ + # -*- coding: utf-8 -*- # Copyright 2025 Google LLC # diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/__init__.py index cbf94b283c70..191773d5572d 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/__init__.py @@ -1,3 +1,4 @@ + # -*- coding: utf-8 -*- # Copyright 2025 Google LLC # diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/__init__.py index cbf94b283c70..191773d5572d 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/__init__.py @@ -1,3 +1,4 @@ + # -*- coding: utf-8 -*- # Copyright 2025 Google LLC # diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py index 36d38d23554a..f890571724a9 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py @@ -13,52 +13,51 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import json -import math import os -from collections.abc import AsyncIterable, Iterable, Mapping, Sequence from unittest import mock from unittest.mock import AsyncMock import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math import pytest +from collections.abc import Sequence, Mapping from google.api_core import api_core_version -from google.protobuf import json_format -from grpc.experimental import aio -from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule -from requests import PreparedRequest, Request, Response +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest from requests.sessions import Session +from google.protobuf import json_format try: from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER +except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False -import google.auth -import google.protobuf.duration_pb2 as duration_pb2 # type: ignore -import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore -from google.api_core import ( - client_options, - gapic_v1, - grpc_helpers, - grpc_helpers_async, - path_template, -) +from google.api_core import client_options from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template from google.api_core import retry as retries from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.iam.credentials_v1.services.iam_credentials import IAMCredentialsAsyncClient +from google.iam.credentials_v1.services.iam_credentials import IAMCredentialsClient +from google.iam.credentials_v1.services.iam_credentials import transports +from google.iam.credentials_v1.types import common from google.oauth2 import service_account +import google.auth +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore + -from google.iam.credentials_v1.services.iam_credentials import ( - IAMCredentialsAsyncClient, - IAMCredentialsClient, - transports, -) -from google.iam.credentials_v1.types import common CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -73,11 +72,9 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") - def client_cert_source_callback(): return b"cert bytes", b"key bytes" - # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -85,27 +82,17 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() - # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return ( - "foo.googleapis.com" - if ("localhost" in client.DEFAULT_ENDPOINT) - else client.DEFAULT_ENDPOINT - ) - + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return ( - "test.{UNIVERSE_DOMAIN}" - if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) - else client._DEFAULT_ENDPOINT_TEMPLATE - ) + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE def test__get_default_mtls_endpoint(): @@ -117,47 +104,21 @@ def test__get_default_mtls_endpoint(): custom_endpoint = ".custom" assert IAMCredentialsClient._get_default_mtls_endpoint(None) is None - assert ( - IAMCredentialsClient._get_default_mtls_endpoint(api_endpoint) - == api_mtls_endpoint - ) - assert ( - IAMCredentialsClient._get_default_mtls_endpoint(api_mtls_endpoint) - == api_mtls_endpoint - ) - assert ( - IAMCredentialsClient._get_default_mtls_endpoint(sandbox_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - IAMCredentialsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - IAMCredentialsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - ) - assert ( - IAMCredentialsClient._get_default_mtls_endpoint(custom_endpoint) - == custom_endpoint - ) - + assert IAMCredentialsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert IAMCredentialsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert IAMCredentialsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert IAMCredentialsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert IAMCredentialsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert IAMCredentialsClient._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint def test__read_environment_variables(): assert IAMCredentialsClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert IAMCredentialsClient._read_environment_variables() == ( - True, - "auto", - None, - ) + assert IAMCredentialsClient._read_environment_variables() == (True, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert IAMCredentialsClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert IAMCredentialsClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} @@ -171,46 +132,27 @@ def test__read_environment_variables(): ) else: assert IAMCredentialsClient._read_environment_variables() == ( - False, - "auto", - None, - ) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert IAMCredentialsClient._read_environment_variables() == ( False, - "never", + "auto", None, ) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert IAMCredentialsClient._read_environment_variables() == (False, "never", None) + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert IAMCredentialsClient._read_environment_variables() == ( - False, - "always", - None, - ) + assert IAMCredentialsClient._read_environment_variables() == (False, "always", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert IAMCredentialsClient._read_environment_variables() == ( - False, - "auto", - None, - ) + assert IAMCredentialsClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: IAMCredentialsClient._read_environment_variables() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert IAMCredentialsClient._read_environment_variables() == ( - False, - "auto", - "foo.com", - ) + assert IAMCredentialsClient._read_environment_variables() == (False, "auto", "foo.com") def test_use_client_cert_effective(): @@ -219,9 +161,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=True - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=True): assert IAMCredentialsClient._use_client_cert_effective() is True # Test case 2: Test when `should_use_client_cert` returns False. @@ -229,9 +169,7 @@ def test_use_client_cert_effective(): # the google-auth library supports automatic mTLS and determines that a # client certificate should NOT be used. if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch( - "google.auth.transport.mtls.should_use_client_cert", return_value=False - ): + with mock.patch("google.auth.transport.mtls.should_use_client_cert", return_value=False): assert IAMCredentialsClient._use_client_cert_effective() is False # Test case 3: Test when `should_use_client_cert` is unavailable and the @@ -243,9 +181,7 @@ def test_use_client_cert_effective(): # Test case 4: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): assert IAMCredentialsClient._use_client_cert_effective() is False # Test case 5: Test when `should_use_client_cert` is unavailable and the @@ -257,9 +193,7 @@ def test_use_client_cert_effective(): # Test case 6: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"}): assert IAMCredentialsClient._use_client_cert_effective() is False # Test case 7: Test when `should_use_client_cert` is unavailable and the @@ -271,9 +205,7 @@ def test_use_client_cert_effective(): # Test case 8: Test when `should_use_client_cert` is unavailable and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"}): assert IAMCredentialsClient._use_client_cert_effective() is False # Test case 9: Test when `should_use_client_cert` is unavailable and the @@ -288,167 +220,83 @@ def test_use_client_cert_effective(): # The method should raise a ValueError as the environment variable must be either # "true" or "false". if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): with pytest.raises(ValueError): IAMCredentialsClient._use_client_cert_effective() # Test case 11: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. # The method should return False as the environment variable is set to an invalid value. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} - ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"}): assert IAMCredentialsClient._use_client_cert_effective() is False # Test case 12: Test when `should_use_client_cert` is available and the # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, # the GOOGLE_API_CONFIG environment variable is unset. - if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): assert IAMCredentialsClient._use_client_cert_effective() is False - def test__get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() assert IAMCredentialsClient._get_client_cert_source(None, False) is None - assert ( - IAMCredentialsClient._get_client_cert_source(mock_provided_cert_source, False) - is None - ) - assert ( - IAMCredentialsClient._get_client_cert_source(mock_provided_cert_source, True) - == mock_provided_cert_source - ) + assert IAMCredentialsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert IAMCredentialsClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", return_value=True - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_default_cert_source, - ): - assert ( - IAMCredentialsClient._get_client_cert_source(None, True) - is mock_default_cert_source - ) - assert ( - IAMCredentialsClient._get_client_cert_source( - mock_provided_cert_source, "true" - ) - is mock_provided_cert_source - ) + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert IAMCredentialsClient._get_client_cert_source(None, True) is mock_default_cert_source + assert IAMCredentialsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object( - IAMCredentialsClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(IAMCredentialsClient), -) -@mock.patch.object( - IAMCredentialsAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(IAMCredentialsAsyncClient), -) +@mock.patch.object(IAMCredentialsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMCredentialsClient)) +@mock.patch.object(IAMCredentialsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMCredentialsAsyncClient)) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = IAMCredentialsClient._DEFAULT_UNIVERSE - default_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - assert ( - IAMCredentialsClient._get_api_endpoint( - api_override, mock_client_cert_source, default_universe, "always" - ) - == api_override - ) - assert ( - IAMCredentialsClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "auto" - ) - == IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - IAMCredentialsClient._get_api_endpoint(None, None, default_universe, "auto") - == default_endpoint - ) - assert ( - IAMCredentialsClient._get_api_endpoint(None, None, default_universe, "always") - == IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - IAMCredentialsClient._get_api_endpoint( - None, mock_client_cert_source, default_universe, "always" - ) - == IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT - ) - assert ( - IAMCredentialsClient._get_api_endpoint(None, None, mock_universe, "never") - == mock_endpoint - ) - assert ( - IAMCredentialsClient._get_api_endpoint(None, None, default_universe, "never") - == default_endpoint - ) + assert IAMCredentialsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert IAMCredentialsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT + assert IAMCredentialsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert IAMCredentialsClient._get_api_endpoint(None, None, default_universe, "always") == IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT + assert IAMCredentialsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == IAMCredentialsClient.DEFAULT_MTLS_ENDPOINT + assert IAMCredentialsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert IAMCredentialsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint with pytest.raises(MutualTLSChannelError) as excinfo: - IAMCredentialsClient._get_api_endpoint( - None, mock_client_cert_source, mock_universe, "auto" - ) - assert ( - str(excinfo.value) - == "mTLS is not supported in any universe other than googleapis.com." - ) + IAMCredentialsClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." def test__get_universe_domain(): client_universe_domain = "foo.com" universe_domain_env = "bar.com" - assert ( - IAMCredentialsClient._get_universe_domain( - client_universe_domain, universe_domain_env - ) - == client_universe_domain - ) - assert ( - IAMCredentialsClient._get_universe_domain(None, universe_domain_env) - == universe_domain_env - ) - assert ( - IAMCredentialsClient._get_universe_domain(None, None) - == IAMCredentialsClient._DEFAULT_UNIVERSE - ) + assert IAMCredentialsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert IAMCredentialsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert IAMCredentialsClient._get_universe_domain(None, None) == IAMCredentialsClient._DEFAULT_UNIVERSE with pytest.raises(ValueError) as excinfo: IAMCredentialsClient._get_universe_domain("", None) assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize( - "error_code,cred_info_json,show_cred_info", - [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False), - ], -) +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): cred = mock.Mock(["get_cred_info"]) cred.get_cred_info = mock.Mock(return_value=cred_info_json) @@ -464,8 +312,7 @@ def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_in else: assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +@pytest.mark.parametrize("error_code", [401,403,404,500]) def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): cred = mock.Mock([]) assert not hasattr(cred, "get_cred_info") @@ -478,20 +325,14 @@ def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): client._add_cred_info_for_auth_errors(error) assert error.details == [] - -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (IAMCredentialsClient, "grpc"), - (IAMCredentialsAsyncClient, "grpc_asyncio"), - (IAMCredentialsClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (IAMCredentialsClient, "grpc"), + (IAMCredentialsAsyncClient, "grpc_asyncio"), + (IAMCredentialsClient, "rest"), +]) def test_iam_credentials_client_from_service_account_info(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_info" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info, transport=transport_name) @@ -499,68 +340,52 @@ def test_iam_credentials_client_from_service_account_info(client_class, transpor assert isinstance(client, client_class) assert client.transport._host == ( - "iamcredentials.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://iamcredentials.googleapis.com" + 'iamcredentials.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://iamcredentials.googleapis.com' ) -@pytest.mark.parametrize( - "transport_class,transport_name", - [ - (transports.IAMCredentialsGrpcTransport, "grpc"), - (transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.IAMCredentialsRestTransport, "rest"), - ], -) -def test_iam_credentials_client_service_account_always_use_jwt( - transport_class, transport_name -): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.IAMCredentialsGrpcTransport, "grpc"), + (transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.IAMCredentialsRestTransport, "rest"), +]) +def test_iam_credentials_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() -@pytest.mark.parametrize( - "client_class,transport_name", - [ - (IAMCredentialsClient, "grpc"), - (IAMCredentialsAsyncClient, "grpc_asyncio"), - (IAMCredentialsClient, "rest"), - ], -) +@pytest.mark.parametrize("client_class,transport_name", [ + (IAMCredentialsClient, "grpc"), + (IAMCredentialsAsyncClient, "grpc_asyncio"), + (IAMCredentialsClient, "rest"), +]) def test_iam_credentials_client_from_service_account_file(client_class, transport_name): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_file" - ) as factory: + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: factory.return_value = creds - client = client_class.from_service_account_file( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) - client = client_class.from_service_account_json( - "dummy/file/path.json", transport=transport_name - ) + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == ( - "iamcredentials.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://iamcredentials.googleapis.com" + 'iamcredentials.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://iamcredentials.googleapis.com' ) @@ -576,45 +401,30 @@ def test_iam_credentials_client_get_transport_class(): assert transport == transports.IAMCredentialsGrpcTransport -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc"), - ( - IAMCredentialsAsyncClient, - transports.IAMCredentialsGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest"), - ], -) -@mock.patch.object( - IAMCredentialsClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(IAMCredentialsClient), -) -@mock.patch.object( - IAMCredentialsAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(IAMCredentialsAsyncClient), -) -def test_iam_credentials_client_client_options( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc"), + (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio"), + (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest"), +]) +@mock.patch.object(IAMCredentialsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMCredentialsClient)) +@mock.patch.object(IAMCredentialsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMCredentialsAsyncClient)) +def test_iam_credentials_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. - with mock.patch.object(IAMCredentialsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + with mock.patch.object(IAMCredentialsClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) client = client_class(transport=transport) gtc.assert_not_called() # Check that if channel is provided via str we will create a new one. - with mock.patch.object(IAMCredentialsClient, "get_transport_class") as gtc: + with mock.patch.object(IAMCredentialsClient, 'get_transport_class') as gtc: client = client_class(transport=transport_name) gtc.assert_called() # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( @@ -632,15 +442,13 @@ def test_iam_credentials_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -652,7 +460,7 @@ def test_iam_credentials_client_client_options( # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -672,22 +480,17 @@ def test_iam_credentials_client_client_options( with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: client = client_class(transport=transport_name) - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id="octopus", @@ -696,82 +499,48 @@ def test_iam_credentials_client_client_options( api_audience=None, ) # Check the case api_endpoint is provided - options = client_options.ClientOptions( - api_audience="https://language.googleapis.com" - ) - with mock.patch.object(transport_class, "__init__") as patched: + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, - api_audience="https://language.googleapis.com", - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,use_client_cert_env", - [ - (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc", "true"), - ( - IAMCredentialsAsyncClient, - transports.IAMCredentialsGrpcAsyncIOTransport, - "grpc_asyncio", - "true", - ), - (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc", "false"), - ( - IAMCredentialsAsyncClient, - transports.IAMCredentialsGrpcAsyncIOTransport, - "grpc_asyncio", - "false", - ), - (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest", "true"), - (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest", "false"), - ], -) -@mock.patch.object( - IAMCredentialsClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(IAMCredentialsClient), -) -@mock.patch.object( - IAMCredentialsAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(IAMCredentialsAsyncClient), -) + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc", "true"), + (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc", "false"), + (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest", "true"), + (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest", "false"), +]) +@mock.patch.object(IAMCredentialsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMCredentialsClient)) +@mock.patch.object(IAMCredentialsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMCredentialsAsyncClient)) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_iam_credentials_client_mtls_env_auto( - client_class, transport_class, transport_name, use_client_cert_env -): +def test_iam_credentials_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) else: expected_client_cert_source = client_cert_source_callback expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -790,22 +559,12 @@ def test_iam_credentials_client_mtls_env_auto( # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=client_cert_source_callback, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -826,22 +585,15 @@ def test_iam_credentials_client_mtls_env_auto( ) # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -851,31 +603,19 @@ def test_iam_credentials_client_mtls_env_auto( ) -@pytest.mark.parametrize( - "client_class", [IAMCredentialsClient, IAMCredentialsAsyncClient] -) -@mock.patch.object( - IAMCredentialsClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(IAMCredentialsClient), -) -@mock.patch.object( - IAMCredentialsAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(IAMCredentialsAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + IAMCredentialsClient, IAMCredentialsAsyncClient +]) +@mock.patch.object(IAMCredentialsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IAMCredentialsClient)) +@mock.patch.object(IAMCredentialsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IAMCredentialsAsyncClient)) def test_iam_credentials_client_get_mtls_endpoint_and_cert_source(client_class): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source == mock_client_cert_source @@ -883,25 +623,18 @@ def test_iam_credentials_client_get_mtls_endpoint_and_cert_source(client_class): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint - ) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( - options - ) + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) assert api_endpoint == mock_api_endpoint assert cert_source is None # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} - ): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): if hasattr(google.auth.transport.mtls, "should_use_client_cert"): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options @@ -938,23 +671,23 @@ def test_iam_credentials_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). test_cases = [ @@ -985,23 +718,23 @@ def test_iam_credentials_client_get_mtls_endpoint_and_cert_source(client_class): env = os.environ.copy() env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") with mock.patch.dict(os.environ, env, clear=True): - config_filename = "mock_certificate_config.json" - config_file_content = json.dumps(config_data) - m = mock.mock_open(read_data=config_file_content) - with mock.patch("builtins.open", m): - with mock.patch.dict( - os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} - ): - mock_api_endpoint = "foo" - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, - api_endpoint=mock_api_endpoint, - ) - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source(options) - ) - assert api_endpoint == mock_api_endpoint - assert cert_source is expected_cert_source + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): @@ -1017,27 +750,16 @@ def test_iam_credentials_client_get_mtls_endpoint_and_cert_source(client_class): # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - with mock.patch( - "google.auth.transport.mtls.default_client_cert_source", - return_value=mock_client_cert_source, - ): - api_endpoint, cert_source = ( - client_class.get_mtls_endpoint_and_cert_source() - ) + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -1047,50 +769,27 @@ def test_iam_credentials_client_get_mtls_endpoint_and_cert_source(client_class): with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert ( - str(excinfo.value) - == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - ) - + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" -@pytest.mark.parametrize( - "client_class", [IAMCredentialsClient, IAMCredentialsAsyncClient] -) -@mock.patch.object( - IAMCredentialsClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(IAMCredentialsClient), -) -@mock.patch.object( - IAMCredentialsAsyncClient, - "_DEFAULT_ENDPOINT_TEMPLATE", - modify_default_endpoint_template(IAMCredentialsAsyncClient), -) +@pytest.mark.parametrize("client_class", [ + IAMCredentialsClient, IAMCredentialsAsyncClient +]) +@mock.patch.object(IAMCredentialsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMCredentialsClient)) +@mock.patch.object(IAMCredentialsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMCredentialsAsyncClient)) def test_iam_credentials_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = IAMCredentialsClient._DEFAULT_UNIVERSE - default_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=default_universe - ) + default_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) mock_universe = "bar.com" - mock_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=mock_universe - ) + mock_endpoint = IAMCredentialsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", # use ClientOptions.api_endpoint as the api endpoint regardless. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch( - "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" - ): - options = client_options.ClientOptions( - client_cert_source=mock_client_cert_source, api_endpoint=api_override - ) - client = client_class( - client_options=options, - credentials=ga_credentials.AnonymousCredentials(), - ) + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == api_override # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", @@ -1113,19 +812,11 @@ def test_iam_credentials_client_client_api_endpoint(client_class): universe_exists = hasattr(options, "universe_domain") if universe_exists: options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) else: - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - assert client.api_endpoint == ( - mock_endpoint if universe_exists else default_endpoint - ) - assert client.universe_domain == ( - mock_universe if universe_exists else default_universe - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. @@ -1133,40 +824,27 @@ def test_iam_credentials_client_client_api_endpoint(client_class): if hasattr(options, "universe_domain"): delattr(options, "universe_domain") with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) assert client.api_endpoint == default_endpoint -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc"), - ( - IAMCredentialsAsyncClient, - transports.IAMCredentialsGrpcAsyncIOTransport, - "grpc_asyncio", - ), - (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest"), - ], -) -def test_iam_credentials_client_client_options_scopes( - client_class, transport_class, transport_name -): +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc"), + (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio"), + (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest"), +]) +def test_iam_credentials_client_client_options_scopes(client_class, transport_class, transport_name): # Check the case scopes are provided. options = client_options.ClientOptions( scopes=["1", "2"], ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=["1", "2"], client_cert_source_for_mtls=None, quota_project_id=None, @@ -1175,40 +853,24 @@ def test_iam_credentials_client_client_options_scopes( api_audience=None, ) - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - IAMCredentialsClient, - transports.IAMCredentialsGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - IAMCredentialsAsyncClient, - transports.IAMCredentialsGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest", None), - ], -) -def test_iam_credentials_client_client_options_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc", grpc_helpers), + (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (IAMCredentialsClient, transports.IAMCredentialsRestTransport, "rest", None), +]) +def test_iam_credentials_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1217,14 +879,11 @@ def test_iam_credentials_client_client_options_credentials_file( api_audience=None, ) - def test_iam_credentials_client_client_options_from_dict(): - with mock.patch( - "google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsGrpcTransport.__init__" - ) as grpc_transport: + with mock.patch('google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsGrpcTransport.__init__') as grpc_transport: grpc_transport.return_value = None client = IAMCredentialsClient( - client_options={"api_endpoint": "squid.clam.whelk"} + client_options={'api_endpoint': 'squid.clam.whelk'} ) grpc_transport.assert_called_once_with( credentials=None, @@ -1239,38 +898,23 @@ def test_iam_credentials_client_client_options_from_dict(): ) -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,grpc_helpers", - [ - ( - IAMCredentialsClient, - transports.IAMCredentialsGrpcTransport, - "grpc", - grpc_helpers, - ), - ( - IAMCredentialsAsyncClient, - transports.IAMCredentialsGrpcAsyncIOTransport, - "grpc_asyncio", - grpc_helpers_async, - ), - ], -) -def test_iam_credentials_client_create_channel_credentials_file( - client_class, transport_class, transport_name, grpc_helpers -): +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport, "grpc", grpc_helpers), + (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_iam_credentials_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): # Check the case credentials file is provided. - options = client_options.ClientOptions(credentials_file="credentials.json") + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) - with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch.object(transport_class, '__init__') as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -1280,13 +924,13 @@ def test_iam_credentials_client_create_channel_credentials_file( ) # test that the credentials from file are saved and used as the credentials. - with ( - mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, - mock.patch.object(google.auth, "default", autospec=True) as adc, - mock.patch.object(grpc_helpers, "create_channel") as create_channel, - ): + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: creds = ga_credentials.AnonymousCredentials() file_creds = ga_credentials.AnonymousCredentials() load_creds.return_value = (file_creds, None) @@ -1297,7 +941,9 @@ def test_iam_credentials_client_create_channel_credentials_file( credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), scopes=None, default_host="iamcredentials.googleapis.com", ssl_credentials=None, @@ -1308,14 +954,11 @@ def test_iam_credentials_client_create_channel_credentials_file( ) -@pytest.mark.parametrize( - "request_type", - [ - common.GenerateAccessTokenRequest, - dict, - ], -) -def test_generate_access_token(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + common.GenerateAccessTokenRequest, + dict, +]) +def test_generate_access_token(request_type, transport: str = 'grpc'): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1327,11 +970,11 @@ def test_generate_access_token(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), "__call__" - ) as call: + type(client.transport.generate_access_token), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = common.GenerateAccessTokenResponse( - access_token="access_token_value", + access_token='access_token_value', ) response = client.generate_access_token(request) @@ -1343,7 +986,7 @@ def test_generate_access_token(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, common.GenerateAccessTokenResponse) - assert response.access_token == "access_token_value" + assert response.access_token == 'access_token_value' def test_generate_access_token_non_empty_request_with_auto_populated_field(): @@ -1351,31 +994,28 @@ def test_generate_access_token_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = common.GenerateAccessTokenRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.generate_access_token), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.generate_access_token(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == common.GenerateAccessTokenRequest( - name="name_value", + name='name_value', ) - def test_generate_access_token_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1390,19 +1030,12 @@ def test_generate_access_token_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.generate_access_token - in client._transport._wrapped_methods - ) + assert client._transport.generate_access_token in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.generate_access_token] = ( - mock_rpc - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_access_token] = mock_rpc request = {} client.generate_access_token(request) @@ -1415,11 +1048,8 @@ def test_generate_access_token_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_generate_access_token_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_generate_access_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1433,17 +1063,12 @@ async def test_generate_access_token_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.generate_access_token - in client._client._transport._wrapped_methods - ) + assert client._client._transport.generate_access_token in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.generate_access_token - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.generate_access_token] = mock_rpc request = {} await client.generate_access_token(request) @@ -1457,11 +1082,8 @@ async def test_generate_access_token_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_generate_access_token_async( - transport: str = "grpc_asyncio", request_type=common.GenerateAccessTokenRequest -): +async def test_generate_access_token_async(transport: str = 'grpc_asyncio', request_type=common.GenerateAccessTokenRequest): client = IAMCredentialsAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1473,14 +1095,12 @@ async def test_generate_access_token_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), "__call__" - ) as call: + type(client.transport.generate_access_token), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.GenerateAccessTokenResponse( - access_token="access_token_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(common.GenerateAccessTokenResponse( + access_token='access_token_value', + )) response = await client.generate_access_token(request) # Establish that the underlying gRPC stub method was called. @@ -1491,14 +1111,13 @@ async def test_generate_access_token_async( # Establish that the response is the type that we expect. assert isinstance(response, common.GenerateAccessTokenResponse) - assert response.access_token == "access_token_value" + assert response.access_token == 'access_token_value' @pytest.mark.asyncio async def test_generate_access_token_async_from_dict(): await test_generate_access_token_async(request_type=dict) - def test_generate_access_token_field_headers(): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1508,12 +1127,12 @@ def test_generate_access_token_field_headers(): # a field header. Set these to a non-empty value. request = common.GenerateAccessTokenRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), "__call__" - ) as call: + type(client.transport.generate_access_token), + '__call__') as call: call.return_value = common.GenerateAccessTokenResponse() client.generate_access_token(request) @@ -1525,9 +1144,9 @@ def test_generate_access_token_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -1540,15 +1159,13 @@ async def test_generate_access_token_field_headers_async(): # a field header. Set these to a non-empty value. request = common.GenerateAccessTokenRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.GenerateAccessTokenResponse() - ) + type(client.transport.generate_access_token), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.GenerateAccessTokenResponse()) await client.generate_access_token(request) # Establish that the underlying gRPC stub method was called. @@ -1559,9 +1176,9 @@ async def test_generate_access_token_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_generate_access_token_flattened(): @@ -1571,16 +1188,16 @@ def test_generate_access_token_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), "__call__" - ) as call: + type(client.transport.generate_access_token), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = common.GenerateAccessTokenResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.generate_access_token( - name="name_value", - delegates=["delegates_value"], - scope=["scope_value"], + name='name_value', + delegates=['delegates_value'], + scope=['scope_value'], lifetime=duration_pb2.Duration(seconds=751), ) @@ -1589,17 +1206,15 @@ def test_generate_access_token_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].delegates - mock_val = ["delegates_value"] + mock_val = ['delegates_value'] assert arg == mock_val arg = args[0].scope - mock_val = ["scope_value"] + mock_val = ['scope_value'] assert arg == mock_val - assert DurationRule().to_proto(args[0].lifetime) == duration_pb2.Duration( - seconds=751 - ) + assert DurationRule().to_proto(args[0].lifetime) == duration_pb2.Duration(seconds=751) def test_generate_access_token_flattened_error(): @@ -1612,13 +1227,12 @@ def test_generate_access_token_flattened_error(): with pytest.raises(ValueError): client.generate_access_token( common.GenerateAccessTokenRequest(), - name="name_value", - delegates=["delegates_value"], - scope=["scope_value"], + name='name_value', + delegates=['delegates_value'], + scope=['scope_value'], lifetime=duration_pb2.Duration(seconds=751), ) - @pytest.mark.asyncio async def test_generate_access_token_flattened_async(): client = IAMCredentialsAsyncClient( @@ -1627,20 +1241,18 @@ async def test_generate_access_token_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), "__call__" - ) as call: + type(client.transport.generate_access_token), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = common.GenerateAccessTokenResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.GenerateAccessTokenResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.GenerateAccessTokenResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.generate_access_token( - name="name_value", - delegates=["delegates_value"], - scope=["scope_value"], + name='name_value', + delegates=['delegates_value'], + scope=['scope_value'], lifetime=duration_pb2.Duration(seconds=751), ) @@ -1649,18 +1261,15 @@ async def test_generate_access_token_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].delegates - mock_val = ["delegates_value"] + mock_val = ['delegates_value'] assert arg == mock_val arg = args[0].scope - mock_val = ["scope_value"] + mock_val = ['scope_value'] assert arg == mock_val - assert DurationRule().to_proto(args[0].lifetime) == duration_pb2.Duration( - seconds=751 - ) - + assert DurationRule().to_proto(args[0].lifetime) == duration_pb2.Duration(seconds=751) @pytest.mark.asyncio async def test_generate_access_token_flattened_error_async(): @@ -1673,21 +1282,18 @@ async def test_generate_access_token_flattened_error_async(): with pytest.raises(ValueError): await client.generate_access_token( common.GenerateAccessTokenRequest(), - name="name_value", - delegates=["delegates_value"], - scope=["scope_value"], + name='name_value', + delegates=['delegates_value'], + scope=['scope_value'], lifetime=duration_pb2.Duration(seconds=751), ) -@pytest.mark.parametrize( - "request_type", - [ - common.GenerateIdTokenRequest, - dict, - ], -) -def test_generate_id_token(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + common.GenerateIdTokenRequest, + dict, +]) +def test_generate_id_token(request_type, transport: str = 'grpc'): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1699,11 +1305,11 @@ def test_generate_id_token(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), "__call__" - ) as call: + type(client.transport.generate_id_token), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = common.GenerateIdTokenResponse( - token="token_value", + token='token_value', ) response = client.generate_id_token(request) @@ -1715,7 +1321,7 @@ def test_generate_id_token(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, common.GenerateIdTokenResponse) - assert response.token == "token_value" + assert response.token == 'token_value' def test_generate_id_token_non_empty_request_with_auto_populated_field(): @@ -1723,33 +1329,30 @@ def test_generate_id_token_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = common.GenerateIdTokenRequest( - name="name_value", - audience="audience_value", + name='name_value', + audience='audience_value', ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + type(client.transport.generate_id_token), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.generate_id_token(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == common.GenerateIdTokenRequest( - name="name_value", - audience="audience_value", + name='name_value', + audience='audience_value', ) - def test_generate_id_token_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1768,12 +1371,8 @@ def test_generate_id_token_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.generate_id_token] = ( - mock_rpc - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_id_token] = mock_rpc request = {} client.generate_id_token(request) @@ -1786,11 +1385,8 @@ def test_generate_id_token_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_generate_id_token_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_generate_id_token_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1804,17 +1400,12 @@ async def test_generate_id_token_async_use_cached_wrapped_rpc( wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.generate_id_token - in client._client._transport._wrapped_methods - ) + assert client._client._transport.generate_id_token in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.generate_id_token - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.generate_id_token] = mock_rpc request = {} await client.generate_id_token(request) @@ -1828,11 +1419,8 @@ async def test_generate_id_token_async_use_cached_wrapped_rpc( assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_generate_id_token_async( - transport: str = "grpc_asyncio", request_type=common.GenerateIdTokenRequest -): +async def test_generate_id_token_async(transport: str = 'grpc_asyncio', request_type=common.GenerateIdTokenRequest): client = IAMCredentialsAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1844,14 +1432,12 @@ async def test_generate_id_token_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), "__call__" - ) as call: + type(client.transport.generate_id_token), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.GenerateIdTokenResponse( - token="token_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(common.GenerateIdTokenResponse( + token='token_value', + )) response = await client.generate_id_token(request) # Establish that the underlying gRPC stub method was called. @@ -1862,14 +1448,13 @@ async def test_generate_id_token_async( # Establish that the response is the type that we expect. assert isinstance(response, common.GenerateIdTokenResponse) - assert response.token == "token_value" + assert response.token == 'token_value' @pytest.mark.asyncio async def test_generate_id_token_async_from_dict(): await test_generate_id_token_async(request_type=dict) - def test_generate_id_token_field_headers(): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1879,12 +1464,12 @@ def test_generate_id_token_field_headers(): # a field header. Set these to a non-empty value. request = common.GenerateIdTokenRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), "__call__" - ) as call: + type(client.transport.generate_id_token), + '__call__') as call: call.return_value = common.GenerateIdTokenResponse() client.generate_id_token(request) @@ -1896,9 +1481,9 @@ def test_generate_id_token_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -1911,15 +1496,13 @@ async def test_generate_id_token_field_headers_async(): # a field header. Set these to a non-empty value. request = common.GenerateIdTokenRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.GenerateIdTokenResponse() - ) + type(client.transport.generate_id_token), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.GenerateIdTokenResponse()) await client.generate_id_token(request) # Establish that the underlying gRPC stub method was called. @@ -1930,9 +1513,9 @@ async def test_generate_id_token_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_generate_id_token_flattened(): @@ -1942,16 +1525,16 @@ def test_generate_id_token_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), "__call__" - ) as call: + type(client.transport.generate_id_token), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = common.GenerateIdTokenResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.generate_id_token( - name="name_value", - delegates=["delegates_value"], - audience="audience_value", + name='name_value', + delegates=['delegates_value'], + audience='audience_value', include_email=True, ) @@ -1960,13 +1543,13 @@ def test_generate_id_token_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].delegates - mock_val = ["delegates_value"] + mock_val = ['delegates_value'] assert arg == mock_val arg = args[0].audience - mock_val = "audience_value" + mock_val = 'audience_value' assert arg == mock_val arg = args[0].include_email mock_val = True @@ -1983,13 +1566,12 @@ def test_generate_id_token_flattened_error(): with pytest.raises(ValueError): client.generate_id_token( common.GenerateIdTokenRequest(), - name="name_value", - delegates=["delegates_value"], - audience="audience_value", + name='name_value', + delegates=['delegates_value'], + audience='audience_value', include_email=True, ) - @pytest.mark.asyncio async def test_generate_id_token_flattened_async(): client = IAMCredentialsAsyncClient( @@ -1998,20 +1580,18 @@ async def test_generate_id_token_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), "__call__" - ) as call: + type(client.transport.generate_id_token), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = common.GenerateIdTokenResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.GenerateIdTokenResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.GenerateIdTokenResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.generate_id_token( - name="name_value", - delegates=["delegates_value"], - audience="audience_value", + name='name_value', + delegates=['delegates_value'], + audience='audience_value', include_email=True, ) @@ -2020,19 +1600,18 @@ async def test_generate_id_token_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].delegates - mock_val = ["delegates_value"] + mock_val = ['delegates_value'] assert arg == mock_val arg = args[0].audience - mock_val = "audience_value" + mock_val = 'audience_value' assert arg == mock_val arg = args[0].include_email mock_val = True assert arg == mock_val - @pytest.mark.asyncio async def test_generate_id_token_flattened_error_async(): client = IAMCredentialsAsyncClient( @@ -2044,21 +1623,18 @@ async def test_generate_id_token_flattened_error_async(): with pytest.raises(ValueError): await client.generate_id_token( common.GenerateIdTokenRequest(), - name="name_value", - delegates=["delegates_value"], - audience="audience_value", + name='name_value', + delegates=['delegates_value'], + audience='audience_value', include_email=True, ) -@pytest.mark.parametrize( - "request_type", - [ - common.SignBlobRequest, - dict, - ], -) -def test_sign_blob(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + common.SignBlobRequest, + dict, +]) +def test_sign_blob(request_type, transport: str = 'grpc'): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2069,11 +1645,13 @@ def test_sign_blob(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + with mock.patch.object( + type(client.transport.sign_blob), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = common.SignBlobResponse( - key_id="key_id_value", - signed_blob=b"signed_blob_blob", + key_id='key_id_value', + signed_blob=b'signed_blob_blob', ) response = client.sign_blob(request) @@ -2085,8 +1663,8 @@ def test_sign_blob(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, common.SignBlobResponse) - assert response.key_id == "key_id_value" - assert response.signed_blob == b"signed_blob_blob" + assert response.key_id == 'key_id_value' + assert response.signed_blob == b'signed_blob_blob' def test_sign_blob_non_empty_request_with_auto_populated_field(): @@ -2094,29 +1672,28 @@ def test_sign_blob_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = common.SignBlobRequest( - name="name_value", + name='name_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.sign_blob), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.sign_blob(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == common.SignBlobRequest( - name="name_value", + name='name_value', ) - def test_sign_blob_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2135,9 +1712,7 @@ def test_sign_blob_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.sign_blob] = mock_rpc request = {} client.sign_blob(request) @@ -2151,7 +1726,6 @@ def test_sign_blob_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio async def test_sign_blob_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -2167,17 +1741,12 @@ async def test_sign_blob_async_use_cached_wrapped_rpc(transport: str = "grpc_asy wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.sign_blob - in client._client._transport._wrapped_methods - ) + assert client._client._transport.sign_blob in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.sign_blob - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.sign_blob] = mock_rpc request = {} await client.sign_blob(request) @@ -2191,11 +1760,8 @@ async def test_sign_blob_async_use_cached_wrapped_rpc(transport: str = "grpc_asy assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_sign_blob_async( - transport: str = "grpc_asyncio", request_type=common.SignBlobRequest -): +async def test_sign_blob_async(transport: str = 'grpc_asyncio', request_type=common.SignBlobRequest): client = IAMCredentialsAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2206,14 +1772,14 @@ async def test_sign_blob_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + with mock.patch.object( + type(client.transport.sign_blob), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.SignBlobResponse( - key_id="key_id_value", - signed_blob=b"signed_blob_blob", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(common.SignBlobResponse( + key_id='key_id_value', + signed_blob=b'signed_blob_blob', + )) response = await client.sign_blob(request) # Establish that the underlying gRPC stub method was called. @@ -2224,15 +1790,14 @@ async def test_sign_blob_async( # Establish that the response is the type that we expect. assert isinstance(response, common.SignBlobResponse) - assert response.key_id == "key_id_value" - assert response.signed_blob == b"signed_blob_blob" + assert response.key_id == 'key_id_value' + assert response.signed_blob == b'signed_blob_blob' @pytest.mark.asyncio async def test_sign_blob_async_from_dict(): await test_sign_blob_async(request_type=dict) - def test_sign_blob_field_headers(): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2242,10 +1807,12 @@ def test_sign_blob_field_headers(): # a field header. Set these to a non-empty value. request = common.SignBlobRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + with mock.patch.object( + type(client.transport.sign_blob), + '__call__') as call: call.return_value = common.SignBlobResponse() client.sign_blob(request) @@ -2257,9 +1824,9 @@ def test_sign_blob_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -2272,13 +1839,13 @@ async def test_sign_blob_field_headers_async(): # a field header. Set these to a non-empty value. request = common.SignBlobRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.SignBlobResponse() - ) + with mock.patch.object( + type(client.transport.sign_blob), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SignBlobResponse()) await client.sign_blob(request) # Establish that the underlying gRPC stub method was called. @@ -2289,9 +1856,9 @@ async def test_sign_blob_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_sign_blob_flattened(): @@ -2300,15 +1867,17 @@ def test_sign_blob_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + with mock.patch.object( + type(client.transport.sign_blob), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = common.SignBlobResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.sign_blob( - name="name_value", - delegates=["delegates_value"], - payload=b"payload_blob", + name='name_value', + delegates=['delegates_value'], + payload=b'payload_blob', ) # Establish that the underlying call was made with the expected @@ -2316,13 +1885,13 @@ def test_sign_blob_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].delegates - mock_val = ["delegates_value"] + mock_val = ['delegates_value'] assert arg == mock_val arg = args[0].payload - mock_val = b"payload_blob" + mock_val = b'payload_blob' assert arg == mock_val @@ -2336,12 +1905,11 @@ def test_sign_blob_flattened_error(): with pytest.raises(ValueError): client.sign_blob( common.SignBlobRequest(), - name="name_value", - delegates=["delegates_value"], - payload=b"payload_blob", + name='name_value', + delegates=['delegates_value'], + payload=b'payload_blob', ) - @pytest.mark.asyncio async def test_sign_blob_flattened_async(): client = IAMCredentialsAsyncClient( @@ -2349,19 +1917,19 @@ async def test_sign_blob_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + with mock.patch.object( + type(client.transport.sign_blob), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = common.SignBlobResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.SignBlobResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SignBlobResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.sign_blob( - name="name_value", - delegates=["delegates_value"], - payload=b"payload_blob", + name='name_value', + delegates=['delegates_value'], + payload=b'payload_blob', ) # Establish that the underlying call was made with the expected @@ -2369,16 +1937,15 @@ async def test_sign_blob_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].delegates - mock_val = ["delegates_value"] + mock_val = ['delegates_value'] assert arg == mock_val arg = args[0].payload - mock_val = b"payload_blob" + mock_val = b'payload_blob' assert arg == mock_val - @pytest.mark.asyncio async def test_sign_blob_flattened_error_async(): client = IAMCredentialsAsyncClient( @@ -2390,20 +1957,17 @@ async def test_sign_blob_flattened_error_async(): with pytest.raises(ValueError): await client.sign_blob( common.SignBlobRequest(), - name="name_value", - delegates=["delegates_value"], - payload=b"payload_blob", + name='name_value', + delegates=['delegates_value'], + payload=b'payload_blob', ) -@pytest.mark.parametrize( - "request_type", - [ - common.SignJwtRequest, - dict, - ], -) -def test_sign_jwt(request_type, transport: str = "grpc"): +@pytest.mark.parametrize("request_type", [ + common.SignJwtRequest, + dict, +]) +def test_sign_jwt(request_type, transport: str = 'grpc'): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2414,11 +1978,13 @@ def test_sign_jwt(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + with mock.patch.object( + type(client.transport.sign_jwt), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = common.SignJwtResponse( - key_id="key_id_value", - signed_jwt="signed_jwt_value", + key_id='key_id_value', + signed_jwt='signed_jwt_value', ) response = client.sign_jwt(request) @@ -2430,8 +1996,8 @@ def test_sign_jwt(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, common.SignJwtResponse) - assert response.key_id == "key_id_value" - assert response.signed_jwt == "signed_jwt_value" + assert response.key_id == 'key_id_value' + assert response.signed_jwt == 'signed_jwt_value' def test_sign_jwt_non_empty_request_with_auto_populated_field(): @@ -2439,31 +2005,30 @@ def test_sign_jwt_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport='grpc', ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = common.SignJwtRequest( - name="name_value", - payload="payload_value", + name='name_value', + payload='payload_value', ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + with mock.patch.object( + type(client.transport.sign_jwt), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client.sign_jwt(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == common.SignJwtRequest( - name="name_value", - payload="payload_value", + name='name_value', + payload='payload_value', ) - def test_sign_jwt_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2482,9 +2047,7 @@ def test_sign_jwt_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.sign_jwt] = mock_rpc request = {} client.sign_jwt(request) @@ -2498,7 +2061,6 @@ def test_sign_jwt_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio async def test_sign_jwt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -2514,17 +2076,12 @@ async def test_sign_jwt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._client._transport.sign_jwt - in client._client._transport._wrapped_methods - ) + assert client._client._transport.sign_jwt in client._client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[ - client._client._transport.sign_jwt - ] = mock_rpc + client._client._transport._wrapped_methods[client._client._transport.sign_jwt] = mock_rpc request = {} await client.sign_jwt(request) @@ -2538,11 +2095,8 @@ async def test_sign_jwt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 - @pytest.mark.asyncio -async def test_sign_jwt_async( - transport: str = "grpc_asyncio", request_type=common.SignJwtRequest -): +async def test_sign_jwt_async(transport: str = 'grpc_asyncio', request_type=common.SignJwtRequest): client = IAMCredentialsAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2553,14 +2107,14 @@ async def test_sign_jwt_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + with mock.patch.object( + type(client.transport.sign_jwt), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.SignJwtResponse( - key_id="key_id_value", - signed_jwt="signed_jwt_value", - ) - ) + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(common.SignJwtResponse( + key_id='key_id_value', + signed_jwt='signed_jwt_value', + )) response = await client.sign_jwt(request) # Establish that the underlying gRPC stub method was called. @@ -2571,15 +2125,14 @@ async def test_sign_jwt_async( # Establish that the response is the type that we expect. assert isinstance(response, common.SignJwtResponse) - assert response.key_id == "key_id_value" - assert response.signed_jwt == "signed_jwt_value" + assert response.key_id == 'key_id_value' + assert response.signed_jwt == 'signed_jwt_value' @pytest.mark.asyncio async def test_sign_jwt_async_from_dict(): await test_sign_jwt_async(request_type=dict) - def test_sign_jwt_field_headers(): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2589,10 +2142,12 @@ def test_sign_jwt_field_headers(): # a field header. Set these to a non-empty value. request = common.SignJwtRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + with mock.patch.object( + type(client.transport.sign_jwt), + '__call__') as call: call.return_value = common.SignJwtResponse() client.sign_jwt(request) @@ -2604,9 +2159,9 @@ def test_sign_jwt_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] @pytest.mark.asyncio @@ -2619,13 +2174,13 @@ async def test_sign_jwt_field_headers_async(): # a field header. Set these to a non-empty value. request = common.SignJwtRequest() - request.name = "name_value" + request.name = 'name_value' # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.SignJwtResponse() - ) + with mock.patch.object( + type(client.transport.sign_jwt), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SignJwtResponse()) await client.sign_jwt(request) # Establish that the underlying gRPC stub method was called. @@ -2636,9 +2191,9 @@ async def test_sign_jwt_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] def test_sign_jwt_flattened(): @@ -2647,15 +2202,17 @@ def test_sign_jwt_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + with mock.patch.object( + type(client.transport.sign_jwt), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = common.SignJwtResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.sign_jwt( - name="name_value", - delegates=["delegates_value"], - payload="payload_value", + name='name_value', + delegates=['delegates_value'], + payload='payload_value', ) # Establish that the underlying call was made with the expected @@ -2663,13 +2220,13 @@ def test_sign_jwt_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].delegates - mock_val = ["delegates_value"] + mock_val = ['delegates_value'] assert arg == mock_val arg = args[0].payload - mock_val = "payload_value" + mock_val = 'payload_value' assert arg == mock_val @@ -2683,12 +2240,11 @@ def test_sign_jwt_flattened_error(): with pytest.raises(ValueError): client.sign_jwt( common.SignJwtRequest(), - name="name_value", - delegates=["delegates_value"], - payload="payload_value", + name='name_value', + delegates=['delegates_value'], + payload='payload_value', ) - @pytest.mark.asyncio async def test_sign_jwt_flattened_async(): client = IAMCredentialsAsyncClient( @@ -2696,19 +2252,19 @@ async def test_sign_jwt_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + with mock.patch.object( + type(client.transport.sign_jwt), + '__call__') as call: # Designate an appropriate return value for the call. call.return_value = common.SignJwtResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.SignJwtResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SignJwtResponse()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.sign_jwt( - name="name_value", - delegates=["delegates_value"], - payload="payload_value", + name='name_value', + delegates=['delegates_value'], + payload='payload_value', ) # Establish that the underlying call was made with the expected @@ -2716,16 +2272,15 @@ async def test_sign_jwt_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = "name_value" + mock_val = 'name_value' assert arg == mock_val arg = args[0].delegates - mock_val = ["delegates_value"] + mock_val = ['delegates_value'] assert arg == mock_val arg = args[0].payload - mock_val = "payload_value" + mock_val = 'payload_value' assert arg == mock_val - @pytest.mark.asyncio async def test_sign_jwt_flattened_error_async(): client = IAMCredentialsAsyncClient( @@ -2737,9 +2292,9 @@ async def test_sign_jwt_flattened_error_async(): with pytest.raises(ValueError): await client.sign_jwt( common.SignJwtRequest(), - name="name_value", - delegates=["delegates_value"], - payload="payload_value", + name='name_value', + delegates=['delegates_value'], + payload='payload_value', ) @@ -2757,19 +2312,12 @@ def test_generate_access_token_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.generate_access_token - in client._transport._wrapped_methods - ) + assert client._transport.generate_access_token in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.generate_access_token] = ( - mock_rpc - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_access_token] = mock_rpc request = {} client.generate_access_token(request) @@ -2784,9 +2332,7 @@ def test_generate_access_token_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_generate_access_token_rest_required_fields( - request_type=common.GenerateAccessTokenRequest, -): +def test_generate_access_token_rest_required_fields(request_type=common.GenerateAccessTokenRequest): transport_class = transports.IAMCredentialsRestTransport request_init = {} @@ -2794,56 +2340,53 @@ def test_generate_access_token_rest_required_fields( request_init["scope"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).generate_access_token._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - jsonified_request["scope"] = "scope_value" + jsonified_request["name"] = 'name_value' + jsonified_request["scope"] = 'scope_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).generate_access_token._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' assert "scope" in jsonified_request - assert jsonified_request["scope"] == "scope_value" + assert jsonified_request["scope"] == 'scope_value' client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = common.GenerateAccessTokenResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + with mock.patch.object(Session, 'request') as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -2853,32 +2396,23 @@ def test_generate_access_token_rest_required_fields( return_value = common.GenerateAccessTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.generate_access_token(request) - expected_params = [] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_generate_access_token_rest_unset_required_fields(): - transport = transports.IAMCredentialsRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.IAMCredentialsRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.generate_access_token._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "scope", - ) - ) - ) + assert set(unset_fields) == (set(()) & set(("name", "scope", ))) def test_generate_access_token_rest_flattened(): @@ -2888,18 +2422,18 @@ def test_generate_access_token_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = common.GenerateAccessTokenResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/serviceAccounts/sample2"} + sample_request = {'name': 'projects/sample1/serviceAccounts/sample2'} # get truthy value for each flattened field mock_args = dict( - name="name_value", - delegates=["delegates_value"], - scope=["scope_value"], + name='name_value', + delegates=['delegates_value'], + scope=['scope_value'], lifetime=duration_pb2.Duration(seconds=751), ) mock_args.update(sample_request) @@ -2910,7 +2444,7 @@ def test_generate_access_token_rest_flattened(): # Convert return value to protobuf type return_value = common.GenerateAccessTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2920,14 +2454,10 @@ def test_generate_access_token_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/serviceAccounts/*}:generateAccessToken" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{name=projects/*/serviceAccounts/*}:generateAccessToken" % client.transport._host, args[1]) -def test_generate_access_token_rest_flattened_error(transport: str = "rest"): +def test_generate_access_token_rest_flattened_error(transport: str = 'rest'): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2938,9 +2468,9 @@ def test_generate_access_token_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.generate_access_token( common.GenerateAccessTokenRequest(), - name="name_value", - delegates=["delegates_value"], - scope=["scope_value"], + name='name_value', + delegates=['delegates_value'], + scope=['scope_value'], lifetime=duration_pb2.Duration(seconds=751), ) @@ -2963,12 +2493,8 @@ def test_generate_id_token_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.generate_id_token] = ( - mock_rpc - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_id_token] = mock_rpc request = {} client.generate_id_token(request) @@ -2983,9 +2509,7 @@ def test_generate_id_token_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_generate_id_token_rest_required_fields( - request_type=common.GenerateIdTokenRequest, -): +def test_generate_id_token_rest_required_fields(request_type=common.GenerateIdTokenRequest): transport_class = transports.IAMCredentialsRestTransport request_init = {} @@ -2993,56 +2517,53 @@ def test_generate_id_token_rest_required_fields( request_init["audience"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).generate_id_token._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_id_token._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - jsonified_request["audience"] = "audience_value" + jsonified_request["name"] = 'name_value' + jsonified_request["audience"] = 'audience_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).generate_id_token._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_id_token._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' assert "audience" in jsonified_request - assert jsonified_request["audience"] == "audience_value" + assert jsonified_request["audience"] == 'audience_value' client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = common.GenerateIdTokenResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + with mock.patch.object(Session, 'request') as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -3052,32 +2573,23 @@ def test_generate_id_token_rest_required_fields( return_value = common.GenerateIdTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.generate_id_token(request) - expected_params = [] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_generate_id_token_rest_unset_required_fields(): - transport = transports.IAMCredentialsRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.IAMCredentialsRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.generate_id_token._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "audience", - ) - ) - ) + assert set(unset_fields) == (set(()) & set(("name", "audience", ))) def test_generate_id_token_rest_flattened(): @@ -3087,18 +2599,18 @@ def test_generate_id_token_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = common.GenerateIdTokenResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/serviceAccounts/sample2"} + sample_request = {'name': 'projects/sample1/serviceAccounts/sample2'} # get truthy value for each flattened field mock_args = dict( - name="name_value", - delegates=["delegates_value"], - audience="audience_value", + name='name_value', + delegates=['delegates_value'], + audience='audience_value', include_email=True, ) mock_args.update(sample_request) @@ -3109,7 +2621,7 @@ def test_generate_id_token_rest_flattened(): # Convert return value to protobuf type return_value = common.GenerateIdTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3119,14 +2631,10 @@ def test_generate_id_token_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/serviceAccounts/*}:generateIdToken" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{name=projects/*/serviceAccounts/*}:generateIdToken" % client.transport._host, args[1]) -def test_generate_id_token_rest_flattened_error(transport: str = "rest"): +def test_generate_id_token_rest_flattened_error(transport: str = 'rest'): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3137,9 +2645,9 @@ def test_generate_id_token_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.generate_id_token( common.GenerateIdTokenRequest(), - name="name_value", - delegates=["delegates_value"], - audience="audience_value", + name='name_value', + delegates=['delegates_value'], + audience='audience_value', include_email=True, ) @@ -3162,9 +2670,7 @@ def test_sign_blob_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.sign_blob] = mock_rpc request = {} @@ -3185,59 +2691,56 @@ def test_sign_blob_rest_required_fields(request_type=common.SignBlobRequest): request_init = {} request_init["name"] = "" - request_init["payload"] = b"" + request_init["payload"] = b'' request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).sign_blob._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).sign_blob._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - jsonified_request["payload"] = b"payload_blob" + jsonified_request["name"] = 'name_value' + jsonified_request["payload"] = b'payload_blob' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).sign_blob._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).sign_blob._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' assert "payload" in jsonified_request - assert jsonified_request["payload"] == b"payload_blob" + assert jsonified_request["payload"] == b'payload_blob' client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = common.SignBlobResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + with mock.patch.object(Session, 'request') as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -3247,32 +2750,23 @@ def test_sign_blob_rest_required_fields(request_type=common.SignBlobRequest): return_value = common.SignBlobResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.sign_blob(request) - expected_params = [] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_sign_blob_rest_unset_required_fields(): - transport = transports.IAMCredentialsRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.IAMCredentialsRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.sign_blob._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "payload", - ) - ) - ) + assert set(unset_fields) == (set(()) & set(("name", "payload", ))) def test_sign_blob_rest_flattened(): @@ -3282,18 +2776,18 @@ def test_sign_blob_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = common.SignBlobResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/serviceAccounts/sample2"} + sample_request = {'name': 'projects/sample1/serviceAccounts/sample2'} # get truthy value for each flattened field mock_args = dict( - name="name_value", - delegates=["delegates_value"], - payload=b"payload_blob", + name='name_value', + delegates=['delegates_value'], + payload=b'payload_blob', ) mock_args.update(sample_request) @@ -3303,7 +2797,7 @@ def test_sign_blob_rest_flattened(): # Convert return value to protobuf type return_value = common.SignBlobResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3313,14 +2807,10 @@ def test_sign_blob_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/serviceAccounts/*}:signBlob" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{name=projects/*/serviceAccounts/*}:signBlob" % client.transport._host, args[1]) -def test_sign_blob_rest_flattened_error(transport: str = "rest"): +def test_sign_blob_rest_flattened_error(transport: str = 'rest'): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3331,9 +2821,9 @@ def test_sign_blob_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.sign_blob( common.SignBlobRequest(), - name="name_value", - delegates=["delegates_value"], - payload=b"payload_blob", + name='name_value', + delegates=['delegates_value'], + payload=b'payload_blob', ) @@ -3355,9 +2845,7 @@ def test_sign_jwt_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. client._transport._wrapped_methods[client._transport.sign_jwt] = mock_rpc request = {} @@ -3381,56 +2869,53 @@ def test_sign_jwt_rest_required_fields(request_type=common.SignJwtRequest): request_init["payload"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) # verify fields with default values are dropped - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).sign_jwt._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).sign_jwt._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - jsonified_request["payload"] = "payload_value" + jsonified_request["name"] = 'name_value' + jsonified_request["payload"] = 'payload_value' - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).sign_jwt._get_unset_required_fields(jsonified_request) + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).sign_jwt._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert jsonified_request["name"] == 'name_value' assert "payload" in jsonified_request - assert jsonified_request["payload"] == "payload_value" + assert jsonified_request["payload"] == 'payload_value' client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport='rest', ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = common.SignJwtResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + with mock.patch.object(Session, 'request') as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: + with mock.patch.object(path_template, 'transcode') as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, } - transcode_result["body"] = pb_request + transcode_result['body'] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -3440,32 +2925,23 @@ def test_sign_jwt_rest_required_fields(request_type=common.SignJwtRequest): return_value = common.SignJwtResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.sign_jwt(request) - expected_params = [] - actual_params = req.call_args.kwargs["params"] + expected_params = [ + ] + actual_params = req.call_args.kwargs['params'] assert expected_params == actual_params def test_sign_jwt_rest_unset_required_fields(): - transport = transports.IAMCredentialsRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + transport = transports.IAMCredentialsRestTransport(credentials=ga_credentials.AnonymousCredentials) unset_fields = transport.sign_jwt._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "name", - "payload", - ) - ) - ) + assert set(unset_fields) == (set(()) & set(("name", "payload", ))) def test_sign_jwt_rest_flattened(): @@ -3475,18 +2951,18 @@ def test_sign_jwt_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = common.SignJwtResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/serviceAccounts/sample2"} + sample_request = {'name': 'projects/sample1/serviceAccounts/sample2'} # get truthy value for each flattened field mock_args = dict( - name="name_value", - delegates=["delegates_value"], - payload="payload_value", + name='name_value', + delegates=['delegates_value'], + payload='payload_value', ) mock_args.update(sample_request) @@ -3496,7 +2972,7 @@ def test_sign_jwt_rest_flattened(): # Convert return value to protobuf type return_value = common.SignJwtResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") + response_value._content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3506,14 +2982,10 @@ def test_sign_jwt_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/serviceAccounts/*}:signJwt" - % client.transport._host, - args[1], - ) + assert path_template.validate("%s/v1/{name=projects/*/serviceAccounts/*}:signJwt" % client.transport._host, args[1]) -def test_sign_jwt_rest_flattened_error(transport: str = "rest"): +def test_sign_jwt_rest_flattened_error(transport: str = 'rest'): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3524,9 +2996,9 @@ def test_sign_jwt_rest_flattened_error(transport: str = "rest"): with pytest.raises(ValueError): client.sign_jwt( common.SignJwtRequest(), - name="name_value", - delegates=["delegates_value"], - payload="payload_value", + name='name_value', + delegates=['delegates_value'], + payload='payload_value', ) @@ -3568,7 +3040,8 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = IAMCredentialsClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + client_options=options, + credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. @@ -3590,7 +3063,6 @@ def test_transport_instance(): client = IAMCredentialsClient(transport=transport) assert client.transport is transport - def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.IAMCredentialsGrpcTransport( @@ -3605,23 +3077,18 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel - -@pytest.mark.parametrize( - "transport_class", - [ - transports.IAMCredentialsGrpcTransport, - transports.IAMCredentialsGrpcAsyncIOTransport, - transports.IAMCredentialsRestTransport, - ], -) +@pytest.mark.parametrize("transport_class", [ + transports.IAMCredentialsGrpcTransport, + transports.IAMCredentialsGrpcAsyncIOTransport, + transports.IAMCredentialsRestTransport, +]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() - def test_transport_kind_grpc(): transport = IAMCredentialsClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -3631,7 +3098,8 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) assert client is not None @@ -3646,8 +3114,8 @@ def test_generate_access_token_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), "__call__" - ) as call: + type(client.transport.generate_access_token), + '__call__') as call: call.return_value = common.GenerateAccessTokenResponse() client.generate_access_token(request=None) @@ -3669,8 +3137,8 @@ def test_generate_id_token_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), "__call__" - ) as call: + type(client.transport.generate_id_token), + '__call__') as call: call.return_value = common.GenerateIdTokenResponse() client.generate_id_token(request=None) @@ -3691,7 +3159,9 @@ def test_sign_blob_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + with mock.patch.object( + type(client.transport.sign_blob), + '__call__') as call: call.return_value = common.SignBlobResponse() client.sign_blob(request=None) @@ -3712,7 +3182,9 @@ def test_sign_jwt_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + with mock.patch.object( + type(client.transport.sign_jwt), + '__call__') as call: call.return_value = common.SignJwtResponse() client.sign_jwt(request=None) @@ -3733,7 +3205,8 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = IAMCredentialsAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) assert client is not None @@ -3749,14 +3222,12 @@ async def test_generate_access_token_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), "__call__" - ) as call: + type(client.transport.generate_access_token), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.GenerateAccessTokenResponse( - access_token="access_token_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.GenerateAccessTokenResponse( + access_token='access_token_value', + )) await client.generate_access_token(request=None) # Establish that the underlying stub method was called. @@ -3778,14 +3249,12 @@ async def test_generate_id_token_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), "__call__" - ) as call: + type(client.transport.generate_id_token), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.GenerateIdTokenResponse( - token="token_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.GenerateIdTokenResponse( + token='token_value', + )) await client.generate_id_token(request=None) # Establish that the underlying stub method was called. @@ -3806,14 +3275,14 @@ async def test_sign_blob_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + with mock.patch.object( + type(client.transport.sign_blob), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.SignBlobResponse( - key_id="key_id_value", - signed_blob=b"signed_blob_blob", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SignBlobResponse( + key_id='key_id_value', + signed_blob=b'signed_blob_blob', + )) await client.sign_blob(request=None) # Establish that the underlying stub method was called. @@ -3834,14 +3303,14 @@ async def test_sign_jwt_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + with mock.patch.object( + type(client.transport.sign_jwt), + '__call__') as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - common.SignJwtResponse( - key_id="key_id_value", - signed_jwt="signed_jwt_value", - ) - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SignJwtResponse( + key_id='key_id_value', + signed_jwt='signed_jwt_value', + )) await client.sign_jwt(request=None) # Establish that the underlying stub method was called. @@ -3859,24 +3328,20 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_generate_access_token_rest_bad_request( - request_type=common.GenerateAccessTokenRequest, -): +def test_generate_access_token_rest_bad_request(request_type=common.GenerateAccessTokenRequest): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/serviceAccounts/sample2"} + request_init = {'name': 'projects/sample1/serviceAccounts/sample2'} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -3885,27 +3350,25 @@ def test_generate_access_token_rest_bad_request( client.generate_access_token(request) -@pytest.mark.parametrize( - "request_type", - [ - common.GenerateAccessTokenRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + common.GenerateAccessTokenRequest, + dict, +]) def test_generate_access_token_rest_call_success(request_type): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/serviceAccounts/sample2"} + request_init = {'name': 'projects/sample1/serviceAccounts/sample2'} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = common.GenerateAccessTokenResponse( - access_token="access_token_value", + access_token='access_token_value', ) # Wrap the value into a proper Response obj @@ -3915,46 +3378,33 @@ def test_generate_access_token_rest_call_success(request_type): # Convert return value to protobuf type return_value = common.GenerateAccessTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.generate_access_token(request) # Establish that the response is the type that we expect. assert isinstance(response, common.GenerateAccessTokenResponse) - assert response.access_token == "access_token_value" + assert response.access_token == 'access_token_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_generate_access_token_rest_interceptors(null_interceptor): transport = transports.IAMCredentialsRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.IAMCredentialsRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.IAMCredentialsRestInterceptor(), + ) client = IAMCredentialsClient(transport=transport) - with ( - mock.patch.object(type(client.transport._session), "request") as req, - mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object( - transports.IAMCredentialsRestInterceptor, "post_generate_access_token" - ) as post, - mock.patch.object( - transports.IAMCredentialsRestInterceptor, - "post_generate_access_token_with_metadata", - ) as post_with_metadata, - mock.patch.object( - transports.IAMCredentialsRestInterceptor, "pre_generate_access_token" - ) as pre, - ): + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.IAMCredentialsRestInterceptor, "post_generate_access_token") as post, \ + mock.patch.object(transports.IAMCredentialsRestInterceptor, "post_generate_access_token_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.IAMCredentialsRestInterceptor, "pre_generate_access_token") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = common.GenerateAccessTokenRequest.pb( - common.GenerateAccessTokenRequest() - ) + pb_message = common.GenerateAccessTokenRequest.pb(common.GenerateAccessTokenRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3965,13 +3415,11 @@ def test_generate_access_token_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = common.GenerateAccessTokenResponse.to_json( - common.GenerateAccessTokenResponse() - ) + return_value = common.GenerateAccessTokenResponse.to_json(common.GenerateAccessTokenResponse()) req.return_value.content = return_value request = common.GenerateAccessTokenRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -3979,13 +3427,7 @@ def test_generate_access_token_rest_interceptors(null_interceptor): post.return_value = common.GenerateAccessTokenResponse() post_with_metadata.return_value = common.GenerateAccessTokenResponse(), metadata - client.generate_access_token( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.generate_access_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() @@ -3994,20 +3436,18 @@ def test_generate_access_token_rest_interceptors(null_interceptor): def test_generate_id_token_rest_bad_request(request_type=common.GenerateIdTokenRequest): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/serviceAccounts/sample2"} + request_init = {'name': 'projects/sample1/serviceAccounts/sample2'} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -4016,27 +3456,25 @@ def test_generate_id_token_rest_bad_request(request_type=common.GenerateIdTokenR client.generate_id_token(request) -@pytest.mark.parametrize( - "request_type", - [ - common.GenerateIdTokenRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + common.GenerateIdTokenRequest, + dict, +]) def test_generate_id_token_rest_call_success(request_type): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/serviceAccounts/sample2"} + request_init = {'name': 'projects/sample1/serviceAccounts/sample2'} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = common.GenerateIdTokenResponse( - token="token_value", + token='token_value', ) # Wrap the value into a proper Response obj @@ -4046,40 +3484,29 @@ def test_generate_id_token_rest_call_success(request_type): # Convert return value to protobuf type return_value = common.GenerateIdTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.generate_id_token(request) # Establish that the response is the type that we expect. assert isinstance(response, common.GenerateIdTokenResponse) - assert response.token == "token_value" + assert response.token == 'token_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_generate_id_token_rest_interceptors(null_interceptor): transport = transports.IAMCredentialsRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.IAMCredentialsRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.IAMCredentialsRestInterceptor(), + ) client = IAMCredentialsClient(transport=transport) - with ( - mock.patch.object(type(client.transport._session), "request") as req, - mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object( - transports.IAMCredentialsRestInterceptor, "post_generate_id_token" - ) as post, - mock.patch.object( - transports.IAMCredentialsRestInterceptor, - "post_generate_id_token_with_metadata", - ) as post_with_metadata, - mock.patch.object( - transports.IAMCredentialsRestInterceptor, "pre_generate_id_token" - ) as pre, - ): + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.IAMCredentialsRestInterceptor, "post_generate_id_token") as post, \ + mock.patch.object(transports.IAMCredentialsRestInterceptor, "post_generate_id_token_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.IAMCredentialsRestInterceptor, "pre_generate_id_token") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -4094,13 +3521,11 @@ def test_generate_id_token_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = common.GenerateIdTokenResponse.to_json( - common.GenerateIdTokenResponse() - ) + return_value = common.GenerateIdTokenResponse.to_json(common.GenerateIdTokenResponse()) req.return_value.content = return_value request = common.GenerateIdTokenRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -4108,13 +3533,7 @@ def test_generate_id_token_rest_interceptors(null_interceptor): post.return_value = common.GenerateIdTokenResponse() post_with_metadata.return_value = common.GenerateIdTokenResponse(), metadata - client.generate_id_token( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.generate_id_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() @@ -4123,20 +3542,18 @@ def test_generate_id_token_rest_interceptors(null_interceptor): def test_sign_blob_rest_bad_request(request_type=common.SignBlobRequest): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/serviceAccounts/sample2"} + request_init = {'name': 'projects/sample1/serviceAccounts/sample2'} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -4145,28 +3562,26 @@ def test_sign_blob_rest_bad_request(request_type=common.SignBlobRequest): client.sign_blob(request) -@pytest.mark.parametrize( - "request_type", - [ - common.SignBlobRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + common.SignBlobRequest, + dict, +]) def test_sign_blob_rest_call_success(request_type): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/serviceAccounts/sample2"} + request_init = {'name': 'projects/sample1/serviceAccounts/sample2'} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = common.SignBlobResponse( - key_id="key_id_value", - signed_blob=b"signed_blob_blob", + key_id='key_id_value', + signed_blob=b'signed_blob_blob', ) # Wrap the value into a proper Response obj @@ -4176,40 +3591,30 @@ def test_sign_blob_rest_call_success(request_type): # Convert return value to protobuf type return_value = common.SignBlobResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.sign_blob(request) # Establish that the response is the type that we expect. assert isinstance(response, common.SignBlobResponse) - assert response.key_id == "key_id_value" - assert response.signed_blob == b"signed_blob_blob" + assert response.key_id == 'key_id_value' + assert response.signed_blob == b'signed_blob_blob' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_sign_blob_rest_interceptors(null_interceptor): transport = transports.IAMCredentialsRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.IAMCredentialsRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.IAMCredentialsRestInterceptor(), + ) client = IAMCredentialsClient(transport=transport) - with ( - mock.patch.object(type(client.transport._session), "request") as req, - mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object( - transports.IAMCredentialsRestInterceptor, "post_sign_blob" - ) as post, - mock.patch.object( - transports.IAMCredentialsRestInterceptor, "post_sign_blob_with_metadata" - ) as post_with_metadata, - mock.patch.object( - transports.IAMCredentialsRestInterceptor, "pre_sign_blob" - ) as pre, - ): + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.IAMCredentialsRestInterceptor, "post_sign_blob") as post, \ + mock.patch.object(transports.IAMCredentialsRestInterceptor, "post_sign_blob_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.IAMCredentialsRestInterceptor, "pre_sign_blob") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -4228,7 +3633,7 @@ def test_sign_blob_rest_interceptors(null_interceptor): req.return_value.content = return_value request = common.SignBlobRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -4236,13 +3641,7 @@ def test_sign_blob_rest_interceptors(null_interceptor): post.return_value = common.SignBlobResponse() post_with_metadata.return_value = common.SignBlobResponse(), metadata - client.sign_blob( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.sign_blob(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() @@ -4251,20 +3650,18 @@ def test_sign_blob_rest_interceptors(null_interceptor): def test_sign_jwt_rest_bad_request(request_type=common.SignJwtRequest): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/serviceAccounts/sample2"} + request_init = {'name': 'projects/sample1/serviceAccounts/sample2'} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = "" + json_return_value = '' response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -4273,28 +3670,26 @@ def test_sign_jwt_rest_bad_request(request_type=common.SignJwtRequest): client.sign_jwt(request) -@pytest.mark.parametrize( - "request_type", - [ - common.SignJwtRequest, - dict, - ], -) +@pytest.mark.parametrize("request_type", [ + common.SignJwtRequest, + dict, +]) def test_sign_jwt_rest_call_success(request_type): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/serviceAccounts/sample2"} + request_init = {'name': 'projects/sample1/serviceAccounts/sample2'} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(type(client.transport._session), 'request') as req: # Designate an appropriate value for the returned response. return_value = common.SignJwtResponse( - key_id="key_id_value", - signed_jwt="signed_jwt_value", + key_id='key_id_value', + signed_jwt='signed_jwt_value', ) # Wrap the value into a proper Response obj @@ -4304,40 +3699,30 @@ def test_sign_jwt_rest_call_success(request_type): # Convert return value to protobuf type return_value = common.SignJwtResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + response_value.content = json_return_value.encode('UTF-8') req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.sign_jwt(request) # Establish that the response is the type that we expect. assert isinstance(response, common.SignJwtResponse) - assert response.key_id == "key_id_value" - assert response.signed_jwt == "signed_jwt_value" + assert response.key_id == 'key_id_value' + assert response.signed_jwt == 'signed_jwt_value' @pytest.mark.parametrize("null_interceptor", [True, False]) def test_sign_jwt_rest_interceptors(null_interceptor): transport = transports.IAMCredentialsRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.IAMCredentialsRestInterceptor(), - ) + interceptor=None if null_interceptor else transports.IAMCredentialsRestInterceptor(), + ) client = IAMCredentialsClient(transport=transport) - with ( - mock.patch.object(type(client.transport._session), "request") as req, - mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object( - transports.IAMCredentialsRestInterceptor, "post_sign_jwt" - ) as post, - mock.patch.object( - transports.IAMCredentialsRestInterceptor, "post_sign_jwt_with_metadata" - ) as post_with_metadata, - mock.patch.object( - transports.IAMCredentialsRestInterceptor, "pre_sign_jwt" - ) as pre, - ): + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.IAMCredentialsRestInterceptor, "post_sign_jwt") as post, \ + mock.patch.object(transports.IAMCredentialsRestInterceptor, "post_sign_jwt_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.IAMCredentialsRestInterceptor, "pre_sign_jwt") as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -4356,7 +3741,7 @@ def test_sign_jwt_rest_interceptors(null_interceptor): req.return_value.content = return_value request = common.SignJwtRequest() - metadata = [ + metadata =[ ("key", "val"), ("cephalopod", "squid"), ] @@ -4364,22 +3749,16 @@ def test_sign_jwt_rest_interceptors(null_interceptor): post.return_value = common.SignJwtResponse() post_with_metadata.return_value = common.SignJwtResponse(), metadata - client.sign_jwt( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + client.sign_jwt(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() - def test_initialize_client_w_rest(): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) assert client is not None @@ -4394,8 +3773,8 @@ def test_generate_access_token_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.generate_access_token), "__call__" - ) as call: + type(client.transport.generate_access_token), + '__call__') as call: client.generate_access_token(request=None) # Establish that the underlying stub method was called. @@ -4416,8 +3795,8 @@ def test_generate_id_token_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.generate_id_token), "__call__" - ) as call: + type(client.transport.generate_id_token), + '__call__') as call: client.generate_id_token(request=None) # Establish that the underlying stub method was called. @@ -4437,7 +3816,9 @@ def test_sign_blob_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + with mock.patch.object( + type(client.transport.sign_blob), + '__call__') as call: client.sign_blob(request=None) # Establish that the underlying stub method was called. @@ -4457,7 +3838,9 @@ def test_sign_jwt_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + with mock.patch.object( + type(client.transport.sign_jwt), + '__call__') as call: client.sign_jwt(request=None) # Establish that the underlying stub method was called. @@ -4478,21 +3861,18 @@ def test_transport_grpc_default(): transports.IAMCredentialsGrpcTransport, ) - def test_iam_credentials_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.IAMCredentialsTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + credentials_file="credentials.json" ) def test_iam_credentials_base_transport(): # Instantiate the base transport. - with mock.patch( - "google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsTransport.__init__" - ) as Transport: + with mock.patch('google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsTransport.__init__') as Transport: Transport.return_value = None transport = transports.IAMCredentialsTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -4501,10 +3881,10 @@ def test_iam_credentials_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - "generate_access_token", - "generate_id_token", - "sign_blob", - "sign_jwt", + 'generate_access_token', + 'generate_id_token', + 'sign_blob', + 'sign_jwt', ) for method in methods: with pytest.raises(NotImplementedError): @@ -4515,7 +3895,7 @@ def test_iam_credentials_base_transport(): # Catch all for all remaining methods and properties remainder = [ - "kind", + 'kind', ] for r in remainder: with pytest.raises(NotImplementedError): @@ -4524,36 +3904,25 @@ def test_iam_credentials_base_transport(): def test_iam_credentials_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file - with ( - mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, - mock.patch( - "google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsTransport._prep_wrapped_messages" - ) as Transport, - ): + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsTransport._prep_wrapped_messages') as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.IAMCredentialsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with( - "credentials.json", + load_creds.assert_called_once_with("credentials.json", scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), quota_project_id="octopus", ) def test_iam_credentials_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with ( - mock.patch.object(google.auth, "default", autospec=True) as adc, - mock.patch( - "google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsTransport._prep_wrapped_messages" - ) as Transport, - ): + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.iam.credentials_v1.services.iam_credentials.transports.IAMCredentialsTransport._prep_wrapped_messages') as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.IAMCredentialsTransport() @@ -4562,12 +3931,14 @@ def test_iam_credentials_base_transport_with_adc(): def test_iam_credentials_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: + with mock.patch.object(google.auth, 'default', autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) IAMCredentialsClient() adc.assert_called_once_with( scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), quota_project_id=None, ) @@ -4582,12 +3953,12 @@ def test_iam_credentials_auth_adc(): def test_iam_credentials_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: + with mock.patch.object(google.auth, 'default', autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class(quota_project_id="octopus", scopes=["1", "2"]) adc.assert_called_once_with( scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), quota_project_id="octopus", ) @@ -4601,46 +3972,48 @@ def test_iam_credentials_transport_auth_adc(transport_class): ], ) def test_iam_credentials_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: + with mock.patch.object(google.auth, 'default', autospec=True) as adc: gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) adc.return_value = (gdch_mock, None) transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) @pytest.mark.parametrize( "transport_class,grpc_helpers", [ (transports.IAMCredentialsGrpcTransport, grpc_helpers), - (transports.IAMCredentialsGrpcAsyncIOTransport, grpc_helpers_async), + (transports.IAMCredentialsGrpcAsyncIOTransport, grpc_helpers_async) ], ) def test_iam_credentials_transport_create_channel(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. - with ( - mock.patch.object(google.auth, "default", autospec=True) as adc, - mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel, - ): + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: creds = ga_credentials.AnonymousCredentials() adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) create_channel.assert_called_with( "iamcredentials.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), scopes=["1", "2"], default_host="iamcredentials.googleapis.com", ssl_credentials=None, @@ -4651,14 +4024,10 @@ def test_iam_credentials_transport_create_channel(transport_class, grpc_helpers) ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.IAMCredentialsGrpcTransport, - transports.IAMCredentialsGrpcAsyncIOTransport, - ], -) -def test_iam_credentials_grpc_transport_client_cert_source_for_mtls(transport_class): +@pytest.mark.parametrize("transport_class", [transports.IAMCredentialsGrpcTransport, transports.IAMCredentialsGrpcAsyncIOTransport]) +def test_iam_credentials_grpc_transport_client_cert_source_for_mtls( + transport_class +): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -4667,7 +4036,7 @@ def test_iam_credentials_grpc_transport_client_cert_source_for_mtls(transport_cl transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, + ssl_channel_credentials=mock_ssl_channel_creds ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", @@ -4688,77 +4057,61 @@ def test_iam_credentials_grpc_transport_client_cert_source_for_mtls(transport_cl with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, + client_cert_source_for_mtls=client_cert_source_callback ) expected_cert, expected_key = client_cert_source_callback() mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key + certificate_chain=expected_cert, + private_key=expected_key ) - def test_iam_credentials_http_transport_client_cert_source_for_mtls(): cred = ga_credentials.AnonymousCredentials() - with mock.patch( - "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" - ) as mock_configure_mtls_channel: - transports.IAMCredentialsRestTransport( - credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.IAMCredentialsRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_iam_credentials_host_no_port(transport_name): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="iamcredentials.googleapis.com" - ), - transport=transport_name, + client_options=client_options.ClientOptions(api_endpoint='iamcredentials.googleapis.com'), + transport=transport_name, ) assert client.transport._host == ( - "iamcredentials.googleapis.com:443" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://iamcredentials.googleapis.com" + 'iamcredentials.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://iamcredentials.googleapis.com' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) def test_iam_credentials_host_with_port(transport_name): client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="iamcredentials.googleapis.com:8000" - ), + client_options=client_options.ClientOptions(api_endpoint='iamcredentials.googleapis.com:8000'), transport=transport_name, ) assert client.transport._host == ( - "iamcredentials.googleapis.com:8000" - if transport_name in ["grpc", "grpc_asyncio"] - else "https://iamcredentials.googleapis.com:8000" + 'iamcredentials.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://iamcredentials.googleapis.com:8000' ) - -@pytest.mark.parametrize( - "transport_name", - [ - "rest", - ], -) +@pytest.mark.parametrize("transport_name", [ + "rest", +]) def test_iam_credentials_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -4782,10 +4135,8 @@ def test_iam_credentials_client_transport_session_collision(transport_name): session1 = client1.transport.sign_jwt._session session2 = client2.transport.sign_jwt._session assert session1 != session2 - - def test_iam_credentials_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.IAMCredentialsGrpcTransport( @@ -4798,7 +4149,7 @@ def test_iam_credentials_grpc_transport_channel(): def test_iam_credentials_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.IAMCredentialsGrpcAsyncIOTransport( @@ -4813,22 +4164,12 @@ def test_iam_credentials_grpc_asyncio_transport_channel(): # Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are # removed from grpc/grpc_asyncio transport constructor. @pytest.mark.filterwarnings("ignore::FutureWarning") -@pytest.mark.parametrize( - "transport_class", - [ - transports.IAMCredentialsGrpcTransport, - transports.IAMCredentialsGrpcAsyncIOTransport, - ], -) +@pytest.mark.parametrize("transport_class", [transports.IAMCredentialsGrpcTransport, transports.IAMCredentialsGrpcAsyncIOTransport]) def test_iam_credentials_transport_channel_mtls_with_client_cert_source( - transport_class, + transport_class ): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: mock_ssl_cred = mock.Mock() grpc_ssl_channel_cred.return_value = mock_ssl_cred @@ -4837,7 +4178,7 @@ def test_iam_credentials_transport_channel_mtls_with_client_cert_source( cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: + with mock.patch.object(google.auth, 'default') as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -4867,23 +4208,17 @@ def test_iam_credentials_transport_channel_mtls_with_client_cert_source( # Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are # removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.IAMCredentialsGrpcTransport, - transports.IAMCredentialsGrpcAsyncIOTransport, - ], -) -def test_iam_credentials_transport_channel_mtls_with_adc(transport_class): +@pytest.mark.parametrize("transport_class", [transports.IAMCredentialsGrpcTransport, transports.IAMCredentialsGrpcAsyncIOTransport]) +def test_iam_credentials_transport_channel_mtls_with_adc( + transport_class +): mock_ssl_cred = mock.Mock() with mock.patch.multiple( "google.auth.transport.grpc.SslCredentials", __init__=mock.Mock(return_value=None), ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel mock_cred = mock.Mock() @@ -4914,10 +4249,7 @@ def test_iam_credentials_transport_channel_mtls_with_adc(transport_class): def test_service_account_path(): project = "squid" service_account = "clam" - expected = "projects/{project}/serviceAccounts/{service_account}".format( - project=project, - service_account=service_account, - ) + expected = "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) actual = IAMCredentialsClient.service_account_path(project, service_account) assert expected == actual @@ -4933,12 +4265,9 @@ def test_parse_service_account_path(): actual = IAMCredentialsClient.parse_service_account_path(path) assert expected == actual - def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) actual = IAMCredentialsClient.common_billing_account_path(billing_account) assert expected == actual @@ -4953,12 +4282,9 @@ def test_parse_common_billing_account_path(): actual = IAMCredentialsClient.parse_common_billing_account_path(path) assert expected == actual - def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format( - folder=folder, - ) + expected = "folders/{folder}".format(folder=folder, ) actual = IAMCredentialsClient.common_folder_path(folder) assert expected == actual @@ -4973,12 +4299,9 @@ def test_parse_common_folder_path(): actual = IAMCredentialsClient.parse_common_folder_path(path) assert expected == actual - def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format( - organization=organization, - ) + expected = "organizations/{organization}".format(organization=organization, ) actual = IAMCredentialsClient.common_organization_path(organization) assert expected == actual @@ -4993,12 +4316,9 @@ def test_parse_common_organization_path(): actual = IAMCredentialsClient.parse_common_organization_path(path) assert expected == actual - def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format( - project=project, - ) + expected = "projects/{project}".format(project=project, ) actual = IAMCredentialsClient.common_project_path(project) assert expected == actual @@ -5013,14 +4333,10 @@ def test_parse_common_project_path(): actual = IAMCredentialsClient.parse_common_project_path(path) assert expected == actual - def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) actual = IAMCredentialsClient.common_location_path(project, location) assert expected == actual @@ -5040,18 +4356,14 @@ def test_parse_common_location_path(): def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object( - transports.IAMCredentialsTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.IAMCredentialsTransport, '_prep_wrapped_messages') as prep: client = IAMCredentialsClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object( - transports.IAMCredentialsTransport, "_prep_wrapped_messages" - ) as prep: + with mock.patch.object(transports.IAMCredentialsTransport, '_prep_wrapped_messages') as prep: transport_class = IAMCredentialsClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -5062,11 +4374,10 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -5075,11 +4386,10 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = IAMCredentialsAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" ) - with mock.patch.object( - type(getattr(client.transport, "_grpc_channel")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: async with client: close.assert_not_called() close.assert_called_once() @@ -5087,11 +4397,10 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" ) - with mock.patch.object( - type(getattr(client.transport, "_session")), "close" - ) as close: + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: with client: close.assert_not_called() close.assert_called_once() @@ -5099,12 +4408,13 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - "rest", - "grpc", + 'rest', + 'grpc', ] for transport in transports: client = IAMCredentialsClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport + credentials=ga_credentials.AnonymousCredentials(), + transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -5113,14 +4423,10 @@ def test_client_ctx(): pass close.assert_called() - -@pytest.mark.parametrize( - "client_class,transport_class", - [ - (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport), - (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport), - ], -) +@pytest.mark.parametrize("client_class,transport_class", [ + (IAMCredentialsClient, transports.IAMCredentialsGrpcTransport), + (IAMCredentialsAsyncClient, transports.IAMCredentialsGrpcAsyncIOTransport), +]) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -5135,9 +4441,7 @@ def test_api_key_credentials(client_class, transport_class): patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format( - UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE - ), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, From c19fc42b8f7e8699831b2726d1909b96894a404c Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 09:58:07 -0400 Subject: [PATCH 50/52] chore(gapic-generator): update goldens for asset API --- .../integration/goldens/asset/google/cloud/asset_v1/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/__init__.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/__init__.py index 3bc2be21fdc5..40ec41664d3c 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/__init__.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/__init__.py @@ -112,7 +112,6 @@ # functions above. We do equivalent checks manually. try: import warnings - import sys _py_version_str = sys.version.split()[0] _package_label = "google.cloud.asset_v1" From 101047cd841154de65e306204f07d536a43ec7c6 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 10:20:24 -0400 Subject: [PATCH 51/52] fix(gapic-generator): skip Python 3.9 unit tests temporarily --- packages/gapic-generator/noxfile.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/gapic-generator/noxfile.py b/packages/gapic-generator/noxfile.py index e170072d4696..24bd8bd4c8d3 100644 --- a/packages/gapic-generator/noxfile.py +++ b/packages/gapic-generator/noxfile.py @@ -44,6 +44,7 @@ RUFF_EXCLUDES = "*golden*,*pb2.py,*pb2.pyi" ALL_PYTHON = ( + "3.9", "3.10", "3.11", "3.12", @@ -57,6 +58,8 @@ @nox.session(python=ALL_PYTHON) def unit(session): """Run the unit test suite.""" + if session.python == "3.9": + session.skip("Skipping Python 3.9 unit tests temporarily.") session.install( # TODO(https://github.com/googleapis/gapic-generator-python/issues/2478): # Temporarily pin coverage to 7.11.0 From bbf78ce127b99ab8434aa73a419589a9ee3486ad Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 4 May 2026 10:49:48 -0400 Subject: [PATCH 52/52] fix(ci): allow Python 3.9 unit tests to run (and be skipped) --- ci/run_single_test.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ci/run_single_test.sh b/ci/run_single_test.sh index 376660a58b2a..fecd7a00bd5a 100755 --- a/ci/run_single_test.sh +++ b/ci/run_single_test.sh @@ -70,6 +70,10 @@ case ${TEST_TYPE} in ;; unit) case ${PY_VERSION} in + "3.9") + nox -s unit-3.9 + retval=$? + ;; "3.10") nox -s unit-3.10 retval=$?