From 70be9ff6053e50665598e28bcd6d4eeb03d6b5af Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Tue, 1 Dec 2026 09:02:58 -0500 Subject: [PATCH 1/5] fix(gapic-generator): forward client_options to Extended Operations sub-clients --- .../%name_%version/%sub/_compat.py.j2 | 111 ++++ .../%sub/services/%service/client.py.j2 | 45 ++ .../services/%service/transports/base.py.j2 | 77 +++ .../%name_%version/%sub/test_%service.py.j2 | 533 ++++++++++++++++++ .../%name_%version/%sub/test_compat.py.j2 | 330 +++++++++++ 5 files changed, 1096 insertions(+) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 index 0716f72decba..e9401fee7a7c 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 @@ -4,6 +4,7 @@ """A compatibility module for older versions of google-api-core.""" {% set has_auto_populated_fields = api.all_method_settings.values()|map(attribute="auto_populated_fields", default=[])|select|list %} +{% set has_extended_operations = api.services.values()|selectattr("any_extended_operations_methods")|list|length > 0 %} {# TODO(https://github.com/googleapis/google-cloud-python/issues/17813): Clean up this file/functions when the minimum supported version of google-api-core has the functions in `_compat.py.j2`. #} @@ -13,6 +14,10 @@ falling back to the local implementation if not present. #} {# TODO(https://github.com/googleapis/google-cloud-python/issues/17883): Backfill compatibility functions being removed from the client layer. #} +{% if has_extended_operations %} +from collections.abc import Mapping +import copy +{% endif %} import inspect import os import json @@ -24,8 +29,13 @@ import google.protobuf.message from typing import Any, Dict, List, Optional, Sequence, Tuple {% if has_auto_populated_fields %} from typing import TYPE_CHECKING, Union +{% elif has_extended_operations %} +from typing import Union {% endif %} +{% if has_extended_operations %} +from google.api_core import client_options as client_options_lib +{% endif %} from google.api_core import gapic_v1 from google.api_core import path_template from google.api_core.universe import EmptyUniverseError @@ -378,6 +388,107 @@ except ImportError: # pragma: NO COVER raise EmptyUniverseError() return resolved +{% if has_extended_operations %} +try: + # mypy flags [attr-defined] when type-checking generated libraries against + # google-api-core <= 2.44.0 before inherit_universe_in_client_options ships. + from google.api_core.universe import ( # type: ignore[attr-defined] + inherit_universe_in_client_options, + ) +except ImportError: # pragma: NO COVER + {# The fallback implementation for `inherit_universe_in_client_options` can be removed once the minimum version of `google-api-core` exceeds 2.44.0 in `setup.py.j2`. #} + # TODO(universe-domain): Replace with + # google.api_core.universe.inherit_universe_in_client_options once minimum + # allowed google-api-core version exceeds 2.44.0. + def inherit_universe_in_client_options( + parent_universe: str, + client_options: Union[ + client_options_lib.ClientOptions, Mapping[str, Any], None + ] = None, + *, + parent_api_endpoint: Optional[str] = None, + clear_credentials: bool = False, + ) -> Optional[client_options_lib.ClientOptions]: + """Inherit ``parent_universe`` onto child ``client_options`` when unset. + + Args: + parent_universe (str): Resolved universe domain of the parent client. + client_options (Union[google.api_core.client_options.ClientOptions, Mapping[str, Any], None]): + Optional child ``ClientOptions`` instance or mapping. If ``None``, + a new ``ClientOptions`` is created only when propagation is required. + parent_api_endpoint (Optional[str]): Optional parent ``api_endpoint`` + override inherited when both ``api_endpoint`` and ``universe_domain`` + are unset on ``client_options``. If ``None``, no endpoint is inherited. + clear_credentials (bool): Whether to clear ``credentials_file`` and + ``api_key`` on the returned copy to avoid duplicate-credential errors. + + Returns: + Optional[google.api_core.client_options.ClientOptions]: Updated + ``ClientOptions`` instance (never mutating caller inputs), or ``None`` + when ``client_options`` is ``None`` and default resolution already + matches the parent. + + Raises: + TypeError: If ``client_options`` is not a ``ClientOptions`` instance, + ``Mapping``, or ``None``. + """ + env_universe = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + should_propagate = parent_universe != DEFAULT_UNIVERSE or ( + env_universe is not None and env_universe.strip() != parent_universe + ) + has_parent_endpoint = bool(parent_api_endpoint) + if client_options is None: + if should_propagate or has_parent_endpoint: + return client_options_lib.ClientOptions( + api_endpoint=parent_api_endpoint if has_parent_endpoint else None, + universe_domain=parent_universe if should_propagate else None, + ) + return None + if isinstance(client_options, Mapping): + opts = client_options_lib.from_dict(client_options) + opts_universe = getattr(opts, "universe_domain", None) + needs_endpoint = ( + has_parent_endpoint + and not opts.api_endpoint + and opts_universe is None + ) + if opts_universe is None and should_propagate: + opts.universe_domain = parent_universe + if needs_endpoint: + opts.api_endpoint = parent_api_endpoint + if clear_credentials: + opts.credentials_file = None + opts.api_key = None + return opts + if isinstance(client_options, client_options_lib.ClientOptions): + opts_universe = getattr(client_options, "universe_domain", None) + needs_universe = opts_universe is None and should_propagate + needs_endpoint = ( + has_parent_endpoint + and not client_options.api_endpoint + and opts_universe is None + ) + needs_cred_clear = clear_credentials and bool( + client_options.credentials_file + or getattr(client_options, "api_key", None) + ) + if needs_universe or needs_endpoint or needs_cred_clear: + opts = copy.copy(client_options) + if needs_universe: + opts.universe_domain = parent_universe + if needs_endpoint: + opts.api_endpoint = parent_api_endpoint + if needs_cred_clear: + opts.credentials_file = None + opts.api_key = None + return opts + return client_options + raise TypeError( + "client_options must be a ClientOptions instance, Mapping, or None; " + f"got {type(client_options).__name__}" + ) + +{% endif %} {% if has_auto_populated_fields %} try: diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 index 4c0a016dbe75..5ce76a173eb3 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 @@ -35,6 +35,9 @@ from google.api_core.resumable_transfer import ResumableUploadConfig {% endif %} from {{package_path}}._compat import _observability from {{package_path}}._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +{% if service.any_extended_operations_methods %} +from {{package_path}}._compat import inherit_universe_in_client_options +{% endif %} {% if has_auto_populated_fields %} from {{package_path}}._compat import setup_request_id {% endif %} @@ -476,6 +479,30 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): ) self._transport = cast({{ service.name }}Transport, transport) self._api_endpoint = self._transport.host + {% if service.any_extended_operations_methods %} + if ( + client_options is not None + or self._universe_domain != {{ service.client_name }}._DEFAULT_UNIVERSE + ): + existing_ext_ops_options = ( + self._transport._extended_operations_client_options + ) + if not isinstance( + existing_ext_ops_options, client_options_lib.ClientOptions + ): + existing_ext_ops_options = None + self._transport._configure_extended_operations_client_options( + self._universe_domain, + existing_ext_ops_options + if client_options is None + else client_options, + fallback_endpoint=( + existing_ext_ops_options.api_endpoint + if existing_ext_ops_options is not None + else None + ), + ) + {% endif %} self._api_endpoint = (self._api_endpoint or get_api_endpoint( @@ -523,6 +550,15 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): client_info=client_info, **({"client_options": client_options} if client_options is not None else {}), ) + {% if service.any_extended_operations_methods %} + self._transport._extended_operations_client_options = ( # pragma: NO COVER + inherit_universe_in_client_options( + self._universe_domain, + self._client_options, + clear_credentials=True, + ) + ) + {% endif %} return {% endif %} @@ -565,6 +601,15 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): **({"client_options": client_options} if client_options is not None else {}), } self._transport = transport_init(**transport_kwargs) + {% if service.any_extended_operations_methods %} + self._transport._extended_operations_client_options = ( + inherit_universe_in_client_options( + self._universe_domain, + self._client_options, + clear_credentials=True, + ) + ) + {% endif %} if "async" not in str(self._transport): if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 index f74aee2690d4..e62e2ddadb14 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 @@ -3,14 +3,26 @@ {% block content %} import abc +{% if service.any_extended_operations_methods %} +from collections.abc import Mapping +import copy +import os +{% endif %} from typing import {% if service.any_extended_operations_methods %}Any, {% endif %}Awaitable, Callable, Dict, Optional, Sequence, Union {% set package_path = api.naming.module_namespace|join('.') + "." + api.naming.versioned_module_name %} from {{package_path}} import gapic_version as package_version from {{package_path}}._compat import ( ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, + {% if service.any_extended_operations_methods %} + DEFAULT_UNIVERSE as _DEFAULT_UNIVERSE, + {% endif %} SUPPORTS_DEFAULT_HOST as _SUPPORTS_DEFAULT_HOST, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, + {% if service.any_extended_operations_methods %} + get_universe_domain as _get_universe_domain, + inherit_universe_in_client_options as _inherit_universe_in_client_options, + {% endif %} ) _ASYNC_WRAP_METHOD_SUPPORTS_TRACING = _WRAP_METHOD_SUPPORTS_TRACING _WRAP_METHOD_SUPPORTS_KIND = _WRAP_METHOD_SUPPORTS_TRACING @@ -75,6 +87,11 @@ class {{ service.name }}Transport(abc.ABC): ) DEFAULT_HOST: str = '{% if service.host %}{{ service.host }}{% endif %}' + {% if service.any_extended_operations_methods %} + _extended_operations_client_options: Optional[ + client_options_lib.ClientOptions + ] = None + {% endif %} def __init__( self, *, @@ -172,6 +189,32 @@ class {{ service.name }}Transport(abc.ABC): self._default_host: Optional[str] = ( None if self._user_provided_channel else self._host ) + {% if service.any_extended_operations_methods %} + self._extended_operations_client_options = None + env_universe = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + extended_ops_universe = _get_universe_domain( + client_options.get("universe_domain") + if isinstance(client_options, Mapping) + else getattr(client_options, "universe_domain", None), + env_universe if env_universe and env_universe.strip() else None, + default_universe=_DEFAULT_UNIVERSE, + ) + default_hosts = ( + self.DEFAULT_HOST, + f"{self.DEFAULT_HOST}:443", + f"https://{self.DEFAULT_HOST}", + f"https://{self.DEFAULT_HOST}:443", + ) + self._configure_extended_operations_client_options( + extended_ops_universe, + client_options, + fallback_endpoint=( + self._default_host + if self._default_host and self._default_host not in default_hosts + else None + ), + ) + {% endif %} self._wrapped_methods: Dict[Callable, Callable] = {} @property @@ -494,6 +537,39 @@ class {{ service.name }}Transport(abc.ABC): def kind(self) -> str: raise NotImplementedError() + {% if service.any_extended_operations_methods %} + def _configure_extended_operations_client_options( + self, + universe_domain: str, + client_options: Optional[ + Union[client_options_lib.ClientOptions, Mapping[str, Any]] + ] = None, + *, + fallback_endpoint: Optional[str] = None, + ) -> None: + """Configure ``ClientOptions`` forwarded to extended operations sub-clients. + + Preserves ``fallback_endpoint`` (such as a custom transport ``host``) when + ``client_options`` does not set ``api_endpoint``, without mutating caller inputs. + """ + opts = _inherit_universe_in_client_options( + universe_domain, + client_options, + clear_credentials=True, + ) + if fallback_endpoint: + if opts is None: + opts = client_options_lib.ClientOptions( + api_endpoint=fallback_endpoint + ) + elif not opts.api_endpoint: + if opts is client_options: + opts = copy.copy(opts) + opts.api_endpoint = fallback_endpoint + self._extended_operations_client_options = opts + self._extended_operations_services.clear() + {% endif %} + {% for operations_service in api.get_extended_operations_services(service)|sort(attribute="name") %} @property def {{ operations_service.client_name|snake_case|make_private }}(self) -> {{ operations_service.name|snake_case }}.{{ operations_service.client_name }}: @@ -502,6 +578,7 @@ class {{ service.name }}Transport(abc.ABC): ex_op_service = {{ operations_service.name|snake_case }}.{{ operations_service.client_name }}( credentials=self._credentials, transport=self.kind, + client_options=self._extended_operations_client_options, ) self._extended_operations_services["{{ operations_service.name|snake_case }}"] = ex_op_service 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 1a056fc22ec6..f3ac564d125a 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 @@ -2856,5 +2856,538 @@ def test_{{ service.name|snake_case }}_base_transport_wrap_async_method_older_ap assert "client_options" not in kwargs assert "method_name" not in kwargs assert "is_streaming" not in kwargs +{% if service.any_extended_operations_methods %} + + +EXTENDED_OPS_CUSTOM_UNIVERSE = "apis-tpclp.goog" +EXTENDED_OPS_DEFAULT_UNIVERSE = "googleapis.com" +EXTENDED_OPS_CUSTOM_ENDPOINT = "custom.endpoint.test:443" +EXTENDED_OPS_TRANSPORT_HOST = "custom.transport.test:443" +EXTENDED_OPS_EXPLICIT_ENDPOINT = "explicit.options.test:443" + + +@pytest.fixture +def clean_universe_env(monkeypatch): + monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) + monkeypatch.delenv("GOOGLE_API_USE_MTLS_ENDPOINT", raising=False) + return monkeypatch + + +{% for operations_service in api.get_extended_operations_services(service)|sort(attribute="name") %} +{% set op_prop = operations_service.client_name|snake_case|make_private %} +{% set op_default_endpoint = '"' ~ operations_service.host ~ '"' if operations_service.host else 'None' %} +{% set op_tpclp_endpoint = '"' ~ operations_service.host.replace("googleapis.com", "apis-tpclp.goog") ~ '"' if operations_service.host else 'None' %} +@pytest.mark.parametrize( + "transport_name", + [ + {% if 'grpc' in opts.transport %} + pytest.param("grpc", id="grpc"), + {% endif %} + {% if 'rest' in opts.transport %} + pytest.param("rest", id="rest"), + {% endif %} + ], +) +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_client_options_object_propagation( + clean_universe_env, transport_name +): + options = client_options.ClientOptions( + universe_domain=EXTENDED_OPS_CUSTOM_UNIVERSE, + quota_project_id="qp-ext", + api_audience="https://custom.aud/", + scopes=["https://www.googleapis.com/auth/cloud-platform"], + ) + creds = ga_credentials.AnonymousCredentials() + + client = {{ service.client_name }}( + credentials=creds, + transport=transport_name, + client_options=options, + ) + op_client = client.transport.{{ op_prop }} + + assert client.transport.{{ op_prop }} is op_client + assert op_client._transport._credentials is creds + assert op_client.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE + assert op_client.api_endpoint == {{ op_tpclp_endpoint }} + assert op_client._client_options.quota_project_id == "qp-ext" + assert op_client._client_options.api_audience == "https://custom.aud/" + assert op_client._client_options.scopes == [ + "https://www.googleapis.com/auth/cloud-platform" + ] + assert options.api_endpoint is None + + +@pytest.mark.parametrize( + "transport_name", + [ + {% if 'grpc' in opts.transport %} + pytest.param("grpc", id="grpc"), + {% endif %} + {% if 'rest' in opts.transport %} + pytest.param("rest", id="rest"), + {% endif %} + ], +) +@pytest.mark.parametrize( + "raw_options,expected_universe,expected_endpoint", + [ + pytest.param( + {"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + EXTENDED_OPS_CUSTOM_UNIVERSE, + {{ op_tpclp_endpoint }}, + id="dict_universe_domain", + ), + pytest.param( + {"api_endpoint": EXTENDED_OPS_CUSTOM_ENDPOINT}, + EXTENDED_OPS_DEFAULT_UNIVERSE, + EXTENDED_OPS_CUSTOM_ENDPOINT, + id="dict_endpoint_only", + ), + ], +) +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_dict_client_options_propagation( + clean_universe_env, + transport_name, + raw_options, + expected_universe, + expected_endpoint, +): + options_dict = dict(raw_options) + + client = {{ service.client_name }}( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + client_options=options_dict, + ) + op_client = client.transport.{{ op_prop }} + + assert op_client.universe_domain == expected_universe + assert op_client.api_endpoint == expected_endpoint + assert options_dict == raw_options + + +@pytest.mark.parametrize( + "transport_name", + [ + {% if 'grpc' in opts.transport %} + pytest.param("grpc", id="grpc"), + {% endif %} + {% if 'rest' in opts.transport %} + pytest.param("rest", id="rest"), + {% endif %} + ], +) +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_env_universe_bound_at_parent_init( + clean_universe_env, transport_name +): + clean_universe_env.setenv( + "GOOGLE_CLOUD_UNIVERSE_DOMAIN", EXTENDED_OPS_CUSTOM_UNIVERSE + ) + + client_env = {{ service.client_name }}( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + clean_universe_env.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) + op_env = client_env.transport.{{ op_prop }} + + assert op_env.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE + assert op_env.api_endpoint == {{ op_tpclp_endpoint }} + + +@pytest.mark.parametrize( + "transport_name", + [ + {% if 'grpc' in opts.transport %} + pytest.param("grpc", id="grpc"), + {% endif %} + {% if 'rest' in opts.transport %} + pytest.param("rest", id="rest"), + {% endif %} + ], +) +@pytest.mark.parametrize( + "env_value,explicit_universe,expected_endpoint", + [ + pytest.param( + EXTENDED_OPS_CUSTOM_UNIVERSE, + EXTENDED_OPS_DEFAULT_UNIVERSE, + {{ op_default_endpoint }}, + id="explicit_gdu_overrides_tpc_env", + ), + pytest.param( + "", + EXTENDED_OPS_CUSTOM_UNIVERSE, + {{ op_tpclp_endpoint }}, + id="explicit_tpc_overrides_empty_env", + ), + pytest.param( + " ", + EXTENDED_OPS_CUSTOM_UNIVERSE, + {{ op_tpclp_endpoint }}, + id="explicit_tpc_overrides_whitespace_env", + ), + ], +) +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_explicit_universe_overrides_env( + clean_universe_env, + transport_name, + env_value, + explicit_universe, + expected_endpoint, +): + clean_universe_env.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", env_value) + + client = {{ service.client_name }}( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + client_options={"universe_domain": explicit_universe}, + ) + op_client = client.transport.{{ op_prop }} + + assert op_client.universe_domain == explicit_universe + assert op_client.api_endpoint == expected_endpoint + + +@pytest.mark.parametrize( + "transport_name", + [ + {% if 'grpc' in opts.transport %} + pytest.param("grpc", id="grpc"), + {% endif %} + {% if 'rest' in opts.transport %} + pytest.param("rest", id="rest"), + {% endif %} + ], +) +@pytest.mark.parametrize( + "bad_universe", + [ + pytest.param("", id="empty_string"), + pytest.param(" ", id="whitespace_only"), + ], +) +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_empty_universe_raises( + clean_universe_env, transport_name, bad_universe +): + from google.api_core.universe import EmptyUniverseError + + transport_cls = {{ service.client_name }}.get_transport_class(transport_name) + + with pytest.raises( + EmptyUniverseError, + match=r"^Universe Domain cannot be an empty string\.$", + ): + {{ service.client_name }}( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + client_options={"universe_domain": bad_universe}, + ) + with pytest.raises( + EmptyUniverseError, + match=r"^Universe Domain cannot be an empty string\.$", + ): + transport_cls( + credentials=ga_credentials.AnonymousCredentials(), + client_options={"universe_domain": bad_universe}, + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + {% if 'grpc' in opts.transport %} + pytest.param("grpc", id="grpc"), + {% endif %} + {% if 'rest' in opts.transport %} + pytest.param("rest", id="rest"), + {% endif %} + ], +) +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_clears_credentials_file( + clean_universe_env, transport_name +): + file_opts = client_options.ClientOptions( + credentials_file="creds.json", + universe_domain=EXTENDED_OPS_CUSTOM_UNIVERSE, + ) + + with mock.patch.object( + google.auth, + "load_credentials_from_file", + autospec=True, + spec_set=True, + return_value=(ga_credentials.AnonymousCredentials(), None), + ): + client_from_file = {{ service.client_name }}( + transport=transport_name, + client_options=file_opts, + ) + op_from_file = client_from_file.transport.{{ op_prop }} + + assert op_from_file.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE + assert op_from_file._client_options.credentials_file is None + assert file_opts.credentials_file == "creds.json" + + +@pytest.mark.parametrize( + "transport_name", + [ + {% if 'grpc' in opts.transport %} + pytest.param("grpc", id="grpc"), + {% endif %} + {% if 'rest' in opts.transport %} + pytest.param("rest", id="rest"), + {% endif %} + ], +) +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_clears_api_key( + clean_universe_env, transport_name +): + gdu_key_opts = client_options.ClientOptions(api_key="test-gdu-key") + tpc_key_dict = { + "api_key": "test-api-key", + "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, + } + + # Patch google.auth.default for google-auth < 2.16.0 lowest-constraints runs + # where google.auth._default.get_api_key_credentials is not yet available. + with mock.patch.object( + google.auth, + "default", + autospec=True, + spec_set=True, + return_value=(ga_credentials.AnonymousCredentials(), None), + ): + client_gdu_key = {{ service.client_name }}( + transport=transport_name, + client_options=gdu_key_opts, + ) + client_tpc_key = {{ service.client_name }}( + transport=transport_name, + client_options=tpc_key_dict, + ) + op_gdu_key = client_gdu_key.transport.{{ op_prop }} + op_tpc_key = client_tpc_key.transport.{{ op_prop }} + + assert op_gdu_key.universe_domain == EXTENDED_OPS_DEFAULT_UNIVERSE + assert op_gdu_key._client_options.api_key is None + assert gdu_key_opts.api_key == "test-gdu-key" + assert op_tpc_key.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE + assert op_tpc_key._client_options.api_key is None + assert tpc_key_dict["api_key"] == "test-api-key" + + +@pytest.mark.parametrize( + "transport_class", + [ + {% if 'grpc' in opts.transport %} + pytest.param(transports.{{ service.grpc_transport_name }}, id="grpc"), + {% endif %} + {% if 'rest' in opts.transport %} + pytest.param(transports.{{ service.rest_transport_name }}, id="rest"), + {% endif %} + ], +) +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_direct_transport_options( + clean_universe_env, transport_class +): + direct_transport = transport_class( + host=EXTENDED_OPS_TRANSPORT_HOST, + credentials=ga_credentials.AnonymousCredentials(), + client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + ) + empty_opts = client_options.ClientOptions() + transport_with_empty_opts = transport_class( + host=EXTENDED_OPS_TRANSPORT_HOST, + credentials=ga_credentials.AnonymousCredentials(), + client_options=empty_opts, + ) + explicit_opts = client_options.ClientOptions( + api_endpoint=EXTENDED_OPS_EXPLICIT_ENDPOINT + ) + transport_with_explicit_opts = transport_class( + host=EXTENDED_OPS_TRANSPORT_HOST, + credentials=ga_credentials.AnonymousCredentials(), + client_options=explicit_opts, + ) + default_https_transport = transport_class( + host=f"https://{transport_class.DEFAULT_HOST}:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + ) + + op_direct = direct_transport.{{ op_prop }} + op_empty = transport_with_empty_opts.{{ op_prop }} + op_explicit = transport_with_explicit_opts.{{ op_prop }} + op_default_https = default_https_transport.{{ op_prop }} + + assert op_direct.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE + assert op_direct.api_endpoint == direct_transport.host + assert empty_opts.api_endpoint is None + assert op_empty.api_endpoint == transport_with_empty_opts.host + assert op_explicit.api_endpoint == EXTENDED_OPS_EXPLICIT_ENDPOINT + assert op_default_https.api_endpoint == {{ op_tpclp_endpoint }} + {% if 'grpc' in opts.transport %} + if transport_class is transports.{{ service.grpc_transport_name }}: + user_channel_transport = transport_class( + host="ignored.channel.test:443", + channel=mock.MagicMock(spec=grpc.Channel), + client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + ) + assert ( + user_channel_transport.{{ op_prop }}.api_endpoint + == {{ op_tpclp_endpoint }} + ) + {% endif %} + + +@pytest.mark.parametrize( + "transport_class", + [ + {% if 'grpc' in opts.transport %} + pytest.param(transports.{{ service.grpc_transport_name }}, id="grpc"), + {% endif %} + {% if 'rest' in opts.transport %} + pytest.param(transports.{{ service.rest_transport_name }}, id="rest"), + {% endif %} + ], +) +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_prebuilt_transport_reconfiguration( + clean_universe_env, transport_class +): + prebuilt_transport = transport_class( + host=EXTENDED_OPS_TRANSPORT_HOST, + credentials=ga_credentials.AnonymousCredentials(), + ) + stale_op = prebuilt_transport.{{ op_prop }} + assert stale_op.universe_domain == EXTENDED_OPS_DEFAULT_UNIVERSE + + client_with_override = {{ service.client_name }}( + transport=prebuilt_transport, + client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + ) + op_prebuilt = client_with_override.transport.{{ op_prop }} + + assert op_prebuilt is not stale_op + assert op_prebuilt.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE + assert op_prebuilt.api_endpoint == prebuilt_transport.host + + +@pytest.mark.parametrize( + "transport_class", + [ + {% if 'grpc' in opts.transport %} + pytest.param(transports.{{ service.grpc_transport_name }}, id="grpc"), + {% endif %} + {% if 'rest' in opts.transport %} + pytest.param(transports.{{ service.rest_transport_name }}, id="rest"), + {% endif %} + ], +) +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_prebuilt_transport_preserves_options( + clean_universe_env, transport_class +): + configured_transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_options={ + "universe_domain": EXTENDED_OPS_DEFAULT_UNIVERSE, + "quota_project_id": "qp-transport", + }, + ) + unconfigured_transport = transport_class( + host=EXTENDED_OPS_TRANSPORT_HOST, + credentials=ga_credentials.AnonymousCredentials(), + ) + gdu_transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_options={ + "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, + "quota_project_id": "qp-gdu", + }, + ) + + client_gdu_preserving = {{ service.client_name }}(transport=gdu_transport) + clean_universe_env.setenv( + "GOOGLE_CLOUD_UNIVERSE_DOMAIN", EXTENDED_OPS_CUSTOM_UNIVERSE + ) + client_env_preserving = {{ service.client_name }}( + transport=configured_transport + ) + client_env_inheriting = {{ service.client_name }}( + transport=unconfigured_transport + ) + clean_universe_env.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) + + assert ( + client_gdu_preserving.transport.{{ op_prop }}.universe_domain + == EXTENDED_OPS_CUSTOM_UNIVERSE + ) + assert ( + client_gdu_preserving.transport.{{ op_prop }}._client_options.quota_project_id + == "qp-gdu" + ) + assert ( + client_env_preserving.transport.{{ op_prop }}.universe_domain + == EXTENDED_OPS_DEFAULT_UNIVERSE + ) + assert ( + client_env_preserving.transport.{{ op_prop }}._client_options.quota_project_id + == "qp-transport" + ) + assert ( + client_env_inheriting.transport.{{ op_prop }}.universe_domain + == EXTENDED_OPS_CUSTOM_UNIVERSE + ) + assert ( + client_env_inheriting.transport.{{ op_prop }}.api_endpoint + == unconfigured_transport.host + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + {% if 'grpc' in opts.transport %} + pytest.param(transports.{{ service.grpc_transport_name }}, id="grpc"), + {% endif %} + {% if 'rest' in opts.transport %} + pytest.param(transports.{{ service.rest_transport_name }}, id="rest"), + {% endif %} + ], +) +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_autospec_mock_and_callable_transport( + clean_universe_env, transport_class +): + autospec_transport = mock.create_autospec( + transport_class, instance=True, spec_set=True + ) + autospec_transport.host = EXTENDED_OPS_TRANSPORT_HOST + callable_transport = mock.create_autospec( + transport_class, instance=True, spec_set=True + ) + + {{ service.client_name }}( + transport=autospec_transport, + client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + ) + client_with_callable = {{ service.client_name }}( + credentials=ga_credentials.AnonymousCredentials(), + transport=lambda **kwargs: callable_transport, + client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + ) + + autospec_transport._configure_extended_operations_client_options.assert_called_once_with( + EXTENDED_OPS_CUSTOM_UNIVERSE, + {"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + fallback_endpoint=None, + ) + assert ( + client_with_callable.transport._extended_operations_client_options.universe_domain + == EXTENDED_OPS_CUSTOM_UNIVERSE + ) +{% endfor %} +{% endif %} {% endblock %} diff --git a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 index dca023a9bcd7..249fcdb11115 100644 --- a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 +++ b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 @@ -3,6 +3,7 @@ {% block content %} {% set has_auto_populated_fields = api.all_method_settings.values()|map(attribute="auto_populated_fields", default=[])|select|list %} +{% set has_extended_operations = api.services.values()|selectattr("any_extended_operations_methods")|list|length > 0 %} """Tests for the compatibility module for older versions of google-api-core.""" {# TODO(https://github.com/googleapis/google-cloud-python/issues/17813): Clean up this file/tests when the minimum supported version of @@ -37,6 +38,11 @@ from {{package_path}}._compat import ( {% if has_auto_populated_fields %} from {{package_path}}._compat import setup_request_id {% endif %} +{% if has_extended_operations %} +import copy +from google.api_core import client_options as client_options_lib +from {{package_path}}._compat import inherit_universe_in_client_options +{% endif %} from google.auth.exceptions import MutualTLSChannelError from google.api_core.universe import EmptyUniverseError @@ -609,5 +615,329 @@ def test_apply_async_channel_interceptors_compat(): dummy_channel = mock.Mock() result = apply_async_channel_interceptors(dummy_channel, None) assert result is dummy_channel +{% if has_extended_operations %} + + +COMPAT_DEFAULT_UNIVERSE = "googleapis.com" +COMPAT_CUSTOM_UNIVERSE = "apis-tpclp.goog" +COMPAT_CHILD_UNIVERSE = "child.goog" +COMPAT_PARENT_ENDPOINT = "custom.endpoint:443" +COMPAT_CHILD_ENDPOINT = "child.endpoint:443" +COMPAT_API_KEY = "secret" +COMPAT_CREDENTIALS_FILE = "creds.json" + + +@pytest.fixture +def fallback_inherit_universe(monkeypatch): + import importlib + import google.api_core.universe + from {{package_path}} import _compat + + monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) + monkeypatch.delattr( + google.api_core.universe, + "inherit_universe_in_client_options", + raising=False, + ) + reloaded = importlib.reload(_compat) + try: + yield reloaded.inherit_universe_in_client_options + finally: + monkeypatch.undo() + importlib.reload(_compat) + + +def test_inherit_universe_in_client_options_compat_reexport(monkeypatch): + import importlib + import google.api_core.universe + from {{package_path}} import _compat + + assert callable(inherit_universe_in_client_options) + sentinel = mock.MagicMock() + monkeypatch.setattr( + google.api_core.universe, + "inherit_universe_in_client_options", + sentinel, + raising=False, + ) + reloaded = importlib.reload(_compat) + try: + assert reloaded.inherit_universe_in_client_options is sentinel + finally: + monkeypatch.undo() + importlib.reload(_compat) + + +@pytest.mark.parametrize( + ( + "parent_universe", + "client_options", + "parent_api_endpoint", + "clear_credentials", + "expected_universe", + "expected_endpoint", + "expected_api_key", + "expected_credentials_file", + "expected_quota_project", + ), + [ + pytest.param( + COMPAT_DEFAULT_UNIVERSE, + None, + COMPAT_PARENT_ENDPOINT, + False, + None, + COMPAT_PARENT_ENDPOINT, + None, + None, + None, + id="none_gdu_with_parent_endpoint_only", + ), + pytest.param( + COMPAT_CUSTOM_UNIVERSE, + None, + "", + False, + COMPAT_CUSTOM_UNIVERSE, + None, + None, + None, + None, + id="none_custom_universe_with_empty_parent_endpoint", + ), + pytest.param( + COMPAT_CUSTOM_UNIVERSE, + None, + COMPAT_PARENT_ENDPOINT, + False, + COMPAT_CUSTOM_UNIVERSE, + COMPAT_PARENT_ENDPOINT, + None, + None, + None, + id="none_inherits_universe_and_endpoint", + ), + pytest.param( + COMPAT_CUSTOM_UNIVERSE, + { + "quota_project_id": "qp-1", + "api_key": COMPAT_API_KEY, + }, + COMPAT_PARENT_ENDPOINT, + True, + COMPAT_CUSTOM_UNIVERSE, + COMPAT_PARENT_ENDPOINT, + None, + None, + "qp-1", + id="mapping_inherits_and_clears_api_key", + ), + pytest.param( + COMPAT_CUSTOM_UNIVERSE, + { + "quota_project_id": "qp-1", + "credentials_file": COMPAT_CREDENTIALS_FILE, + }, + COMPAT_PARENT_ENDPOINT, + True, + COMPAT_CUSTOM_UNIVERSE, + COMPAT_PARENT_ENDPOINT, + None, + None, + "qp-1", + id="mapping_inherits_and_clears_credentials_file", + ), + pytest.param( + COMPAT_CUSTOM_UNIVERSE, + {"api_endpoint": COMPAT_CHILD_ENDPOINT, "api_key": COMPAT_API_KEY}, + COMPAT_PARENT_ENDPOINT, + False, + COMPAT_CUSTOM_UNIVERSE, + COMPAT_CHILD_ENDPOINT, + COMPAT_API_KEY, + None, + None, + id="mapping_child_endpoint_preserved_without_cred_clear", + ), + pytest.param( + COMPAT_DEFAULT_UNIVERSE, + {"universe_domain": COMPAT_CHILD_UNIVERSE, "api_key": COMPAT_API_KEY}, + COMPAT_PARENT_ENDPOINT, + False, + COMPAT_CHILD_UNIVERSE, + None, + COMPAT_API_KEY, + None, + None, + id="mapping_child_universe_blocks_parent_endpoint", + ), + pytest.param( + COMPAT_CUSTOM_UNIVERSE, + client_options_lib.ClientOptions( + api_endpoint=COMPAT_CHILD_ENDPOINT, + api_key=COMPAT_API_KEY, + ), + COMPAT_PARENT_ENDPOINT, + False, + COMPAT_CUSTOM_UNIVERSE, + COMPAT_CHILD_ENDPOINT, + COMPAT_API_KEY, + None, + None, + id="client_options_preserves_child_endpoint_and_credentials", + ), + pytest.param( + COMPAT_CUSTOM_UNIVERSE, + client_options_lib.ClientOptions(api_key=COMPAT_API_KEY), + COMPAT_PARENT_ENDPOINT, + True, + COMPAT_CUSTOM_UNIVERSE, + COMPAT_PARENT_ENDPOINT, + None, + None, + None, + id="client_options_inherits_and_clears_api_key", + ), + pytest.param( + COMPAT_CUSTOM_UNIVERSE, + client_options_lib.ClientOptions( + credentials_file=COMPAT_CREDENTIALS_FILE + ), + COMPAT_PARENT_ENDPOINT, + True, + COMPAT_CUSTOM_UNIVERSE, + COMPAT_PARENT_ENDPOINT, + None, + None, + None, + id="client_options_inherits_and_clears_credentials_file", + ), + pytest.param( + COMPAT_CUSTOM_UNIVERSE, + client_options_lib.ClientOptions( + universe_domain=COMPAT_CHILD_UNIVERSE, + api_key=COMPAT_API_KEY, + ), + COMPAT_PARENT_ENDPOINT, + True, + COMPAT_CHILD_UNIVERSE, + None, + None, + None, + None, + id="client_options_child_universe_blocks_parent_endpoint", + ), + ], +) +def test_inherit_universe_in_client_options_compat_propagates_options( + fallback_inherit_universe, + parent_universe, + client_options, + parent_api_endpoint, + clear_credentials, + expected_universe, + expected_endpoint, + expected_api_key, + expected_credentials_file, + expected_quota_project, +): + options = copy.deepcopy(client_options) + + inherited = fallback_inherit_universe( + parent_universe, + options, + parent_api_endpoint=parent_api_endpoint, + clear_credentials=clear_credentials, + ) + + assert inherited is not None + assert inherited.universe_domain == expected_universe + assert inherited.api_endpoint == expected_endpoint + assert inherited.api_key == expected_api_key + assert inherited.credentials_file == expected_credentials_file + assert inherited.quota_project_id == expected_quota_project + + +@pytest.mark.parametrize( + "parent_endpoint", + [ + pytest.param(None, id="none_parent_endpoint"), + pytest.param("", id="empty_parent_endpoint"), + ], +) +def test_inherit_universe_in_client_options_compat_gdu_none_returns_none( + fallback_inherit_universe, parent_endpoint +): + inherited = fallback_inherit_universe( + COMPAT_DEFAULT_UNIVERSE, None, parent_api_endpoint=parent_endpoint + ) + + assert inherited is None + + +def test_inherit_universe_in_client_options_compat_unchanged_returns_same_instance( + fallback_inherit_universe, +): + unchanged_opts = client_options_lib.ClientOptions(quota_project_id="qp-1") + + inherited = fallback_inherit_universe( + COMPAT_DEFAULT_UNIVERSE, unchanged_opts + ) + + assert inherited is unchanged_opts + + +def test_inherit_universe_in_client_options_compat_preserves_caller_inputs( + fallback_inherit_universe, +): + raw_dict = { + "quota_project_id": "qp-1", + "api_key": COMPAT_API_KEY, + } + parent_opts = client_options_lib.ClientOptions( + credentials_file=COMPAT_CREDENTIALS_FILE, + ) + + inherited_from_dict = fallback_inherit_universe( + COMPAT_CUSTOM_UNIVERSE, raw_dict, clear_credentials=True + ) + inherited_from_opts = fallback_inherit_universe( + COMPAT_CUSTOM_UNIVERSE, parent_opts, clear_credentials=True + ) + + assert raw_dict == { + "quota_project_id": "qp-1", + "api_key": COMPAT_API_KEY, + } + assert inherited_from_dict.api_key is None + assert inherited_from_opts is not parent_opts + assert parent_opts.credentials_file == COMPAT_CREDENTIALS_FILE + assert inherited_from_opts.credentials_file is None + + +def test_inherit_universe_in_client_options_compat_env_override_and_whitespace( + fallback_inherit_universe, monkeypatch +): + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", " googleapis.com ") + assert fallback_inherit_universe(COMPAT_DEFAULT_UNIVERSE, None) is None + + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", COMPAT_CUSTOM_UNIVERSE) + inherited_env_override = fallback_inherit_universe( + COMPAT_DEFAULT_UNIVERSE, None + ) + assert inherited_env_override is not None + assert inherited_env_override.universe_domain == COMPAT_DEFAULT_UNIVERSE + assert inherited_env_override.api_endpoint is None + + +def test_inherit_universe_in_client_options_compat_invalid_type_raises( + fallback_inherit_universe, +): + with pytest.raises( + TypeError, + match=r"ClientOptions instance, Mapping, or None; got str", + ): + fallback_inherit_universe(COMPAT_DEFAULT_UNIVERSE, "invalid") # type: ignore[arg-type] +{% endif %} {% endblock %} From 244fdf2fc7f4c807db069aab08b94d5125531b35 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Tue, 1 Dec 2026 10:16:55 -0500 Subject: [PATCH 2/5] fix(gapic-generator): mock ADC in extended-ops tests and use getattr for credentials_file --- .../%name_%version/%sub/_compat.py.j2 | 2 +- .../%name_%version/%sub/test_%service.py.j2 | 36 +++++++++++++------ 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 index e9401fee7a7c..9f6417a57869 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 @@ -469,7 +469,7 @@ except ImportError: # pragma: NO COVER and opts_universe is None ) needs_cred_clear = clear_credentials and bool( - client_options.credentials_file + getattr(client_options, "credentials_file", None) or getattr(client_options, "api_key", None) ) if needs_universe or needs_endpoint or needs_cred_clear: 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 f3ac564d125a..c6c505e71068 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 @@ -3113,12 +3113,21 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service universe_domain=EXTENDED_OPS_CUSTOM_UNIVERSE, ) - with mock.patch.object( - google.auth, - "load_credentials_from_file", - autospec=True, - spec_set=True, - return_value=(ga_credentials.AnonymousCredentials(), None), + with ( + mock.patch.object( + google.auth, + "load_credentials_from_file", + autospec=True, + spec_set=True, + return_value=(ga_credentials.AnonymousCredentials(), None), + ), + mock.patch.object( + google.auth, + "default", + autospec=True, + spec_set=True, + return_value=(ga_credentials.AnonymousCredentials(), None), + ), ): client_from_file = {{ service.client_name }}( transport=transport_name, @@ -3236,10 +3245,17 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service channel=mock.MagicMock(spec=grpc.Channel), client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, ) - assert ( - user_channel_transport.{{ op_prop }}.api_endpoint - == {{ op_tpclp_endpoint }} - ) + with mock.patch.object( + google.auth, + "default", + autospec=True, + spec_set=True, + return_value=(ga_credentials.AnonymousCredentials(), None), + ): + assert ( + user_channel_transport.{{ op_prop }}.api_endpoint + == {{ op_tpclp_endpoint }} + ) {% endif %} From 7b376055491034c55a7e6e40cb8398f9c69227a9 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Tue, 1 Dec 2026 11:41:46 -0500 Subject: [PATCH 3/5] fix(gapic-generator): address code and test review findings for extended-ops universe forwarding --- .../%name_%version/%sub/_compat.py.j2 | 62 +-- .../%sub/services/%service/client.py.j2 | 40 +- .../services/%service/transports/base.py.j2 | 48 +- .../%name_%version/%sub/test_%service.py.j2 | 471 ++++++++++++------ .../%name_%version/%sub/test_compat.py.j2 | 217 ++++---- 5 files changed, 504 insertions(+), 334 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 index 9f6417a57869..fc4d1a6215f3 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 @@ -413,7 +413,7 @@ except ImportError: # pragma: NO COVER Args: parent_universe (str): Resolved universe domain of the parent client. - client_options (Union[google.api_core.client_options.ClientOptions, Mapping[str, Any], None]): + client_options: Optional child ``ClientOptions`` instance or mapping. If ``None``, a new ``ClientOptions`` is created only when propagation is required. parent_api_endpoint (Optional[str]): Optional parent ``api_endpoint`` @@ -446,47 +446,37 @@ except ImportError: # pragma: NO COVER return None if isinstance(client_options, Mapping): opts = client_options_lib.from_dict(client_options) - opts_universe = getattr(opts, "universe_domain", None) - needs_endpoint = ( - has_parent_endpoint - and not opts.api_endpoint - and opts_universe is None + is_fresh_copy = True + elif isinstance(client_options, client_options_lib.ClientOptions): + opts = client_options + is_fresh_copy = False + else: + raise TypeError( + "client_options must be a ClientOptions instance, Mapping, or None; " + f"got {type(client_options).__name__}" ) - if opts_universe is None and should_propagate: + opts_universe = getattr(opts, "universe_domain", None) + needs_universe = opts_universe is None and should_propagate + needs_endpoint = ( + has_parent_endpoint + and not opts.api_endpoint + and opts_universe is None + ) + needs_cred_clear = clear_credentials and bool( + getattr(opts, "credentials_file", None) + or getattr(opts, "api_key", None) + ) + if needs_universe or needs_endpoint or needs_cred_clear: + if not is_fresh_copy: + opts = copy.copy(opts) + if needs_universe: opts.universe_domain = parent_universe if needs_endpoint: opts.api_endpoint = parent_api_endpoint - if clear_credentials: + if needs_cred_clear: opts.credentials_file = None opts.api_key = None - return opts - if isinstance(client_options, client_options_lib.ClientOptions): - opts_universe = getattr(client_options, "universe_domain", None) - needs_universe = opts_universe is None and should_propagate - needs_endpoint = ( - has_parent_endpoint - and not client_options.api_endpoint - and opts_universe is None - ) - needs_cred_clear = clear_credentials and bool( - getattr(client_options, "credentials_file", None) - or getattr(client_options, "api_key", None) - ) - if needs_universe or needs_endpoint or needs_cred_clear: - opts = copy.copy(client_options) - if needs_universe: - opts.universe_domain = parent_universe - if needs_endpoint: - opts.api_endpoint = parent_api_endpoint - if needs_cred_clear: - opts.credentials_file = None - opts.api_key = None - return opts - return client_options - raise TypeError( - "client_options must be a ClientOptions instance, Mapping, or None; " - f"got {type(client_options).__name__}" - ) + return opts {% endif %} {% if has_auto_populated_fields %} diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 index 5ce76a173eb3..6abbe94885b0 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 @@ -484,24 +484,36 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): client_options is not None or self._universe_domain != {{ service.client_name }}._DEFAULT_UNIVERSE ): - existing_ext_ops_options = ( - self._transport._extended_operations_client_options + configure_ext_ops = getattr( + self._transport, + "_configure_extended_operations_client_options", + None, ) - if not isinstance( - existing_ext_ops_options, client_options_lib.ClientOptions - ): - existing_ext_ops_options = None - self._transport._configure_extended_operations_client_options( - self._universe_domain, - existing_ext_ops_options - if client_options is None - else client_options, - fallback_endpoint=( + if callable(configure_ext_ops): + existing_ext_ops_options = getattr( + self._transport, + "_extended_operations_client_options", + None, + ) + if not isinstance( + existing_ext_ops_options, client_options_lib.ClientOptions + ): + existing_ext_ops_options = None + effective_options = ( + existing_ext_ops_options + if client_options is None + else client_options + ) + fallback_endpoint = ( existing_ext_ops_options.api_endpoint if existing_ext_ops_options is not None else None - ), - ) + ) + configure_ext_ops( + self._universe_domain, + effective_options, + fallback_endpoint=fallback_endpoint, + ) {% endif %} self._api_endpoint = (self._api_endpoint or diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 index e62e2ddadb14..044d11cd0d2a 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 @@ -192,28 +192,30 @@ class {{ service.name }}Transport(abc.ABC): {% if service.any_extended_operations_methods %} self._extended_operations_client_options = None env_universe = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - extended_ops_universe = _get_universe_domain( - client_options.get("universe_domain") - if isinstance(client_options, Mapping) - else getattr(client_options, "universe_domain", None), - env_universe if env_universe and env_universe.strip() else None, - default_universe=_DEFAULT_UNIVERSE, - ) - default_hosts = ( - self.DEFAULT_HOST, - f"{self.DEFAULT_HOST}:443", - f"https://{self.DEFAULT_HOST}", - f"https://{self.DEFAULT_HOST}:443", - ) - self._configure_extended_operations_client_options( - extended_ops_universe, - client_options, - fallback_endpoint=( - self._default_host - if self._default_host and self._default_host not in default_hosts - else None - ), - ) + if isinstance(client_options, Mapping): + client_universe = client_options.get("universe_domain") + else: + client_universe = getattr(client_options, "universe_domain", None) + if client_universe is not None or env_universe is None or env_universe.strip(): + extended_ops_universe = _get_universe_domain( + client_universe, + env_universe, + default_universe=_DEFAULT_UNIVERSE, + ) + default_hosts = ( + self.DEFAULT_HOST, + f"{self.DEFAULT_HOST}:443", + f"https://{self.DEFAULT_HOST}", + f"https://{self.DEFAULT_HOST}:443", + ) + fallback_endpoint = None + if self._default_host and self._default_host not in default_hosts: + fallback_endpoint = self._default_host + self._configure_extended_operations_client_options( + extended_ops_universe, + client_options, + fallback_endpoint=fallback_endpoint, + ) {% endif %} self._wrapped_methods: Dict[Callable, Callable] = {} @@ -555,7 +557,7 @@ class {{ service.name }}Transport(abc.ABC): opts = _inherit_universe_in_client_options( universe_domain, client_options, - clear_credentials=True, + clear_credentials=self._credentials is not None, ) if fallback_endpoint: if opts is None: 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 c6c505e71068..5332ca576180 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 @@ -75,6 +75,9 @@ from google.api_core import retry as retries {% if service.has_lro or service.has_extended_lro %} from google.api_core import future {% endif %} +{% if service.any_extended_operations_methods %} +from google.api_core.universe import EmptyUniverseError +{% endif %} {% if service.has_lro %} from google.api_core import operation from google.api_core import operations_v1 @@ -2864,6 +2867,10 @@ EXTENDED_OPS_DEFAULT_UNIVERSE = "googleapis.com" EXTENDED_OPS_CUSTOM_ENDPOINT = "custom.endpoint.test:443" EXTENDED_OPS_TRANSPORT_HOST = "custom.transport.test:443" EXTENDED_OPS_EXPLICIT_ENDPOINT = "explicit.options.test:443" +EXTENDED_OPS_CREDENTIALS_FILE = "creds.json" +EXTENDED_OPS_GDU_API_KEY = "test-gdu-key" +EXTENDED_OPS_TPC_API_KEY = "test-api-key" +EXTENDED_OPS_IGNORED_CHANNEL_HOST = "ignored.channel.test:443" @pytest.fixture @@ -2873,6 +2880,18 @@ def clean_universe_env(monkeypatch): return monkeypatch +@pytest.fixture +def mock_default_credentials(): + with mock.patch.object( + google.auth, + "default", + autospec=True, + spec_set=True, + return_value=(ga_credentials.AnonymousCredentials(), None), + ) as patched: + yield patched + + {% for operations_service in api.get_extended_operations_services(service)|sort(attribute="name") %} {% set op_prop = operations_service.client_name|snake_case|make_private %} {% set op_default_endpoint = '"' ~ operations_service.host ~ '"' if operations_service.host else 'None' %} @@ -3071,8 +3090,6 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_empty_universe_raises( clean_universe_env, transport_name, bad_universe ): - from google.api_core.universe import EmptyUniverseError - transport_cls = {{ service.client_name }}.get_transport_class(transport_name) with pytest.raises( @@ -3106,28 +3123,19 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service ], ) def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_clears_credentials_file( - clean_universe_env, transport_name + clean_universe_env, mock_default_credentials, transport_name ): file_opts = client_options.ClientOptions( - credentials_file="creds.json", + credentials_file=EXTENDED_OPS_CREDENTIALS_FILE, universe_domain=EXTENDED_OPS_CUSTOM_UNIVERSE, ) - with ( - mock.patch.object( - google.auth, - "load_credentials_from_file", - autospec=True, - spec_set=True, - return_value=(ga_credentials.AnonymousCredentials(), None), - ), - mock.patch.object( - google.auth, - "default", - autospec=True, - spec_set=True, - return_value=(ga_credentials.AnonymousCredentials(), None), - ), + with mock.patch.object( + google.auth, + "load_credentials_from_file", + autospec=True, + spec_set=True, + return_value=(ga_credentials.AnonymousCredentials(), None), ): client_from_file = {{ service.client_name }}( transport=transport_name, @@ -3137,7 +3145,7 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service assert op_from_file.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE assert op_from_file._client_options.credentials_file is None - assert file_opts.credentials_file == "creds.json" + assert file_opts.credentials_file == EXTENDED_OPS_CREDENTIALS_FILE @pytest.mark.parametrize( @@ -3151,41 +3159,50 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service {% endif %} ], ) +@pytest.mark.parametrize( + "options_factory,expected_universe,expected_original_key", + [ + pytest.param( + lambda: client_options.ClientOptions(api_key=EXTENDED_OPS_GDU_API_KEY), + EXTENDED_OPS_DEFAULT_UNIVERSE, + EXTENDED_OPS_GDU_API_KEY, + id="gdu_client_options", + ), + pytest.param( + lambda: { + "api_key": EXTENDED_OPS_TPC_API_KEY, + "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, + }, + EXTENDED_OPS_CUSTOM_UNIVERSE, + EXTENDED_OPS_TPC_API_KEY, + id="tpc_dict", + ), + ], +) def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_clears_api_key( - clean_universe_env, transport_name + clean_universe_env, + mock_default_credentials, + transport_name, + options_factory, + expected_universe, + expected_original_key, ): - gdu_key_opts = client_options.ClientOptions(api_key="test-gdu-key") - tpc_key_dict = { - "api_key": "test-api-key", - "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, - } + # mock_default_credentials also guards google-auth < 2.16.0 lowest-constraints + # runs where google.auth._default.get_api_key_credentials is not yet available. + opts = options_factory() - # Patch google.auth.default for google-auth < 2.16.0 lowest-constraints runs - # where google.auth._default.get_api_key_credentials is not yet available. - with mock.patch.object( - google.auth, - "default", - autospec=True, - spec_set=True, - return_value=(ga_credentials.AnonymousCredentials(), None), - ): - client_gdu_key = {{ service.client_name }}( - transport=transport_name, - client_options=gdu_key_opts, - ) - client_tpc_key = {{ service.client_name }}( - transport=transport_name, - client_options=tpc_key_dict, - ) - op_gdu_key = client_gdu_key.transport.{{ op_prop }} - op_tpc_key = client_tpc_key.transport.{{ op_prop }} + client = {{ service.client_name }}( + transport=transport_name, + client_options=opts, + ) + op_client = client.transport.{{ op_prop }} - assert op_gdu_key.universe_domain == EXTENDED_OPS_DEFAULT_UNIVERSE - assert op_gdu_key._client_options.api_key is None - assert gdu_key_opts.api_key == "test-gdu-key" - assert op_tpc_key.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE - assert op_tpc_key._client_options.api_key is None - assert tpc_key_dict["api_key"] == "test-api-key" + assert op_client.universe_domain == expected_universe + assert op_client._client_options.api_key is None + if isinstance(opts, dict): + assert opts["api_key"] == expected_original_key + else: + assert opts.api_key == expected_original_key @pytest.mark.parametrize( @@ -3199,64 +3216,133 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service {% endif %} ], ) +@pytest.mark.parametrize( + "host_fn,options_fn,expected_universe,expected_endpoint_fn", + [ + pytest.param( + lambda cls: EXTENDED_OPS_TRANSPORT_HOST, + lambda: {"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + EXTENDED_OPS_CUSTOM_UNIVERSE, + lambda transport: transport.host, + id="custom_host_with_tpc_dict", + ), + pytest.param( + lambda cls: EXTENDED_OPS_TRANSPORT_HOST, + client_options.ClientOptions, + EXTENDED_OPS_DEFAULT_UNIVERSE, + lambda transport: transport.host, + id="custom_host_with_empty_client_options", + ), + pytest.param( + lambda cls: EXTENDED_OPS_TRANSPORT_HOST, + lambda: client_options.ClientOptions( + api_endpoint=EXTENDED_OPS_EXPLICIT_ENDPOINT + ), + EXTENDED_OPS_DEFAULT_UNIVERSE, + lambda transport: EXTENDED_OPS_EXPLICIT_ENDPOINT, + id="explicit_endpoint_overrides_transport_host", + ), + pytest.param( + lambda cls: f"https://{cls.DEFAULT_HOST}:443", + lambda: {"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + EXTENDED_OPS_CUSTOM_UNIVERSE, + lambda transport: {{ op_tpclp_endpoint }}, + id="default_https_host_uses_tpc_endpoint", + ), + ], +) def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_direct_transport_options( - clean_universe_env, transport_class + clean_universe_env, + transport_class, + host_fn, + options_fn, + expected_universe, + expected_endpoint_fn, ): - direct_transport = transport_class( - host=EXTENDED_OPS_TRANSPORT_HOST, - credentials=ga_credentials.AnonymousCredentials(), - client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, - ) - empty_opts = client_options.ClientOptions() - transport_with_empty_opts = transport_class( - host=EXTENDED_OPS_TRANSPORT_HOST, - credentials=ga_credentials.AnonymousCredentials(), - client_options=empty_opts, - ) - explicit_opts = client_options.ClientOptions( - api_endpoint=EXTENDED_OPS_EXPLICIT_ENDPOINT + opts = options_fn() + started_without_endpoint = ( + isinstance(opts, client_options.ClientOptions) + and opts.api_endpoint is None ) - transport_with_explicit_opts = transport_class( - host=EXTENDED_OPS_TRANSPORT_HOST, + transport = transport_class( + host=host_fn(transport_class), credentials=ga_credentials.AnonymousCredentials(), - client_options=explicit_opts, + client_options=opts, ) - default_https_transport = transport_class( - host=f"https://{transport_class.DEFAULT_HOST}:443", - credentials=ga_credentials.AnonymousCredentials(), + op_client = transport.{{ op_prop }} + + assert op_client.universe_domain == expected_universe + assert op_client.api_endpoint == expected_endpoint_fn(transport) + if started_without_endpoint: + assert opts.api_endpoint is None + + +{% if 'grpc' in opts.transport %} +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_direct_transport_user_channel_ignores_host( + clean_universe_env, mock_default_credentials +): + user_channel_transport = transports.{{ service.grpc_transport_name }}( + host=EXTENDED_OPS_IGNORED_CHANNEL_HOST, + channel=mock.create_autospec(grpc.Channel, instance=True, spec_set=True), client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, ) - op_direct = direct_transport.{{ op_prop }} - op_empty = transport_with_empty_opts.{{ op_prop }} - op_explicit = transport_with_explicit_opts.{{ op_prop }} - op_default_https = default_https_transport.{{ op_prop }} + assert user_channel_transport.{{ op_prop }}.api_endpoint == {{ op_tpclp_endpoint }} - assert op_direct.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE - assert op_direct.api_endpoint == direct_transport.host - assert empty_opts.api_endpoint is None - assert op_empty.api_endpoint == transport_with_empty_opts.host - assert op_explicit.api_endpoint == EXTENDED_OPS_EXPLICIT_ENDPOINT - assert op_default_https.api_endpoint == {{ op_tpclp_endpoint }} - {% if 'grpc' in opts.transport %} - if transport_class is transports.{{ service.grpc_transport_name }}: - user_channel_transport = transport_class( - host="ignored.channel.test:443", - channel=mock.MagicMock(spec=grpc.Channel), - client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, - ) - with mock.patch.object( - google.auth, - "default", - autospec=True, - spec_set=True, - return_value=(ga_credentials.AnonymousCredentials(), None), - ): - assert ( - user_channel_transport.{{ op_prop }}.api_endpoint - == {{ op_tpclp_endpoint }} - ) - {% endif %} + +{% endif %} +@pytest.mark.parametrize( + "transport_class", + [ + {% if 'grpc' in opts.transport %} + pytest.param(transports.{{ service.grpc_transport_name }}, id="grpc"), + {% endif %} + {% if 'rest' in opts.transport %} + pytest.param(transports.{{ service.rest_transport_name }}, id="rest"), + {% endif %} + ], +) +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_direct_transport_env_universe( + clean_universe_env, transport_class +): + clean_universe_env.setenv( + "GOOGLE_CLOUD_UNIVERSE_DOMAIN", EXTENDED_OPS_CUSTOM_UNIVERSE + ) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + op_client = transport.{{ op_prop }} + + assert op_client.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE + assert op_client.api_endpoint == {{ op_tpclp_endpoint }} + + +@pytest.mark.parametrize( + "transport_class", + [ + {% if 'grpc' in opts.transport %} + pytest.param(transports.{{ service.grpc_transport_name }}, id="grpc"), + {% endif %} + {% if 'rest' in opts.transport %} + pytest.param(transports.{{ service.rest_transport_name }}, id="rest"), + {% endif %} + ], +) +@pytest.mark.parametrize( + "bad_env", + [ + pytest.param("", id="empty_env"), + pytest.param(" ", id="whitespace_env"), + ], +) +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_direct_transport_blank_env_raises( + clean_universe_env, transport_class, bad_env +): + clean_universe_env.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", bad_env) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + with pytest.raises( + EmptyUniverseError, + match=r"^Universe Domain cannot be an empty string\.$", + ): + _ = transport.{{ op_prop }} @pytest.mark.parametrize( @@ -3290,6 +3376,16 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service assert op_prebuilt.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE assert op_prebuilt.api_endpoint == prebuilt_transport.host + gdu_endpoint_client = {{ service.client_name }}( + transport=prebuilt_transport, + client_options={"api_endpoint": EXTENDED_OPS_EXPLICIT_ENDPOINT}, + ) + op_gdu_endpoint = gdu_endpoint_client.transport.{{ op_prop }} + + assert op_gdu_endpoint is not op_prebuilt + assert op_gdu_endpoint.universe_domain == EXTENDED_OPS_DEFAULT_UNIVERSE + assert op_gdu_endpoint.api_endpoint == EXTENDED_OPS_EXPLICIT_ENDPOINT + @pytest.mark.parametrize( "transport_class", @@ -3302,64 +3398,69 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service {% endif %} ], ) +@pytest.mark.parametrize( + "transport_kwargs,env_universe,expected_universe,expected_quota_project,expect_transport_host", + [ + pytest.param( + { + "client_options": { + "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, + "quota_project_id": "qp-gdu", + }, + }, + None, + EXTENDED_OPS_CUSTOM_UNIVERSE, + "qp-gdu", + False, + id="gdu_client_preserves_tpc_transport", + ), + pytest.param( + { + "client_options": { + "universe_domain": EXTENDED_OPS_DEFAULT_UNIVERSE, + "quota_project_id": "qp-transport", + }, + }, + EXTENDED_OPS_CUSTOM_UNIVERSE, + EXTENDED_OPS_DEFAULT_UNIVERSE, + "qp-transport", + False, + id="tpc_env_preserves_configured_transport", + ), + pytest.param( + {"host": EXTENDED_OPS_TRANSPORT_HOST}, + EXTENDED_OPS_CUSTOM_UNIVERSE, + EXTENDED_OPS_CUSTOM_UNIVERSE, + None, + True, + id="tpc_env_inherits_into_unconfigured_transport", + ), + ], +) def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_prebuilt_transport_preserves_options( - clean_universe_env, transport_class + clean_universe_env, + transport_class, + transport_kwargs, + env_universe, + expected_universe, + expected_quota_project, + expect_transport_host, ): - configured_transport = transport_class( + transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), - client_options={ - "universe_domain": EXTENDED_OPS_DEFAULT_UNIVERSE, - "quota_project_id": "qp-transport", - }, - ) - unconfigured_transport = transport_class( - host=EXTENDED_OPS_TRANSPORT_HOST, - credentials=ga_credentials.AnonymousCredentials(), - ) - gdu_transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_options={ - "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, - "quota_project_id": "qp-gdu", - }, + **transport_kwargs, ) + if env_universe is not None: + clean_universe_env.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", env_universe) - client_gdu_preserving = {{ service.client_name }}(transport=gdu_transport) - clean_universe_env.setenv( - "GOOGLE_CLOUD_UNIVERSE_DOMAIN", EXTENDED_OPS_CUSTOM_UNIVERSE - ) - client_env_preserving = {{ service.client_name }}( - transport=configured_transport - ) - client_env_inheriting = {{ service.client_name }}( - transport=unconfigured_transport - ) - clean_universe_env.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) + client = {{ service.client_name }}(transport=transport) + op_client = client.transport.{{ op_prop }} - assert ( - client_gdu_preserving.transport.{{ op_prop }}.universe_domain - == EXTENDED_OPS_CUSTOM_UNIVERSE - ) - assert ( - client_gdu_preserving.transport.{{ op_prop }}._client_options.quota_project_id - == "qp-gdu" - ) - assert ( - client_env_preserving.transport.{{ op_prop }}.universe_domain - == EXTENDED_OPS_DEFAULT_UNIVERSE - ) - assert ( - client_env_preserving.transport.{{ op_prop }}._client_options.quota_project_id - == "qp-transport" - ) - assert ( - client_env_inheriting.transport.{{ op_prop }}.universe_domain - == EXTENDED_OPS_CUSTOM_UNIVERSE - ) - assert ( - client_env_inheriting.transport.{{ op_prop }}.api_endpoint - == unconfigured_transport.host - ) + assert op_client.universe_domain == expected_universe + if expected_quota_project is not None: + assert op_client._client_options.quota_project_id == expected_quota_project + if expect_transport_host: + assert op_client.api_endpoint == transport.host @pytest.mark.parametrize( @@ -3373,36 +3474,78 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service {% endif %} ], ) -def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_autospec_mock_and_callable_transport( +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_autospec_mock_transport( clean_universe_env, transport_class ): autospec_transport = mock.create_autospec( transport_class, instance=True, spec_set=True ) autospec_transport.host = EXTENDED_OPS_TRANSPORT_HOST - callable_transport = mock.create_autospec( - transport_class, instance=True, spec_set=True - ) {{ service.client_name }}( transport=autospec_transport, client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, ) - client_with_callable = {{ service.client_name }}( - credentials=ga_credentials.AnonymousCredentials(), - transport=lambda **kwargs: callable_transport, - client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, - ) autospec_transport._configure_extended_operations_client_options.assert_called_once_with( EXTENDED_OPS_CUSTOM_UNIVERSE, {"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, fallback_endpoint=None, ) - assert ( - client_with_callable.transport._extended_operations_client_options.universe_domain - == EXTENDED_OPS_CUSTOM_UNIVERSE + + +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_duck_typed_transport_ignored( + clean_universe_env, +): + class CustomTransport(transports.{{ service.name }}Transport): + _configure_extended_operations_client_options = None + + def __init__(self): + self._host = EXTENDED_OPS_TRANSPORT_HOST + + @property + def kind(self) -> str: + return "custom" + + custom_transport = CustomTransport() + client = {{ service.client_name }}( + transport=custom_transport, + client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + ) + + assert client.transport is custom_transport + + +@pytest.mark.parametrize( + "transport_class", + [ + {% if 'grpc' in opts.transport %} + pytest.param(transports.{{ service.grpc_transport_name }}, id="grpc"), + {% endif %} + {% if 'rest' in opts.transport %} + pytest.param(transports.{{ service.rest_transport_name }}, id="rest"), + {% endif %} + ], +) +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_callable_transport( + clean_universe_env, mock_default_credentials, transport_class +): + real_transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() ) + + client_with_callable = {{ service.client_name }}( + transport=lambda **kwargs: real_transport, + client_options={ + "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, + "api_key": EXTENDED_OPS_TPC_API_KEY, + }, + ) + op_client = client_with_callable.transport.{{ op_prop }} + + assert op_client.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE + assert op_client.api_endpoint == {{ op_tpclp_endpoint }} + assert op_client._client_options.api_key is None {% endfor %} {% endif %} diff --git a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 index 249fcdb11115..bd57cc28ec79 100644 --- a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 +++ b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 @@ -11,6 +11,10 @@ google-api-core has the functions in `_compat.py.j2`. #} {# TODO(https://github.com/googleapis/google-cloud-python/issues/17883): Backfill compatibility functions tests being removed from the client layer. #} +{% if has_extended_operations %} +import copy +import importlib +{% endif %} import json import pytest import os @@ -39,8 +43,9 @@ from {{package_path}}._compat import ( from {{package_path}}._compat import setup_request_id {% endif %} {% if has_extended_operations %} -import copy from google.api_core import client_options as client_options_lib +import google.api_core.universe +from {{package_path}} import _compat from {{package_path}}._compat import inherit_universe_in_client_options {% endif %} @@ -625,14 +630,11 @@ COMPAT_PARENT_ENDPOINT = "custom.endpoint:443" COMPAT_CHILD_ENDPOINT = "child.endpoint:443" COMPAT_API_KEY = "secret" COMPAT_CREDENTIALS_FILE = "creds.json" +COMPAT_QUOTA_PROJECT_ID = "qp-1" @pytest.fixture def fallback_inherit_universe(monkeypatch): - import importlib - import google.api_core.universe - from {{package_path}} import _compat - monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) monkeypatch.delattr( google.api_core.universe, @@ -648,12 +650,8 @@ def fallback_inherit_universe(monkeypatch): def test_inherit_universe_in_client_options_compat_reexport(monkeypatch): - import importlib - import google.api_core.universe - from {{package_path}} import _compat - assert callable(inherit_universe_in_client_options) - sentinel = mock.MagicMock() + sentinel = object() monkeypatch.setattr( google.api_core.universe, "inherit_universe_in_client_options", @@ -674,11 +672,7 @@ def test_inherit_universe_in_client_options_compat_reexport(monkeypatch): "client_options", "parent_api_endpoint", "clear_credentials", - "expected_universe", - "expected_endpoint", - "expected_api_key", - "expected_credentials_file", - "expected_quota_project", + "expected", ), [ pytest.param( @@ -686,11 +680,7 @@ def test_inherit_universe_in_client_options_compat_reexport(monkeypatch): None, COMPAT_PARENT_ENDPOINT, False, - None, - COMPAT_PARENT_ENDPOINT, - None, - None, - None, + {"api_endpoint": COMPAT_PARENT_ENDPOINT}, id="none_gdu_with_parent_endpoint_only", ), pytest.param( @@ -698,11 +688,7 @@ def test_inherit_universe_in_client_options_compat_reexport(monkeypatch): None, "", False, - COMPAT_CUSTOM_UNIVERSE, - None, - None, - None, - None, + {"universe_domain": COMPAT_CUSTOM_UNIVERSE}, id="none_custom_universe_with_empty_parent_endpoint", ), pytest.param( @@ -710,41 +696,48 @@ def test_inherit_universe_in_client_options_compat_reexport(monkeypatch): None, COMPAT_PARENT_ENDPOINT, False, - COMPAT_CUSTOM_UNIVERSE, - COMPAT_PARENT_ENDPOINT, - None, - None, - None, + { + "universe_domain": COMPAT_CUSTOM_UNIVERSE, + "api_endpoint": COMPAT_PARENT_ENDPOINT, + }, id="none_inherits_universe_and_endpoint", ), + pytest.param( + COMPAT_DEFAULT_UNIVERSE, + {}, + None, + False, + {}, + id="empty_mapping_gdu_leaves_universe_unset", + ), pytest.param( COMPAT_CUSTOM_UNIVERSE, { - "quota_project_id": "qp-1", + "quota_project_id": COMPAT_QUOTA_PROJECT_ID, "api_key": COMPAT_API_KEY, }, COMPAT_PARENT_ENDPOINT, True, - COMPAT_CUSTOM_UNIVERSE, - COMPAT_PARENT_ENDPOINT, - None, - None, - "qp-1", + { + "universe_domain": COMPAT_CUSTOM_UNIVERSE, + "api_endpoint": COMPAT_PARENT_ENDPOINT, + "quota_project_id": COMPAT_QUOTA_PROJECT_ID, + }, id="mapping_inherits_and_clears_api_key", ), pytest.param( COMPAT_CUSTOM_UNIVERSE, { - "quota_project_id": "qp-1", + "quota_project_id": COMPAT_QUOTA_PROJECT_ID, "credentials_file": COMPAT_CREDENTIALS_FILE, }, COMPAT_PARENT_ENDPOINT, True, - COMPAT_CUSTOM_UNIVERSE, - COMPAT_PARENT_ENDPOINT, - None, - None, - "qp-1", + { + "universe_domain": COMPAT_CUSTOM_UNIVERSE, + "api_endpoint": COMPAT_PARENT_ENDPOINT, + "quota_project_id": COMPAT_QUOTA_PROJECT_ID, + }, id="mapping_inherits_and_clears_credentials_file", ), pytest.param( @@ -752,11 +745,11 @@ def test_inherit_universe_in_client_options_compat_reexport(monkeypatch): {"api_endpoint": COMPAT_CHILD_ENDPOINT, "api_key": COMPAT_API_KEY}, COMPAT_PARENT_ENDPOINT, False, - COMPAT_CUSTOM_UNIVERSE, - COMPAT_CHILD_ENDPOINT, - COMPAT_API_KEY, - None, - None, + { + "universe_domain": COMPAT_CUSTOM_UNIVERSE, + "api_endpoint": COMPAT_CHILD_ENDPOINT, + "api_key": COMPAT_API_KEY, + }, id="mapping_child_endpoint_preserved_without_cred_clear", ), pytest.param( @@ -764,13 +757,25 @@ def test_inherit_universe_in_client_options_compat_reexport(monkeypatch): {"universe_domain": COMPAT_CHILD_UNIVERSE, "api_key": COMPAT_API_KEY}, COMPAT_PARENT_ENDPOINT, False, - COMPAT_CHILD_UNIVERSE, - None, - COMPAT_API_KEY, - None, - None, + { + "universe_domain": COMPAT_CHILD_UNIVERSE, + "api_key": COMPAT_API_KEY, + }, id="mapping_child_universe_blocks_parent_endpoint", ), + pytest.param( + COMPAT_DEFAULT_UNIVERSE, + client_options_lib.ClientOptions( + quota_project_id=COMPAT_QUOTA_PROJECT_ID, + ), + COMPAT_PARENT_ENDPOINT, + False, + { + "api_endpoint": COMPAT_PARENT_ENDPOINT, + "quota_project_id": COMPAT_QUOTA_PROJECT_ID, + }, + id="client_options_gdu_inherits_endpoint_only", + ), pytest.param( COMPAT_CUSTOM_UNIVERSE, client_options_lib.ClientOptions( @@ -779,11 +784,11 @@ def test_inherit_universe_in_client_options_compat_reexport(monkeypatch): ), COMPAT_PARENT_ENDPOINT, False, - COMPAT_CUSTOM_UNIVERSE, - COMPAT_CHILD_ENDPOINT, - COMPAT_API_KEY, - None, - None, + { + "universe_domain": COMPAT_CUSTOM_UNIVERSE, + "api_endpoint": COMPAT_CHILD_ENDPOINT, + "api_key": COMPAT_API_KEY, + }, id="client_options_preserves_child_endpoint_and_credentials", ), pytest.param( @@ -791,11 +796,10 @@ def test_inherit_universe_in_client_options_compat_reexport(monkeypatch): client_options_lib.ClientOptions(api_key=COMPAT_API_KEY), COMPAT_PARENT_ENDPOINT, True, - COMPAT_CUSTOM_UNIVERSE, - COMPAT_PARENT_ENDPOINT, - None, - None, - None, + { + "universe_domain": COMPAT_CUSTOM_UNIVERSE, + "api_endpoint": COMPAT_PARENT_ENDPOINT, + }, id="client_options_inherits_and_clears_api_key", ), pytest.param( @@ -805,11 +809,10 @@ def test_inherit_universe_in_client_options_compat_reexport(monkeypatch): ), COMPAT_PARENT_ENDPOINT, True, - COMPAT_CUSTOM_UNIVERSE, - COMPAT_PARENT_ENDPOINT, - None, - None, - None, + { + "universe_domain": COMPAT_CUSTOM_UNIVERSE, + "api_endpoint": COMPAT_PARENT_ENDPOINT, + }, id="client_options_inherits_and_clears_credentials_file", ), pytest.param( @@ -820,11 +823,7 @@ def test_inherit_universe_in_client_options_compat_reexport(monkeypatch): ), COMPAT_PARENT_ENDPOINT, True, - COMPAT_CHILD_UNIVERSE, - None, - None, - None, - None, + {"universe_domain": COMPAT_CHILD_UNIVERSE}, id="client_options_child_universe_blocks_parent_endpoint", ), ], @@ -835,11 +834,7 @@ def test_inherit_universe_in_client_options_compat_propagates_options( client_options, parent_api_endpoint, clear_credentials, - expected_universe, - expected_endpoint, - expected_api_key, - expected_credentials_file, - expected_quota_project, + expected, ): options = copy.deepcopy(client_options) @@ -851,11 +846,11 @@ def test_inherit_universe_in_client_options_compat_propagates_options( ) assert inherited is not None - assert inherited.universe_domain == expected_universe - assert inherited.api_endpoint == expected_endpoint - assert inherited.api_key == expected_api_key - assert inherited.credentials_file == expected_credentials_file - assert inherited.quota_project_id == expected_quota_project + assert inherited.universe_domain == expected.get("universe_domain") + assert inherited.api_endpoint == expected.get("api_endpoint") + assert inherited.api_key == expected.get("api_key") + assert inherited.credentials_file == expected.get("credentials_file") + assert inherited.quota_project_id == expected.get("quota_project_id") @pytest.mark.parametrize( @@ -875,13 +870,24 @@ def test_inherit_universe_in_client_options_compat_gdu_none_returns_none( assert inherited is None +@pytest.mark.parametrize( + "clear_credentials", + [ + pytest.param(False, id="keep_credentials"), + pytest.param(True, id="clear_credentials_noop"), + ], +) def test_inherit_universe_in_client_options_compat_unchanged_returns_same_instance( - fallback_inherit_universe, + fallback_inherit_universe, clear_credentials ): - unchanged_opts = client_options_lib.ClientOptions(quota_project_id="qp-1") + unchanged_opts = client_options_lib.ClientOptions( + quota_project_id=COMPAT_QUOTA_PROJECT_ID + ) inherited = fallback_inherit_universe( - COMPAT_DEFAULT_UNIVERSE, unchanged_opts + COMPAT_DEFAULT_UNIVERSE, + unchanged_opts, + clear_credentials=clear_credentials, ) assert inherited is unchanged_opts @@ -891,7 +897,7 @@ def test_inherit_universe_in_client_options_compat_preserves_caller_inputs( fallback_inherit_universe, ): raw_dict = { - "quota_project_id": "qp-1", + "quota_project_id": COMPAT_QUOTA_PROJECT_ID, "api_key": COMPAT_API_KEY, } parent_opts = client_options_lib.ClientOptions( @@ -906,7 +912,7 @@ def test_inherit_universe_in_client_options_compat_preserves_caller_inputs( ) assert raw_dict == { - "quota_project_id": "qp-1", + "quota_project_id": COMPAT_QUOTA_PROJECT_ID, "api_key": COMPAT_API_KEY, } assert inherited_from_dict.api_key is None @@ -915,19 +921,36 @@ def test_inherit_universe_in_client_options_compat_preserves_caller_inputs( assert inherited_from_opts.credentials_file is None +@pytest.mark.parametrize( + "env_value,expected_universe", + [ + pytest.param(" googleapis.com ", None, id="whitespace_padded_gdu"), + pytest.param( + COMPAT_CUSTOM_UNIVERSE, + COMPAT_DEFAULT_UNIVERSE, + id="tpc_env_requires_explicit_gdu", + ), + pytest.param("", COMPAT_DEFAULT_UNIVERSE, id="empty_env_requires_explicit_gdu"), + pytest.param( + " ", + COMPAT_DEFAULT_UNIVERSE, + id="whitespace_env_requires_explicit_gdu", + ), + ], +) def test_inherit_universe_in_client_options_compat_env_override_and_whitespace( - fallback_inherit_universe, monkeypatch + fallback_inherit_universe, monkeypatch, env_value, expected_universe ): - monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", " googleapis.com ") - assert fallback_inherit_universe(COMPAT_DEFAULT_UNIVERSE, None) is None + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", env_value) - monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", COMPAT_CUSTOM_UNIVERSE) - inherited_env_override = fallback_inherit_universe( - COMPAT_DEFAULT_UNIVERSE, None - ) - assert inherited_env_override is not None - assert inherited_env_override.universe_domain == COMPAT_DEFAULT_UNIVERSE - assert inherited_env_override.api_endpoint is None + inherited = fallback_inherit_universe(COMPAT_DEFAULT_UNIVERSE, None) + + if expected_universe is None: + assert inherited is None + else: + assert inherited is not None + assert inherited.universe_domain == expected_universe + assert inherited.api_endpoint is None def test_inherit_universe_in_client_options_compat_invalid_type_raises( From 65d654713538bccf1a08761317872bf1b25bbdff Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Tue, 1 Dec 2026 12:56:26 -0500 Subject: [PATCH 4/5] refactor(gapic-generator): move _inherit_universe_in_client_options from _compat to transports/base --- .../%name_%version/%sub/_compat.py.j2 | 101 ----- .../%sub/services/%service/client.py.j2 | 10 +- .../services/%service/transports/base.py.j2 | 82 +++- .../%name_%version/%sub/test_%service.py.j2 | 325 ++++++++++++++++ .../%name_%version/%sub/test_compat.py.j2 | 353 ------------------ 5 files changed, 411 insertions(+), 460 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 index fc4d1a6215f3..0716f72decba 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 @@ -4,7 +4,6 @@ """A compatibility module for older versions of google-api-core.""" {% set has_auto_populated_fields = api.all_method_settings.values()|map(attribute="auto_populated_fields", default=[])|select|list %} -{% set has_extended_operations = api.services.values()|selectattr("any_extended_operations_methods")|list|length > 0 %} {# TODO(https://github.com/googleapis/google-cloud-python/issues/17813): Clean up this file/functions when the minimum supported version of google-api-core has the functions in `_compat.py.j2`. #} @@ -14,10 +13,6 @@ falling back to the local implementation if not present. #} {# TODO(https://github.com/googleapis/google-cloud-python/issues/17883): Backfill compatibility functions being removed from the client layer. #} -{% if has_extended_operations %} -from collections.abc import Mapping -import copy -{% endif %} import inspect import os import json @@ -29,13 +24,8 @@ import google.protobuf.message from typing import Any, Dict, List, Optional, Sequence, Tuple {% if has_auto_populated_fields %} from typing import TYPE_CHECKING, Union -{% elif has_extended_operations %} -from typing import Union {% endif %} -{% if has_extended_operations %} -from google.api_core import client_options as client_options_lib -{% endif %} from google.api_core import gapic_v1 from google.api_core import path_template from google.api_core.universe import EmptyUniverseError @@ -388,97 +378,6 @@ except ImportError: # pragma: NO COVER raise EmptyUniverseError() return resolved -{% if has_extended_operations %} -try: - # mypy flags [attr-defined] when type-checking generated libraries against - # google-api-core <= 2.44.0 before inherit_universe_in_client_options ships. - from google.api_core.universe import ( # type: ignore[attr-defined] - inherit_universe_in_client_options, - ) -except ImportError: # pragma: NO COVER - {# The fallback implementation for `inherit_universe_in_client_options` can be removed once the minimum version of `google-api-core` exceeds 2.44.0 in `setup.py.j2`. #} - # TODO(universe-domain): Replace with - # google.api_core.universe.inherit_universe_in_client_options once minimum - # allowed google-api-core version exceeds 2.44.0. - def inherit_universe_in_client_options( - parent_universe: str, - client_options: Union[ - client_options_lib.ClientOptions, Mapping[str, Any], None - ] = None, - *, - parent_api_endpoint: Optional[str] = None, - clear_credentials: bool = False, - ) -> Optional[client_options_lib.ClientOptions]: - """Inherit ``parent_universe`` onto child ``client_options`` when unset. - - Args: - parent_universe (str): Resolved universe domain of the parent client. - client_options: - Optional child ``ClientOptions`` instance or mapping. If ``None``, - a new ``ClientOptions`` is created only when propagation is required. - parent_api_endpoint (Optional[str]): Optional parent ``api_endpoint`` - override inherited when both ``api_endpoint`` and ``universe_domain`` - are unset on ``client_options``. If ``None``, no endpoint is inherited. - clear_credentials (bool): Whether to clear ``credentials_file`` and - ``api_key`` on the returned copy to avoid duplicate-credential errors. - - Returns: - Optional[google.api_core.client_options.ClientOptions]: Updated - ``ClientOptions`` instance (never mutating caller inputs), or ``None`` - when ``client_options`` is ``None`` and default resolution already - matches the parent. - - Raises: - TypeError: If ``client_options`` is not a ``ClientOptions`` instance, - ``Mapping``, or ``None``. - """ - env_universe = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - should_propagate = parent_universe != DEFAULT_UNIVERSE or ( - env_universe is not None and env_universe.strip() != parent_universe - ) - has_parent_endpoint = bool(parent_api_endpoint) - if client_options is None: - if should_propagate or has_parent_endpoint: - return client_options_lib.ClientOptions( - api_endpoint=parent_api_endpoint if has_parent_endpoint else None, - universe_domain=parent_universe if should_propagate else None, - ) - return None - if isinstance(client_options, Mapping): - opts = client_options_lib.from_dict(client_options) - is_fresh_copy = True - elif isinstance(client_options, client_options_lib.ClientOptions): - opts = client_options - is_fresh_copy = False - else: - raise TypeError( - "client_options must be a ClientOptions instance, Mapping, or None; " - f"got {type(client_options).__name__}" - ) - opts_universe = getattr(opts, "universe_domain", None) - needs_universe = opts_universe is None and should_propagate - needs_endpoint = ( - has_parent_endpoint - and not opts.api_endpoint - and opts_universe is None - ) - needs_cred_clear = clear_credentials and bool( - getattr(opts, "credentials_file", None) - or getattr(opts, "api_key", None) - ) - if needs_universe or needs_endpoint or needs_cred_clear: - if not is_fresh_copy: - opts = copy.copy(opts) - if needs_universe: - opts.universe_domain = parent_universe - if needs_endpoint: - opts.api_endpoint = parent_api_endpoint - if needs_cred_clear: - opts.credentials_file = None - opts.api_key = None - return opts - -{% endif %} {% if has_auto_populated_fields %} try: diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 index 6abbe94885b0..03f7493470fe 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 @@ -35,9 +35,6 @@ from google.api_core.resumable_transfer import ResumableUploadConfig {% endif %} from {{package_path}}._compat import _observability from {{package_path}}._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables -{% if service.any_extended_operations_methods %} -from {{package_path}}._compat import inherit_universe_in_client_options -{% endif %} {% if has_auto_populated_fields %} from {{package_path}}._compat import setup_request_id {% endif %} @@ -81,6 +78,9 @@ from google.longrunning import operations_pb2 # type: ignore {% endif %} {% endfilter %} from .transports.base import {{ service.name }}Transport, DEFAULT_CLIENT_INFO +{% if service.any_extended_operations_methods %} +from .transports.base import _inherit_universe_in_client_options +{% endif %} {% if 'grpc' in opts.transport %} from .transports.grpc import {{ service.grpc_transport_name }} from .transports.grpc_asyncio import {{ service.grpc_asyncio_transport_name }} @@ -564,7 +564,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): ) {% if service.any_extended_operations_methods %} self._transport._extended_operations_client_options = ( # pragma: NO COVER - inherit_universe_in_client_options( + _inherit_universe_in_client_options( self._universe_domain, self._client_options, clear_credentials=True, @@ -615,7 +615,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): self._transport = transport_init(**transport_kwargs) {% if service.any_extended_operations_methods %} self._transport._extended_operations_client_options = ( - inherit_universe_in_client_options( + _inherit_universe_in_client_options( self._universe_domain, self._client_options, clear_credentials=True, diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 index 044d11cd0d2a..32c60a5ba98e 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2 @@ -21,7 +21,6 @@ from {{package_path}}._compat import ( WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, {% if service.any_extended_operations_methods %} get_universe_domain as _get_universe_domain, - inherit_universe_in_client_options as _inherit_universe_in_client_options, {% endif %} ) _ASYNC_WRAP_METHOD_SUPPORTS_TRACING = _WRAP_METHOD_SUPPORTS_TRACING @@ -75,6 +74,87 @@ from {{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + ser DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +{% if service.any_extended_operations_methods %} + + +def _inherit_universe_in_client_options( + parent_universe: str, + client_options: Union[ + client_options_lib.ClientOptions, Mapping[str, Any], None + ] = None, + *, + parent_api_endpoint: Optional[str] = None, + clear_credentials: bool = False, +) -> Optional[client_options_lib.ClientOptions]: + """Inherit ``parent_universe`` onto child ``client_options`` when unset. + + Args: + parent_universe (str): Resolved universe domain of the parent client. + client_options: + Optional child ``ClientOptions`` instance or mapping. If ``None``, + a new ``ClientOptions`` is created only when propagation is required. + parent_api_endpoint (Optional[str]): Optional parent ``api_endpoint`` + override inherited when both ``api_endpoint`` and ``universe_domain`` + are unset on ``client_options``. If ``None``, no endpoint is inherited. + clear_credentials (bool): Whether to clear ``credentials_file`` and + ``api_key`` on the returned copy to avoid duplicate-credential errors. + + Returns: + Optional[google.api_core.client_options.ClientOptions]: Updated + ``ClientOptions`` instance (never mutating caller inputs), or ``None`` + when ``client_options`` is ``None`` and default resolution already + matches the parent. + + Raises: + TypeError: If ``client_options`` is not a ``ClientOptions`` instance, + ``Mapping``, or ``None``. + """ + env_universe = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + should_propagate = parent_universe != _DEFAULT_UNIVERSE or ( + env_universe is not None and env_universe.strip() != parent_universe + ) + has_parent_endpoint = bool(parent_api_endpoint) + if client_options is None: + if should_propagate or has_parent_endpoint: + return client_options_lib.ClientOptions( + api_endpoint=parent_api_endpoint if has_parent_endpoint else None, + universe_domain=parent_universe if should_propagate else None, + ) + return None + if isinstance(client_options, Mapping): + opts = client_options_lib.from_dict(client_options) + is_fresh_copy = True + elif isinstance(client_options, client_options_lib.ClientOptions): + opts = client_options + is_fresh_copy = False + else: + raise TypeError( + "client_options must be a ClientOptions instance, Mapping, or None; " + f"got {type(client_options).__name__}" + ) + opts_universe = getattr(opts, "universe_domain", None) + needs_universe = opts_universe is None and should_propagate + needs_endpoint = ( + has_parent_endpoint + and not opts.api_endpoint + and opts_universe is None + ) + needs_cred_clear = clear_credentials and bool( + getattr(opts, "credentials_file", None) + or getattr(opts, "api_key", None) + ) + if needs_universe or needs_endpoint or needs_cred_clear: + if not is_fresh_copy: + opts = copy.copy(opts) + if needs_universe: + opts.universe_domain = parent_universe + if needs_endpoint: + opts.api_endpoint = parent_api_endpoint + if needs_cred_clear: + opts.credentials_file = None + opts.api_key = None + return opts +{% endif %} class {{ service.name }}Transport(abc.ABC): 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 5332ca576180..e0835d639e6e 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 @@ -8,6 +8,9 @@ import os import asyncio +{% if service.any_extended_operations_methods %} +import copy +{% endif %} {% if has_auto_populated_fields %} import re {% endif %} @@ -64,6 +67,9 @@ from {{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + ser from {{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + service.meta.address.subpackage)|join(".") }}.services.{{ service.name|snake_case }} import {{ service.async_client_name }} {% endif %} from {{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + service.meta.address.subpackage)|join(".") }}.services.{{ service.name|snake_case }} import transports +{% if service.any_extended_operations_methods %} +from {{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + service.meta.address.subpackage)|join(".") }}.services.{{ service.name|snake_case }}.transports.base import _inherit_universe_in_client_options +{% endif %} from {{ (api.naming.module_namespace + (api.naming.versioned_module_name,) + service.meta.address.subpackage)|join(".") }}.services.{{ service.name|snake_case }}.client import _observability from google.api_core import client_options @@ -3547,6 +3553,325 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service assert op_client.api_endpoint == {{ op_tpclp_endpoint }} assert op_client._client_options.api_key is None {% endfor %} + + +EXTENDED_OPS_CHILD_UNIVERSE = "child.goog" +EXTENDED_OPS_PARENT_ENDPOINT = "custom.endpoint:443" +EXTENDED_OPS_CHILD_ENDPOINT = "child.endpoint:443" +EXTENDED_OPS_QUOTA_PROJECT_ID = "qp-1" + + +@pytest.mark.parametrize( + ( + "parent_universe", + "options_input", + "parent_api_endpoint", + "clear_credentials", + "expected", + ), + [ + pytest.param( + EXTENDED_OPS_DEFAULT_UNIVERSE, + None, + EXTENDED_OPS_PARENT_ENDPOINT, + False, + {"api_endpoint": EXTENDED_OPS_PARENT_ENDPOINT}, + id="none_gdu_with_parent_endpoint_only", + ), + pytest.param( + EXTENDED_OPS_CUSTOM_UNIVERSE, + None, + "", + False, + {"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + id="none_custom_universe_with_empty_parent_endpoint", + ), + pytest.param( + EXTENDED_OPS_CUSTOM_UNIVERSE, + None, + EXTENDED_OPS_PARENT_ENDPOINT, + False, + { + "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, + "api_endpoint": EXTENDED_OPS_PARENT_ENDPOINT, + }, + id="none_inherits_universe_and_endpoint", + ), + pytest.param( + EXTENDED_OPS_DEFAULT_UNIVERSE, + {}, + None, + False, + {}, + id="empty_mapping_gdu_leaves_universe_unset", + ), + pytest.param( + EXTENDED_OPS_CUSTOM_UNIVERSE, + { + "quota_project_id": EXTENDED_OPS_QUOTA_PROJECT_ID, + "api_key": EXTENDED_OPS_TPC_API_KEY, + }, + EXTENDED_OPS_PARENT_ENDPOINT, + True, + { + "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, + "api_endpoint": EXTENDED_OPS_PARENT_ENDPOINT, + "quota_project_id": EXTENDED_OPS_QUOTA_PROJECT_ID, + }, + id="mapping_inherits_and_clears_api_key", + ), + pytest.param( + EXTENDED_OPS_CUSTOM_UNIVERSE, + { + "quota_project_id": EXTENDED_OPS_QUOTA_PROJECT_ID, + "credentials_file": EXTENDED_OPS_CREDENTIALS_FILE, + }, + EXTENDED_OPS_PARENT_ENDPOINT, + True, + { + "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, + "api_endpoint": EXTENDED_OPS_PARENT_ENDPOINT, + "quota_project_id": EXTENDED_OPS_QUOTA_PROJECT_ID, + }, + id="mapping_inherits_and_clears_credentials_file", + ), + pytest.param( + EXTENDED_OPS_CUSTOM_UNIVERSE, + { + "api_endpoint": EXTENDED_OPS_CHILD_ENDPOINT, + "api_key": EXTENDED_OPS_TPC_API_KEY, + }, + EXTENDED_OPS_PARENT_ENDPOINT, + False, + { + "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, + "api_endpoint": EXTENDED_OPS_CHILD_ENDPOINT, + "api_key": EXTENDED_OPS_TPC_API_KEY, + }, + id="mapping_child_endpoint_preserved_without_cred_clear", + ), + pytest.param( + EXTENDED_OPS_DEFAULT_UNIVERSE, + { + "universe_domain": EXTENDED_OPS_CHILD_UNIVERSE, + "api_key": EXTENDED_OPS_TPC_API_KEY, + }, + EXTENDED_OPS_PARENT_ENDPOINT, + False, + { + "universe_domain": EXTENDED_OPS_CHILD_UNIVERSE, + "api_key": EXTENDED_OPS_TPC_API_KEY, + }, + id="mapping_child_universe_blocks_parent_endpoint", + ), + pytest.param( + EXTENDED_OPS_DEFAULT_UNIVERSE, + client_options.ClientOptions( + quota_project_id=EXTENDED_OPS_QUOTA_PROJECT_ID, + ), + EXTENDED_OPS_PARENT_ENDPOINT, + False, + { + "api_endpoint": EXTENDED_OPS_PARENT_ENDPOINT, + "quota_project_id": EXTENDED_OPS_QUOTA_PROJECT_ID, + }, + id="client_options_gdu_inherits_endpoint_only", + ), + pytest.param( + EXTENDED_OPS_CUSTOM_UNIVERSE, + client_options.ClientOptions( + api_endpoint=EXTENDED_OPS_CHILD_ENDPOINT, + api_key=EXTENDED_OPS_TPC_API_KEY, + ), + EXTENDED_OPS_PARENT_ENDPOINT, + False, + { + "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, + "api_endpoint": EXTENDED_OPS_CHILD_ENDPOINT, + "api_key": EXTENDED_OPS_TPC_API_KEY, + }, + id="client_options_preserves_child_endpoint_and_credentials", + ), + pytest.param( + EXTENDED_OPS_CUSTOM_UNIVERSE, + client_options.ClientOptions(api_key=EXTENDED_OPS_TPC_API_KEY), + EXTENDED_OPS_PARENT_ENDPOINT, + True, + { + "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, + "api_endpoint": EXTENDED_OPS_PARENT_ENDPOINT, + }, + id="client_options_inherits_and_clears_api_key", + ), + pytest.param( + EXTENDED_OPS_CUSTOM_UNIVERSE, + client_options.ClientOptions( + credentials_file=EXTENDED_OPS_CREDENTIALS_FILE + ), + EXTENDED_OPS_PARENT_ENDPOINT, + True, + { + "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, + "api_endpoint": EXTENDED_OPS_PARENT_ENDPOINT, + }, + id="client_options_inherits_and_clears_credentials_file", + ), + pytest.param( + EXTENDED_OPS_CUSTOM_UNIVERSE, + client_options.ClientOptions( + universe_domain=EXTENDED_OPS_CHILD_UNIVERSE, + api_key=EXTENDED_OPS_TPC_API_KEY, + ), + EXTENDED_OPS_PARENT_ENDPOINT, + True, + {"universe_domain": EXTENDED_OPS_CHILD_UNIVERSE}, + id="client_options_child_universe_blocks_parent_endpoint", + ), + ], +) +def test_{{ service.name|snake_case }}_inherit_universe_in_client_options_propagates_options( + clean_universe_env, + parent_universe, + options_input, + parent_api_endpoint, + clear_credentials, + expected, +): + options = copy.deepcopy(options_input) + + inherited = _inherit_universe_in_client_options( + parent_universe, + options, + parent_api_endpoint=parent_api_endpoint, + clear_credentials=clear_credentials, + ) + + assert inherited is not None + assert inherited.universe_domain == expected.get("universe_domain") + assert inherited.api_endpoint == expected.get("api_endpoint") + assert inherited.api_key == expected.get("api_key") + assert inherited.credentials_file == expected.get("credentials_file") + assert inherited.quota_project_id == expected.get("quota_project_id") + + +@pytest.mark.parametrize( + "parent_endpoint", + [ + pytest.param(None, id="none_parent_endpoint"), + pytest.param("", id="empty_parent_endpoint"), + ], +) +def test_{{ service.name|snake_case }}_inherit_universe_in_client_options_gdu_none_returns_none( + clean_universe_env, parent_endpoint +): + inherited = _inherit_universe_in_client_options( + EXTENDED_OPS_DEFAULT_UNIVERSE, + None, + parent_api_endpoint=parent_endpoint, + ) + + assert inherited is None + + +@pytest.mark.parametrize( + "clear_credentials", + [ + pytest.param(False, id="keep_credentials"), + pytest.param(True, id="clear_credentials_noop"), + ], +) +def test_{{ service.name|snake_case }}_inherit_universe_in_client_options_unchanged_returns_same_instance( + clean_universe_env, clear_credentials +): + unchanged_opts = client_options.ClientOptions( + quota_project_id=EXTENDED_OPS_QUOTA_PROJECT_ID + ) + + inherited = _inherit_universe_in_client_options( + EXTENDED_OPS_DEFAULT_UNIVERSE, + unchanged_opts, + clear_credentials=clear_credentials, + ) + + assert inherited is unchanged_opts + + +def test_{{ service.name|snake_case }}_inherit_universe_in_client_options_preserves_caller_inputs( + clean_universe_env, +): + raw_dict = { + "quota_project_id": EXTENDED_OPS_QUOTA_PROJECT_ID, + "api_key": EXTENDED_OPS_TPC_API_KEY, + } + parent_opts = client_options.ClientOptions( + credentials_file=EXTENDED_OPS_CREDENTIALS_FILE, + ) + + inherited_from_dict = _inherit_universe_in_client_options( + EXTENDED_OPS_CUSTOM_UNIVERSE, raw_dict, clear_credentials=True + ) + inherited_from_opts = _inherit_universe_in_client_options( + EXTENDED_OPS_CUSTOM_UNIVERSE, parent_opts, clear_credentials=True + ) + + assert raw_dict == { + "quota_project_id": EXTENDED_OPS_QUOTA_PROJECT_ID, + "api_key": EXTENDED_OPS_TPC_API_KEY, + } + assert inherited_from_dict.api_key is None + assert inherited_from_opts is not parent_opts + assert parent_opts.credentials_file == EXTENDED_OPS_CREDENTIALS_FILE + assert inherited_from_opts.credentials_file is None + + +@pytest.mark.parametrize( + "env_value,expected_universe", + [ + pytest.param(" googleapis.com ", None, id="whitespace_padded_gdu"), + pytest.param( + EXTENDED_OPS_CUSTOM_UNIVERSE, + EXTENDED_OPS_DEFAULT_UNIVERSE, + id="tpc_env_requires_explicit_gdu", + ), + pytest.param( + "", + EXTENDED_OPS_DEFAULT_UNIVERSE, + id="empty_env_requires_explicit_gdu", + ), + pytest.param( + " ", + EXTENDED_OPS_DEFAULT_UNIVERSE, + id="whitespace_env_requires_explicit_gdu", + ), + ], +) +def test_{{ service.name|snake_case }}_inherit_universe_in_client_options_env_override_and_whitespace( + clean_universe_env, env_value, expected_universe +): + clean_universe_env.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", env_value) + + inherited = _inherit_universe_in_client_options( + EXTENDED_OPS_DEFAULT_UNIVERSE, None + ) + + if expected_universe is None: + assert inherited is None + else: + assert inherited is not None + assert inherited.universe_domain == expected_universe + assert inherited.api_endpoint is None + + +def test_{{ service.name|snake_case }}_inherit_universe_in_client_options_invalid_type_raises( + clean_universe_env, +): + with pytest.raises( + TypeError, + match=r"ClientOptions instance, Mapping, or None; got str", + ): + _inherit_universe_in_client_options( + EXTENDED_OPS_DEFAULT_UNIVERSE, "invalid" # type: ignore[arg-type] + ) {% endif %} {% endblock %} diff --git a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 index bd57cc28ec79..dca023a9bcd7 100644 --- a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 +++ b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 @@ -3,7 +3,6 @@ {% block content %} {% set has_auto_populated_fields = api.all_method_settings.values()|map(attribute="auto_populated_fields", default=[])|select|list %} -{% set has_extended_operations = api.services.values()|selectattr("any_extended_operations_methods")|list|length > 0 %} """Tests for the compatibility module for older versions of google-api-core.""" {# TODO(https://github.com/googleapis/google-cloud-python/issues/17813): Clean up this file/tests when the minimum supported version of @@ -11,10 +10,6 @@ google-api-core has the functions in `_compat.py.j2`. #} {# TODO(https://github.com/googleapis/google-cloud-python/issues/17883): Backfill compatibility functions tests being removed from the client layer. #} -{% if has_extended_operations %} -import copy -import importlib -{% endif %} import json import pytest import os @@ -42,12 +37,6 @@ from {{package_path}}._compat import ( {% if has_auto_populated_fields %} from {{package_path}}._compat import setup_request_id {% endif %} -{% if has_extended_operations %} -from google.api_core import client_options as client_options_lib -import google.api_core.universe -from {{package_path}} import _compat -from {{package_path}}._compat import inherit_universe_in_client_options -{% endif %} from google.auth.exceptions import MutualTLSChannelError from google.api_core.universe import EmptyUniverseError @@ -620,347 +609,5 @@ def test_apply_async_channel_interceptors_compat(): dummy_channel = mock.Mock() result = apply_async_channel_interceptors(dummy_channel, None) assert result is dummy_channel -{% if has_extended_operations %} - - -COMPAT_DEFAULT_UNIVERSE = "googleapis.com" -COMPAT_CUSTOM_UNIVERSE = "apis-tpclp.goog" -COMPAT_CHILD_UNIVERSE = "child.goog" -COMPAT_PARENT_ENDPOINT = "custom.endpoint:443" -COMPAT_CHILD_ENDPOINT = "child.endpoint:443" -COMPAT_API_KEY = "secret" -COMPAT_CREDENTIALS_FILE = "creds.json" -COMPAT_QUOTA_PROJECT_ID = "qp-1" - - -@pytest.fixture -def fallback_inherit_universe(monkeypatch): - monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) - monkeypatch.delattr( - google.api_core.universe, - "inherit_universe_in_client_options", - raising=False, - ) - reloaded = importlib.reload(_compat) - try: - yield reloaded.inherit_universe_in_client_options - finally: - monkeypatch.undo() - importlib.reload(_compat) - - -def test_inherit_universe_in_client_options_compat_reexport(monkeypatch): - assert callable(inherit_universe_in_client_options) - sentinel = object() - monkeypatch.setattr( - google.api_core.universe, - "inherit_universe_in_client_options", - sentinel, - raising=False, - ) - reloaded = importlib.reload(_compat) - try: - assert reloaded.inherit_universe_in_client_options is sentinel - finally: - monkeypatch.undo() - importlib.reload(_compat) - - -@pytest.mark.parametrize( - ( - "parent_universe", - "client_options", - "parent_api_endpoint", - "clear_credentials", - "expected", - ), - [ - pytest.param( - COMPAT_DEFAULT_UNIVERSE, - None, - COMPAT_PARENT_ENDPOINT, - False, - {"api_endpoint": COMPAT_PARENT_ENDPOINT}, - id="none_gdu_with_parent_endpoint_only", - ), - pytest.param( - COMPAT_CUSTOM_UNIVERSE, - None, - "", - False, - {"universe_domain": COMPAT_CUSTOM_UNIVERSE}, - id="none_custom_universe_with_empty_parent_endpoint", - ), - pytest.param( - COMPAT_CUSTOM_UNIVERSE, - None, - COMPAT_PARENT_ENDPOINT, - False, - { - "universe_domain": COMPAT_CUSTOM_UNIVERSE, - "api_endpoint": COMPAT_PARENT_ENDPOINT, - }, - id="none_inherits_universe_and_endpoint", - ), - pytest.param( - COMPAT_DEFAULT_UNIVERSE, - {}, - None, - False, - {}, - id="empty_mapping_gdu_leaves_universe_unset", - ), - pytest.param( - COMPAT_CUSTOM_UNIVERSE, - { - "quota_project_id": COMPAT_QUOTA_PROJECT_ID, - "api_key": COMPAT_API_KEY, - }, - COMPAT_PARENT_ENDPOINT, - True, - { - "universe_domain": COMPAT_CUSTOM_UNIVERSE, - "api_endpoint": COMPAT_PARENT_ENDPOINT, - "quota_project_id": COMPAT_QUOTA_PROJECT_ID, - }, - id="mapping_inherits_and_clears_api_key", - ), - pytest.param( - COMPAT_CUSTOM_UNIVERSE, - { - "quota_project_id": COMPAT_QUOTA_PROJECT_ID, - "credentials_file": COMPAT_CREDENTIALS_FILE, - }, - COMPAT_PARENT_ENDPOINT, - True, - { - "universe_domain": COMPAT_CUSTOM_UNIVERSE, - "api_endpoint": COMPAT_PARENT_ENDPOINT, - "quota_project_id": COMPAT_QUOTA_PROJECT_ID, - }, - id="mapping_inherits_and_clears_credentials_file", - ), - pytest.param( - COMPAT_CUSTOM_UNIVERSE, - {"api_endpoint": COMPAT_CHILD_ENDPOINT, "api_key": COMPAT_API_KEY}, - COMPAT_PARENT_ENDPOINT, - False, - { - "universe_domain": COMPAT_CUSTOM_UNIVERSE, - "api_endpoint": COMPAT_CHILD_ENDPOINT, - "api_key": COMPAT_API_KEY, - }, - id="mapping_child_endpoint_preserved_without_cred_clear", - ), - pytest.param( - COMPAT_DEFAULT_UNIVERSE, - {"universe_domain": COMPAT_CHILD_UNIVERSE, "api_key": COMPAT_API_KEY}, - COMPAT_PARENT_ENDPOINT, - False, - { - "universe_domain": COMPAT_CHILD_UNIVERSE, - "api_key": COMPAT_API_KEY, - }, - id="mapping_child_universe_blocks_parent_endpoint", - ), - pytest.param( - COMPAT_DEFAULT_UNIVERSE, - client_options_lib.ClientOptions( - quota_project_id=COMPAT_QUOTA_PROJECT_ID, - ), - COMPAT_PARENT_ENDPOINT, - False, - { - "api_endpoint": COMPAT_PARENT_ENDPOINT, - "quota_project_id": COMPAT_QUOTA_PROJECT_ID, - }, - id="client_options_gdu_inherits_endpoint_only", - ), - pytest.param( - COMPAT_CUSTOM_UNIVERSE, - client_options_lib.ClientOptions( - api_endpoint=COMPAT_CHILD_ENDPOINT, - api_key=COMPAT_API_KEY, - ), - COMPAT_PARENT_ENDPOINT, - False, - { - "universe_domain": COMPAT_CUSTOM_UNIVERSE, - "api_endpoint": COMPAT_CHILD_ENDPOINT, - "api_key": COMPAT_API_KEY, - }, - id="client_options_preserves_child_endpoint_and_credentials", - ), - pytest.param( - COMPAT_CUSTOM_UNIVERSE, - client_options_lib.ClientOptions(api_key=COMPAT_API_KEY), - COMPAT_PARENT_ENDPOINT, - True, - { - "universe_domain": COMPAT_CUSTOM_UNIVERSE, - "api_endpoint": COMPAT_PARENT_ENDPOINT, - }, - id="client_options_inherits_and_clears_api_key", - ), - pytest.param( - COMPAT_CUSTOM_UNIVERSE, - client_options_lib.ClientOptions( - credentials_file=COMPAT_CREDENTIALS_FILE - ), - COMPAT_PARENT_ENDPOINT, - True, - { - "universe_domain": COMPAT_CUSTOM_UNIVERSE, - "api_endpoint": COMPAT_PARENT_ENDPOINT, - }, - id="client_options_inherits_and_clears_credentials_file", - ), - pytest.param( - COMPAT_CUSTOM_UNIVERSE, - client_options_lib.ClientOptions( - universe_domain=COMPAT_CHILD_UNIVERSE, - api_key=COMPAT_API_KEY, - ), - COMPAT_PARENT_ENDPOINT, - True, - {"universe_domain": COMPAT_CHILD_UNIVERSE}, - id="client_options_child_universe_blocks_parent_endpoint", - ), - ], -) -def test_inherit_universe_in_client_options_compat_propagates_options( - fallback_inherit_universe, - parent_universe, - client_options, - parent_api_endpoint, - clear_credentials, - expected, -): - options = copy.deepcopy(client_options) - - inherited = fallback_inherit_universe( - parent_universe, - options, - parent_api_endpoint=parent_api_endpoint, - clear_credentials=clear_credentials, - ) - - assert inherited is not None - assert inherited.universe_domain == expected.get("universe_domain") - assert inherited.api_endpoint == expected.get("api_endpoint") - assert inherited.api_key == expected.get("api_key") - assert inherited.credentials_file == expected.get("credentials_file") - assert inherited.quota_project_id == expected.get("quota_project_id") - - -@pytest.mark.parametrize( - "parent_endpoint", - [ - pytest.param(None, id="none_parent_endpoint"), - pytest.param("", id="empty_parent_endpoint"), - ], -) -def test_inherit_universe_in_client_options_compat_gdu_none_returns_none( - fallback_inherit_universe, parent_endpoint -): - inherited = fallback_inherit_universe( - COMPAT_DEFAULT_UNIVERSE, None, parent_api_endpoint=parent_endpoint - ) - - assert inherited is None - - -@pytest.mark.parametrize( - "clear_credentials", - [ - pytest.param(False, id="keep_credentials"), - pytest.param(True, id="clear_credentials_noop"), - ], -) -def test_inherit_universe_in_client_options_compat_unchanged_returns_same_instance( - fallback_inherit_universe, clear_credentials -): - unchanged_opts = client_options_lib.ClientOptions( - quota_project_id=COMPAT_QUOTA_PROJECT_ID - ) - - inherited = fallback_inherit_universe( - COMPAT_DEFAULT_UNIVERSE, - unchanged_opts, - clear_credentials=clear_credentials, - ) - - assert inherited is unchanged_opts - - -def test_inherit_universe_in_client_options_compat_preserves_caller_inputs( - fallback_inherit_universe, -): - raw_dict = { - "quota_project_id": COMPAT_QUOTA_PROJECT_ID, - "api_key": COMPAT_API_KEY, - } - parent_opts = client_options_lib.ClientOptions( - credentials_file=COMPAT_CREDENTIALS_FILE, - ) - - inherited_from_dict = fallback_inherit_universe( - COMPAT_CUSTOM_UNIVERSE, raw_dict, clear_credentials=True - ) - inherited_from_opts = fallback_inherit_universe( - COMPAT_CUSTOM_UNIVERSE, parent_opts, clear_credentials=True - ) - - assert raw_dict == { - "quota_project_id": COMPAT_QUOTA_PROJECT_ID, - "api_key": COMPAT_API_KEY, - } - assert inherited_from_dict.api_key is None - assert inherited_from_opts is not parent_opts - assert parent_opts.credentials_file == COMPAT_CREDENTIALS_FILE - assert inherited_from_opts.credentials_file is None - - -@pytest.mark.parametrize( - "env_value,expected_universe", - [ - pytest.param(" googleapis.com ", None, id="whitespace_padded_gdu"), - pytest.param( - COMPAT_CUSTOM_UNIVERSE, - COMPAT_DEFAULT_UNIVERSE, - id="tpc_env_requires_explicit_gdu", - ), - pytest.param("", COMPAT_DEFAULT_UNIVERSE, id="empty_env_requires_explicit_gdu"), - pytest.param( - " ", - COMPAT_DEFAULT_UNIVERSE, - id="whitespace_env_requires_explicit_gdu", - ), - ], -) -def test_inherit_universe_in_client_options_compat_env_override_and_whitespace( - fallback_inherit_universe, monkeypatch, env_value, expected_universe -): - monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", env_value) - - inherited = fallback_inherit_universe(COMPAT_DEFAULT_UNIVERSE, None) - - if expected_universe is None: - assert inherited is None - else: - assert inherited is not None - assert inherited.universe_domain == expected_universe - assert inherited.api_endpoint is None - - -def test_inherit_universe_in_client_options_compat_invalid_type_raises( - fallback_inherit_universe, -): - with pytest.raises( - TypeError, - match=r"ClientOptions instance, Mapping, or None; got str", - ): - fallback_inherit_universe(COMPAT_DEFAULT_UNIVERSE, "invalid") # type: ignore[arg-type] -{% endif %} {% endblock %} From a47519646028e4bd615cfb194063e4a01015177b Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Tue, 1 Dec 2026 13:38:04 -0500 Subject: [PATCH 5/5] refactor(gapic-generator): keep generated extended-ops tests lean and move exhaustive helper matrix to generator unit tests --- .../%name_%version/%sub/test_%service.py.j2 | 945 +++--------------- .../generator/test_extended_ops_universe.py | 394 ++++++++ 2 files changed, 517 insertions(+), 822 deletions(-) create mode 100644 packages/gapic-generator/tests/unit/generator/test_extended_ops_universe.py 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 e0835d639e6e..ff97fc9351fe 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 @@ -8,9 +8,6 @@ import os import asyncio -{% if service.any_extended_operations_methods %} -import copy -{% endif %} {% if has_auto_populated_fields %} import re {% endif %} @@ -2870,13 +2867,10 @@ def test_{{ service.name|snake_case }}_base_transport_wrap_async_method_older_ap EXTENDED_OPS_CUSTOM_UNIVERSE = "apis-tpclp.goog" EXTENDED_OPS_DEFAULT_UNIVERSE = "googleapis.com" -EXTENDED_OPS_CUSTOM_ENDPOINT = "custom.endpoint.test:443" EXTENDED_OPS_TRANSPORT_HOST = "custom.transport.test:443" EXTENDED_OPS_EXPLICIT_ENDPOINT = "explicit.options.test:443" EXTENDED_OPS_CREDENTIALS_FILE = "creds.json" -EXTENDED_OPS_GDU_API_KEY = "test-gdu-key" -EXTENDED_OPS_TPC_API_KEY = "test-api-key" -EXTENDED_OPS_IGNORED_CHANNEL_HOST = "ignored.channel.test:443" +EXTENDED_OPS_API_KEY = "test-api-key" @pytest.fixture @@ -2902,47 +2896,6 @@ def mock_default_credentials(): {% set op_prop = operations_service.client_name|snake_case|make_private %} {% set op_default_endpoint = '"' ~ operations_service.host ~ '"' if operations_service.host else 'None' %} {% set op_tpclp_endpoint = '"' ~ operations_service.host.replace("googleapis.com", "apis-tpclp.goog") ~ '"' if operations_service.host else 'None' %} -@pytest.mark.parametrize( - "transport_name", - [ - {% if 'grpc' in opts.transport %} - pytest.param("grpc", id="grpc"), - {% endif %} - {% if 'rest' in opts.transport %} - pytest.param("rest", id="rest"), - {% endif %} - ], -) -def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_client_options_object_propagation( - clean_universe_env, transport_name -): - options = client_options.ClientOptions( - universe_domain=EXTENDED_OPS_CUSTOM_UNIVERSE, - quota_project_id="qp-ext", - api_audience="https://custom.aud/", - scopes=["https://www.googleapis.com/auth/cloud-platform"], - ) - creds = ga_credentials.AnonymousCredentials() - - client = {{ service.client_name }}( - credentials=creds, - transport=transport_name, - client_options=options, - ) - op_client = client.transport.{{ op_prop }} - - assert client.transport.{{ op_prop }} is op_client - assert op_client._transport._credentials is creds - assert op_client.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE - assert op_client.api_endpoint == {{ op_tpclp_endpoint }} - assert op_client._client_options.quota_project_id == "qp-ext" - assert op_client._client_options.api_audience == "https://custom.aud/" - assert op_client._client_options.scopes == [ - "https://www.googleapis.com/auth/cloud-platform" - ] - assert options.api_endpoint is None - - @pytest.mark.parametrize( "transport_name", [ @@ -2955,123 +2908,64 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service ], ) @pytest.mark.parametrize( - "raw_options,expected_universe,expected_endpoint", + "env_value,raw_options,expected_universe,expected_endpoint", [ pytest.param( - {"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + None, + client_options.ClientOptions( + universe_domain=EXTENDED_OPS_CUSTOM_UNIVERSE, + quota_project_id="qp-ext", + ), EXTENDED_OPS_CUSTOM_UNIVERSE, {{ op_tpclp_endpoint }}, - id="dict_universe_domain", + id="client_options_tpc", ), pytest.param( - {"api_endpoint": EXTENDED_OPS_CUSTOM_ENDPOINT}, + None, + {"api_endpoint": EXTENDED_OPS_EXPLICIT_ENDPOINT}, EXTENDED_OPS_DEFAULT_UNIVERSE, - EXTENDED_OPS_CUSTOM_ENDPOINT, + EXTENDED_OPS_EXPLICIT_ENDPOINT, id="dict_endpoint_only", ), - ], -) -def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_dict_client_options_propagation( - clean_universe_env, - transport_name, - raw_options, - expected_universe, - expected_endpoint, -): - options_dict = dict(raw_options) - - client = {{ service.client_name }}( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - client_options=options_dict, - ) - op_client = client.transport.{{ op_prop }} - - assert op_client.universe_domain == expected_universe - assert op_client.api_endpoint == expected_endpoint - assert options_dict == raw_options - - -@pytest.mark.parametrize( - "transport_name", - [ - {% if 'grpc' in opts.transport %} - pytest.param("grpc", id="grpc"), - {% endif %} - {% if 'rest' in opts.transport %} - pytest.param("rest", id="rest"), - {% endif %} - ], -) -def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_env_universe_bound_at_parent_init( - clean_universe_env, transport_name -): - clean_universe_env.setenv( - "GOOGLE_CLOUD_UNIVERSE_DOMAIN", EXTENDED_OPS_CUSTOM_UNIVERSE - ) - - client_env = {{ service.client_name }}( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - clean_universe_env.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) - op_env = client_env.transport.{{ op_prop }} - - assert op_env.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE - assert op_env.api_endpoint == {{ op_tpclp_endpoint }} - - -@pytest.mark.parametrize( - "transport_name", - [ - {% if 'grpc' in opts.transport %} - pytest.param("grpc", id="grpc"), - {% endif %} - {% if 'rest' in opts.transport %} - pytest.param("rest", id="rest"), - {% endif %} - ], -) -@pytest.mark.parametrize( - "env_value,explicit_universe,expected_endpoint", - [ pytest.param( EXTENDED_OPS_CUSTOM_UNIVERSE, - EXTENDED_OPS_DEFAULT_UNIVERSE, - {{ op_default_endpoint }}, - id="explicit_gdu_overrides_tpc_env", - ), - pytest.param( - "", + None, EXTENDED_OPS_CUSTOM_UNIVERSE, {{ op_tpclp_endpoint }}, - id="explicit_tpc_overrides_empty_env", + id="env_universe_bound_at_init", ), pytest.param( - " ", + "", + {"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, EXTENDED_OPS_CUSTOM_UNIVERSE, {{ op_tpclp_endpoint }}, - id="explicit_tpc_overrides_whitespace_env", + id="explicit_tpc_overrides_empty_env", ), ], ) -def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_explicit_universe_overrides_env( +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_client_options_propagation( clean_universe_env, transport_name, env_value, - explicit_universe, + raw_options, + expected_universe, expected_endpoint, ): - clean_universe_env.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", env_value) + if env_value is not None: + clean_universe_env.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", env_value) + creds = ga_credentials.AnonymousCredentials() client = {{ service.client_name }}( - credentials=ga_credentials.AnonymousCredentials(), + credentials=creds, transport=transport_name, - client_options={"universe_domain": explicit_universe}, + client_options=raw_options, ) + clean_universe_env.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) op_client = client.transport.{{ op_prop }} - assert op_client.universe_domain == explicit_universe + assert client.transport.{{ op_prop }} is op_client + assert op_client._transport._credentials is creds + assert op_client.universe_domain == expected_universe assert op_client.api_endpoint == expected_endpoint @@ -3086,55 +2980,14 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service {% endif %} ], ) -@pytest.mark.parametrize( - "bad_universe", - [ - pytest.param("", id="empty_string"), - pytest.param(" ", id="whitespace_only"), - ], -) -def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_empty_universe_raises( - clean_universe_env, transport_name, bad_universe -): - transport_cls = {{ service.client_name }}.get_transport_class(transport_name) - - with pytest.raises( - EmptyUniverseError, - match=r"^Universe Domain cannot be an empty string\.$", - ): - {{ service.client_name }}( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - client_options={"universe_domain": bad_universe}, - ) - with pytest.raises( - EmptyUniverseError, - match=r"^Universe Domain cannot be an empty string\.$", - ): - transport_cls( - credentials=ga_credentials.AnonymousCredentials(), - client_options={"universe_domain": bad_universe}, - ) - - -@pytest.mark.parametrize( - "transport_name", - [ - {% if 'grpc' in opts.transport %} - pytest.param("grpc", id="grpc"), - {% endif %} - {% if 'rest' in opts.transport %} - pytest.param("rest", id="rest"), - {% endif %} - ], -) -def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_clears_credentials_file( +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_clears_credentials_and_api_key( clean_universe_env, mock_default_credentials, transport_name ): file_opts = client_options.ClientOptions( credentials_file=EXTENDED_OPS_CREDENTIALS_FILE, universe_domain=EXTENDED_OPS_CUSTOM_UNIVERSE, ) + key_opts = {"api_key": EXTENDED_OPS_API_KEY, "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE} with mock.patch.object( google.auth, @@ -3143,72 +2996,17 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service spec_set=True, return_value=(ga_credentials.AnonymousCredentials(), None), ): - client_from_file = {{ service.client_name }}( - transport=transport_name, - client_options=file_opts, + client_file = {{ service.client_name }}( + transport=transport_name, client_options=file_opts ) - op_from_file = client_from_file.transport.{{ op_prop }} - - assert op_from_file.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE - assert op_from_file._client_options.credentials_file is None - assert file_opts.credentials_file == EXTENDED_OPS_CREDENTIALS_FILE - - -@pytest.mark.parametrize( - "transport_name", - [ - {% if 'grpc' in opts.transport %} - pytest.param("grpc", id="grpc"), - {% endif %} - {% if 'rest' in opts.transport %} - pytest.param("rest", id="rest"), - {% endif %} - ], -) -@pytest.mark.parametrize( - "options_factory,expected_universe,expected_original_key", - [ - pytest.param( - lambda: client_options.ClientOptions(api_key=EXTENDED_OPS_GDU_API_KEY), - EXTENDED_OPS_DEFAULT_UNIVERSE, - EXTENDED_OPS_GDU_API_KEY, - id="gdu_client_options", - ), - pytest.param( - lambda: { - "api_key": EXTENDED_OPS_TPC_API_KEY, - "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, - }, - EXTENDED_OPS_CUSTOM_UNIVERSE, - EXTENDED_OPS_TPC_API_KEY, - id="tpc_dict", - ), - ], -) -def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_clears_api_key( - clean_universe_env, - mock_default_credentials, - transport_name, - options_factory, - expected_universe, - expected_original_key, -): - # mock_default_credentials also guards google-auth < 2.16.0 lowest-constraints - # runs where google.auth._default.get_api_key_credentials is not yet available. - opts = options_factory() - - client = {{ service.client_name }}( - transport=transport_name, - client_options=opts, + client_key = {{ service.client_name }}( + transport=transport_name, client_options=key_opts ) - op_client = client.transport.{{ op_prop }} - assert op_client.universe_domain == expected_universe - assert op_client._client_options.api_key is None - if isinstance(opts, dict): - assert opts["api_key"] == expected_original_key - else: - assert opts.api_key == expected_original_key + assert client_file.transport.{{ op_prop }}._client_options.credentials_file is None + assert file_opts.credentials_file == EXTENDED_OPS_CREDENTIALS_FILE + assert client_key.transport.{{ op_prop }}._client_options.api_key is None + assert key_opts["api_key"] == EXTENDED_OPS_API_KEY @pytest.mark.parametrize( @@ -3222,73 +3020,50 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service {% endif %} ], ) -@pytest.mark.parametrize( - "host_fn,options_fn,expected_universe,expected_endpoint_fn", - [ - pytest.param( - lambda cls: EXTENDED_OPS_TRANSPORT_HOST, - lambda: {"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, - EXTENDED_OPS_CUSTOM_UNIVERSE, - lambda transport: transport.host, - id="custom_host_with_tpc_dict", - ), - pytest.param( - lambda cls: EXTENDED_OPS_TRANSPORT_HOST, - client_options.ClientOptions, - EXTENDED_OPS_DEFAULT_UNIVERSE, - lambda transport: transport.host, - id="custom_host_with_empty_client_options", - ), - pytest.param( - lambda cls: EXTENDED_OPS_TRANSPORT_HOST, - lambda: client_options.ClientOptions( - api_endpoint=EXTENDED_OPS_EXPLICIT_ENDPOINT - ), - EXTENDED_OPS_DEFAULT_UNIVERSE, - lambda transport: EXTENDED_OPS_EXPLICIT_ENDPOINT, - id="explicit_endpoint_overrides_transport_host", - ), - pytest.param( - lambda cls: f"https://{cls.DEFAULT_HOST}:443", - lambda: {"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, - EXTENDED_OPS_CUSTOM_UNIVERSE, - lambda transport: {{ op_tpclp_endpoint }}, - id="default_https_host_uses_tpc_endpoint", - ), - ], -) def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_direct_transport_options( - clean_universe_env, - transport_class, - host_fn, - options_fn, - expected_universe, - expected_endpoint_fn, + clean_universe_env, transport_class ): - opts = options_fn() - started_without_endpoint = ( - isinstance(opts, client_options.ClientOptions) - and opts.api_endpoint is None + creds = ga_credentials.AnonymousCredentials() + t_custom = transport_class( + host=EXTENDED_OPS_TRANSPORT_HOST, + credentials=creds, + client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, ) - transport = transport_class( - host=host_fn(transport_class), - credentials=ga_credentials.AnonymousCredentials(), - client_options=opts, + t_empty = transport_class( + host=EXTENDED_OPS_TRANSPORT_HOST, + credentials=creds, + client_options=client_options.ClientOptions(), + ) + t_explicit = transport_class( + host=EXTENDED_OPS_TRANSPORT_HOST, + credentials=creds, + client_options=client_options.ClientOptions( + api_endpoint=EXTENDED_OPS_EXPLICIT_ENDPOINT + ), + ) + t_default_https = transport_class( + host=f"https://{transport_class.DEFAULT_HOST}:443", + credentials=creds, + client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, ) - op_client = transport.{{ op_prop }} - assert op_client.universe_domain == expected_universe - assert op_client.api_endpoint == expected_endpoint_fn(transport) - if started_without_endpoint: - assert opts.api_endpoint is None + assert t_custom.{{ op_prop }}.api_endpoint == t_custom.host + assert t_empty.{{ op_prop }}.api_endpoint == t_empty.host + assert t_explicit.{{ op_prop }}.api_endpoint == EXTENDED_OPS_EXPLICIT_ENDPOINT + assert t_default_https.{{ op_prop }}.api_endpoint == {{ op_tpclp_endpoint }} + + clean_universe_env.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", "") + t_blank_env = transport_class(credentials=creds) + with pytest.raises(EmptyUniverseError): + _ = t_blank_env.{{ op_prop }} {% if 'grpc' in opts.transport %} -def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_direct_transport_user_channel_ignores_host( +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_direct_transport_user_channel( clean_universe_env, mock_default_credentials ): user_channel_transport = transports.{{ service.grpc_transport_name }}( - host=EXTENDED_OPS_IGNORED_CHANNEL_HOST, + host="ignored.channel.test:443", channel=mock.create_autospec(grpc.Channel, instance=True, spec_set=True), client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, ) @@ -3308,199 +3083,57 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service {% endif %} ], ) -def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_direct_transport_env_universe( - clean_universe_env, transport_class -): - clean_universe_env.setenv( - "GOOGLE_CLOUD_UNIVERSE_DOMAIN", EXTENDED_OPS_CUSTOM_UNIVERSE - ) - transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) - op_client = transport.{{ op_prop }} - - assert op_client.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE - assert op_client.api_endpoint == {{ op_tpclp_endpoint }} - - -@pytest.mark.parametrize( - "transport_class", - [ - {% if 'grpc' in opts.transport %} - pytest.param(transports.{{ service.grpc_transport_name }}, id="grpc"), - {% endif %} - {% if 'rest' in opts.transport %} - pytest.param(transports.{{ service.rest_transport_name }}, id="rest"), - {% endif %} - ], -) -@pytest.mark.parametrize( - "bad_env", - [ - pytest.param("", id="empty_env"), - pytest.param(" ", id="whitespace_env"), - ], -) -def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_direct_transport_blank_env_raises( - clean_universe_env, transport_class, bad_env -): - clean_universe_env.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", bad_env) - transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) - with pytest.raises( - EmptyUniverseError, - match=r"^Universe Domain cannot be an empty string\.$", - ): - _ = transport.{{ op_prop }} - - -@pytest.mark.parametrize( - "transport_class", - [ - {% if 'grpc' in opts.transport %} - pytest.param(transports.{{ service.grpc_transport_name }}, id="grpc"), - {% endif %} - {% if 'rest' in opts.transport %} - pytest.param(transports.{{ service.rest_transport_name }}, id="rest"), - {% endif %} - ], -) -def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_prebuilt_transport_reconfiguration( - clean_universe_env, transport_class +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_prebuilt_and_callable_transport( + clean_universe_env, mock_default_credentials, transport_class ): - prebuilt_transport = transport_class( - host=EXTENDED_OPS_TRANSPORT_HOST, - credentials=ga_credentials.AnonymousCredentials(), - ) - stale_op = prebuilt_transport.{{ op_prop }} - assert stale_op.universe_domain == EXTENDED_OPS_DEFAULT_UNIVERSE + creds = ga_credentials.AnonymousCredentials() + prebuilt = transport_class(host=EXTENDED_OPS_TRANSPORT_HOST, credentials=creds) + stale_op = prebuilt.{{ op_prop }} - client_with_override = {{ service.client_name }}( - transport=prebuilt_transport, + client_tpc = {{ service.client_name }}( + transport=prebuilt, client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, ) - op_prebuilt = client_with_override.transport.{{ op_prop }} + assert client_tpc.transport.{{ op_prop }} is not stale_op + assert client_tpc.transport.{{ op_prop }}.api_endpoint == prebuilt.host - assert op_prebuilt is not stale_op - assert op_prebuilt.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE - assert op_prebuilt.api_endpoint == prebuilt_transport.host - - gdu_endpoint_client = {{ service.client_name }}( - transport=prebuilt_transport, + client_gdu = {{ service.client_name }}( + transport=prebuilt, client_options={"api_endpoint": EXTENDED_OPS_EXPLICIT_ENDPOINT}, ) - op_gdu_endpoint = gdu_endpoint_client.transport.{{ op_prop }} - - assert op_gdu_endpoint is not op_prebuilt - assert op_gdu_endpoint.universe_domain == EXTENDED_OPS_DEFAULT_UNIVERSE - assert op_gdu_endpoint.api_endpoint == EXTENDED_OPS_EXPLICIT_ENDPOINT + assert client_gdu.transport.{{ op_prop }}.api_endpoint == EXTENDED_OPS_EXPLICIT_ENDPOINT - -@pytest.mark.parametrize( - "transport_class", - [ - {% if 'grpc' in opts.transport %} - pytest.param(transports.{{ service.grpc_transport_name }}, id="grpc"), - {% endif %} - {% if 'rest' in opts.transport %} - pytest.param(transports.{{ service.rest_transport_name }}, id="rest"), - {% endif %} - ], -) -@pytest.mark.parametrize( - "transport_kwargs,env_universe,expected_universe,expected_quota_project,expect_transport_host", - [ - pytest.param( - { - "client_options": { - "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, - "quota_project_id": "qp-gdu", - }, - }, - None, - EXTENDED_OPS_CUSTOM_UNIVERSE, - "qp-gdu", - False, - id="gdu_client_preserves_tpc_transport", - ), - pytest.param( - { - "client_options": { - "universe_domain": EXTENDED_OPS_DEFAULT_UNIVERSE, - "quota_project_id": "qp-transport", - }, - }, - EXTENDED_OPS_CUSTOM_UNIVERSE, - EXTENDED_OPS_DEFAULT_UNIVERSE, - "qp-transport", - False, - id="tpc_env_preserves_configured_transport", - ), - pytest.param( - {"host": EXTENDED_OPS_TRANSPORT_HOST}, - EXTENDED_OPS_CUSTOM_UNIVERSE, - EXTENDED_OPS_CUSTOM_UNIVERSE, - None, - True, - id="tpc_env_inherits_into_unconfigured_transport", - ), - ], -) -def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_prebuilt_transport_preserves_options( - clean_universe_env, - transport_class, - transport_kwargs, - env_universe, - expected_universe, - expected_quota_project, - expect_transport_host, -): - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - **transport_kwargs, + configured = transport_class( + credentials=creds, + client_options={"universe_domain": EXTENDED_OPS_DEFAULT_UNIVERSE}, ) - if env_universe is not None: - clean_universe_env.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", env_universe) - - client = {{ service.client_name }}(transport=transport) - op_client = client.transport.{{ op_prop }} - - assert op_client.universe_domain == expected_universe - if expected_quota_project is not None: - assert op_client._client_options.quota_project_id == expected_quota_project - if expect_transport_host: - assert op_client.api_endpoint == transport.host - - -@pytest.mark.parametrize( - "transport_class", - [ - {% if 'grpc' in opts.transport %} - pytest.param(transports.{{ service.grpc_transport_name }}, id="grpc"), - {% endif %} - {% if 'rest' in opts.transport %} - pytest.param(transports.{{ service.rest_transport_name }}, id="rest"), - {% endif %} - ], -) -def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_autospec_mock_transport( - clean_universe_env, transport_class -): - autospec_transport = mock.create_autospec( - transport_class, instance=True, spec_set=True + clean_universe_env.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", EXTENDED_OPS_CUSTOM_UNIVERSE) + assert ( + {{ service.client_name }}(transport=configured).transport.{{ op_prop }}.universe_domain + == EXTENDED_OPS_DEFAULT_UNIVERSE ) - autospec_transport.host = EXTENDED_OPS_TRANSPORT_HOST + clean_universe_env.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) + autospec_t = mock.create_autospec(transport_class, instance=True, spec_set=True) + autospec_t.host = EXTENDED_OPS_TRANSPORT_HOST {{ service.client_name }}( - transport=autospec_transport, + transport=autospec_t, client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, ) + autospec_t._configure_extended_operations_client_options.assert_called_once() - autospec_transport._configure_extended_operations_client_options.assert_called_once_with( - EXTENDED_OPS_CUSTOM_UNIVERSE, - {"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, - fallback_endpoint=None, + real_t = transport_class(credentials=creds) + callable_client = {{ service.client_name }}( + transport=lambda **kwargs: real_t, + client_options={ + "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, + "api_key": EXTENDED_OPS_API_KEY, + }, ) + assert callable_client.transport.{{ op_prop }}._client_options.api_key is None -def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_duck_typed_transport_ignored( +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_custom_transport_and_helper_boundaries( clean_universe_env, ): class CustomTransport(transports.{{ service.name }}Transport): @@ -3513,365 +3146,33 @@ def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service def kind(self) -> str: return "custom" - custom_transport = CustomTransport() - client = {{ service.client_name }}( - transport=custom_transport, - client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, - ) - - assert client.transport is custom_transport - - -@pytest.mark.parametrize( - "transport_class", - [ - {% if 'grpc' in opts.transport %} - pytest.param(transports.{{ service.grpc_transport_name }}, id="grpc"), - {% endif %} - {% if 'rest' in opts.transport %} - pytest.param(transports.{{ service.rest_transport_name }}, id="rest"), - {% endif %} - ], -) -def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_callable_transport( - clean_universe_env, mock_default_credentials, transport_class -): - real_transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() + custom_t = CustomTransport() + assert ( + {{ service.client_name }}( + transport=custom_t, + client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + ).transport + is custom_t ) - - client_with_callable = {{ service.client_name }}( - transport=lambda **kwargs: real_transport, - client_options={ - "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, - "api_key": EXTENDED_OPS_TPC_API_KEY, - }, + assert _inherit_universe_in_client_options(EXTENDED_OPS_DEFAULT_UNIVERSE, None) is None + unchanged = client_options.ClientOptions(quota_project_id="qp-1") + assert ( + _inherit_universe_in_client_options(EXTENDED_OPS_DEFAULT_UNIVERSE, unchanged) + is unchanged ) - op_client = client_with_callable.transport.{{ op_prop }} - - assert op_client.universe_domain == EXTENDED_OPS_CUSTOM_UNIVERSE - assert op_client.api_endpoint == {{ op_tpclp_endpoint }} - assert op_client._client_options.api_key is None -{% endfor %} - - -EXTENDED_OPS_CHILD_UNIVERSE = "child.goog" -EXTENDED_OPS_PARENT_ENDPOINT = "custom.endpoint:443" -EXTENDED_OPS_CHILD_ENDPOINT = "child.endpoint:443" -EXTENDED_OPS_QUOTA_PROJECT_ID = "qp-1" - - -@pytest.mark.parametrize( - ( - "parent_universe", - "options_input", - "parent_api_endpoint", - "clear_credentials", - "expected", - ), - [ - pytest.param( - EXTENDED_OPS_DEFAULT_UNIVERSE, - None, - EXTENDED_OPS_PARENT_ENDPOINT, - False, - {"api_endpoint": EXTENDED_OPS_PARENT_ENDPOINT}, - id="none_gdu_with_parent_endpoint_only", - ), - pytest.param( - EXTENDED_OPS_CUSTOM_UNIVERSE, - None, - "", - False, - {"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, - id="none_custom_universe_with_empty_parent_endpoint", - ), - pytest.param( + assert ( + _inherit_universe_in_client_options( EXTENDED_OPS_CUSTOM_UNIVERSE, None, - EXTENDED_OPS_PARENT_ENDPOINT, - False, - { - "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, - "api_endpoint": EXTENDED_OPS_PARENT_ENDPOINT, - }, - id="none_inherits_universe_and_endpoint", - ), - pytest.param( - EXTENDED_OPS_DEFAULT_UNIVERSE, - {}, - None, - False, - {}, - id="empty_mapping_gdu_leaves_universe_unset", - ), - pytest.param( - EXTENDED_OPS_CUSTOM_UNIVERSE, - { - "quota_project_id": EXTENDED_OPS_QUOTA_PROJECT_ID, - "api_key": EXTENDED_OPS_TPC_API_KEY, - }, - EXTENDED_OPS_PARENT_ENDPOINT, - True, - { - "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, - "api_endpoint": EXTENDED_OPS_PARENT_ENDPOINT, - "quota_project_id": EXTENDED_OPS_QUOTA_PROJECT_ID, - }, - id="mapping_inherits_and_clears_api_key", - ), - pytest.param( - EXTENDED_OPS_CUSTOM_UNIVERSE, - { - "quota_project_id": EXTENDED_OPS_QUOTA_PROJECT_ID, - "credentials_file": EXTENDED_OPS_CREDENTIALS_FILE, - }, - EXTENDED_OPS_PARENT_ENDPOINT, - True, - { - "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, - "api_endpoint": EXTENDED_OPS_PARENT_ENDPOINT, - "quota_project_id": EXTENDED_OPS_QUOTA_PROJECT_ID, - }, - id="mapping_inherits_and_clears_credentials_file", - ), - pytest.param( - EXTENDED_OPS_CUSTOM_UNIVERSE, - { - "api_endpoint": EXTENDED_OPS_CHILD_ENDPOINT, - "api_key": EXTENDED_OPS_TPC_API_KEY, - }, - EXTENDED_OPS_PARENT_ENDPOINT, - False, - { - "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, - "api_endpoint": EXTENDED_OPS_CHILD_ENDPOINT, - "api_key": EXTENDED_OPS_TPC_API_KEY, - }, - id="mapping_child_endpoint_preserved_without_cred_clear", - ), - pytest.param( - EXTENDED_OPS_DEFAULT_UNIVERSE, - { - "universe_domain": EXTENDED_OPS_CHILD_UNIVERSE, - "api_key": EXTENDED_OPS_TPC_API_KEY, - }, - EXTENDED_OPS_PARENT_ENDPOINT, - False, - { - "universe_domain": EXTENDED_OPS_CHILD_UNIVERSE, - "api_key": EXTENDED_OPS_TPC_API_KEY, - }, - id="mapping_child_universe_blocks_parent_endpoint", - ), - pytest.param( - EXTENDED_OPS_DEFAULT_UNIVERSE, - client_options.ClientOptions( - quota_project_id=EXTENDED_OPS_QUOTA_PROJECT_ID, - ), - EXTENDED_OPS_PARENT_ENDPOINT, - False, - { - "api_endpoint": EXTENDED_OPS_PARENT_ENDPOINT, - "quota_project_id": EXTENDED_OPS_QUOTA_PROJECT_ID, - }, - id="client_options_gdu_inherits_endpoint_only", - ), - pytest.param( - EXTENDED_OPS_CUSTOM_UNIVERSE, - client_options.ClientOptions( - api_endpoint=EXTENDED_OPS_CHILD_ENDPOINT, - api_key=EXTENDED_OPS_TPC_API_KEY, - ), - EXTENDED_OPS_PARENT_ENDPOINT, - False, - { - "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, - "api_endpoint": EXTENDED_OPS_CHILD_ENDPOINT, - "api_key": EXTENDED_OPS_TPC_API_KEY, - }, - id="client_options_preserves_child_endpoint_and_credentials", - ), - pytest.param( - EXTENDED_OPS_CUSTOM_UNIVERSE, - client_options.ClientOptions(api_key=EXTENDED_OPS_TPC_API_KEY), - EXTENDED_OPS_PARENT_ENDPOINT, - True, - { - "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, - "api_endpoint": EXTENDED_OPS_PARENT_ENDPOINT, - }, - id="client_options_inherits_and_clears_api_key", - ), - pytest.param( - EXTENDED_OPS_CUSTOM_UNIVERSE, - client_options.ClientOptions( - credentials_file=EXTENDED_OPS_CREDENTIALS_FILE - ), - EXTENDED_OPS_PARENT_ENDPOINT, - True, - { - "universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE, - "api_endpoint": EXTENDED_OPS_PARENT_ENDPOINT, - }, - id="client_options_inherits_and_clears_credentials_file", - ), - pytest.param( - EXTENDED_OPS_CUSTOM_UNIVERSE, - client_options.ClientOptions( - universe_domain=EXTENDED_OPS_CHILD_UNIVERSE, - api_key=EXTENDED_OPS_TPC_API_KEY, - ), - EXTENDED_OPS_PARENT_ENDPOINT, - True, - {"universe_domain": EXTENDED_OPS_CHILD_UNIVERSE}, - id="client_options_child_universe_blocks_parent_endpoint", - ), - ], -) -def test_{{ service.name|snake_case }}_inherit_universe_in_client_options_propagates_options( - clean_universe_env, - parent_universe, - options_input, - parent_api_endpoint, - clear_credentials, - expected, -): - options = copy.deepcopy(options_input) - - inherited = _inherit_universe_in_client_options( - parent_universe, - options, - parent_api_endpoint=parent_api_endpoint, - clear_credentials=clear_credentials, - ) - - assert inherited is not None - assert inherited.universe_domain == expected.get("universe_domain") - assert inherited.api_endpoint == expected.get("api_endpoint") - assert inherited.api_key == expected.get("api_key") - assert inherited.credentials_file == expected.get("credentials_file") - assert inherited.quota_project_id == expected.get("quota_project_id") - - -@pytest.mark.parametrize( - "parent_endpoint", - [ - pytest.param(None, id="none_parent_endpoint"), - pytest.param("", id="empty_parent_endpoint"), - ], -) -def test_{{ service.name|snake_case }}_inherit_universe_in_client_options_gdu_none_returns_none( - clean_universe_env, parent_endpoint -): - inherited = _inherit_universe_in_client_options( - EXTENDED_OPS_DEFAULT_UNIVERSE, - None, - parent_api_endpoint=parent_endpoint, - ) - - assert inherited is None - - -@pytest.mark.parametrize( - "clear_credentials", - [ - pytest.param(False, id="keep_credentials"), - pytest.param(True, id="clear_credentials_noop"), - ], -) -def test_{{ service.name|snake_case }}_inherit_universe_in_client_options_unchanged_returns_same_instance( - clean_universe_env, clear_credentials -): - unchanged_opts = client_options.ClientOptions( - quota_project_id=EXTENDED_OPS_QUOTA_PROJECT_ID - ) - - inherited = _inherit_universe_in_client_options( - EXTENDED_OPS_DEFAULT_UNIVERSE, - unchanged_opts, - clear_credentials=clear_credentials, - ) - - assert inherited is unchanged_opts - - -def test_{{ service.name|snake_case }}_inherit_universe_in_client_options_preserves_caller_inputs( - clean_universe_env, -): - raw_dict = { - "quota_project_id": EXTENDED_OPS_QUOTA_PROJECT_ID, - "api_key": EXTENDED_OPS_TPC_API_KEY, - } - parent_opts = client_options.ClientOptions( - credentials_file=EXTENDED_OPS_CREDENTIALS_FILE, - ) - - inherited_from_dict = _inherit_universe_in_client_options( - EXTENDED_OPS_CUSTOM_UNIVERSE, raw_dict, clear_credentials=True - ) - inherited_from_opts = _inherit_universe_in_client_options( - EXTENDED_OPS_CUSTOM_UNIVERSE, parent_opts, clear_credentials=True - ) - - assert raw_dict == { - "quota_project_id": EXTENDED_OPS_QUOTA_PROJECT_ID, - "api_key": EXTENDED_OPS_TPC_API_KEY, - } - assert inherited_from_dict.api_key is None - assert inherited_from_opts is not parent_opts - assert parent_opts.credentials_file == EXTENDED_OPS_CREDENTIALS_FILE - assert inherited_from_opts.credentials_file is None - - -@pytest.mark.parametrize( - "env_value,expected_universe", - [ - pytest.param(" googleapis.com ", None, id="whitespace_padded_gdu"), - pytest.param( - EXTENDED_OPS_CUSTOM_UNIVERSE, - EXTENDED_OPS_DEFAULT_UNIVERSE, - id="tpc_env_requires_explicit_gdu", - ), - pytest.param( - "", - EXTENDED_OPS_DEFAULT_UNIVERSE, - id="empty_env_requires_explicit_gdu", - ), - pytest.param( - " ", - EXTENDED_OPS_DEFAULT_UNIVERSE, - id="whitespace_env_requires_explicit_gdu", - ), - ], -) -def test_{{ service.name|snake_case }}_inherit_universe_in_client_options_env_override_and_whitespace( - clean_universe_env, env_value, expected_universe -): - clean_universe_env.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", env_value) - - inherited = _inherit_universe_in_client_options( - EXTENDED_OPS_DEFAULT_UNIVERSE, None + parent_api_endpoint=EXTENDED_OPS_TRANSPORT_HOST, + ).api_endpoint + == EXTENDED_OPS_TRANSPORT_HOST ) - - if expected_universe is None: - assert inherited is None - else: - assert inherited is not None - assert inherited.universe_domain == expected_universe - assert inherited.api_endpoint is None - - -def test_{{ service.name|snake_case }}_inherit_universe_in_client_options_invalid_type_raises( - clean_universe_env, -): - with pytest.raises( - TypeError, - match=r"ClientOptions instance, Mapping, or None; got str", - ): + with pytest.raises(TypeError, match="ClientOptions instance, Mapping, or None"): _inherit_universe_in_client_options( EXTENDED_OPS_DEFAULT_UNIVERSE, "invalid" # type: ignore[arg-type] ) +{% endfor %} {% endif %} {% endblock %} diff --git a/packages/gapic-generator/tests/unit/generator/test_extended_ops_universe.py b/packages/gapic-generator/tests/unit/generator/test_extended_ops_universe.py new file mode 100644 index 000000000000..b53ad798a4ca --- /dev/null +++ b/packages/gapic-generator/tests/unit/generator/test_extended_ops_universe.py @@ -0,0 +1,394 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Generator-level exhaustive tests for Extended Operations universe helpers.""" + +import ast +import copy +import dataclasses +import os +from collections.abc import Mapping +from typing import Any, Optional, Union + +import pytest +from google.api_core import client_options as client_options_lib + +from gapic.generator import generator +from gapic.schema import metadata +from gapic.utils import Options + +DEFAULT_UNIVERSE = "googleapis.com" +CUSTOM_UNIVERSE = "apis-tpclp.goog" +CHILD_UNIVERSE = "child.goog" +PARENT_ENDPOINT = "custom.endpoint:443" +CHILD_ENDPOINT = "child.endpoint:443" +API_KEY = "secret" +CREDENTIALS_FILE = "creds.json" +QUOTA_PROJECT_ID = "qp-1" + + +@dataclasses.dataclass +class _MinimalNaming: + module_namespace: tuple[str, ...] = ("google", "cloud") + versioned_module_name: str = "compute_v1" + warehouse_package_name: str = "google-cloud-compute" + + +@dataclasses.dataclass +class _MinimalService: + any_extended_operations_methods: bool + name: str = "Instances" + host: str = "compute.googleapis.com" + oauth_scopes: tuple[str, ...] = ("https://www.googleapis.com/auth/compute",) + methods: dict[str, Any] = dataclasses.field(default_factory=dict) + has_lro: bool = False + has_resumable_upload_methods: bool = False + meta: metadata.Metadata = dataclasses.field(default_factory=metadata.Metadata) + + +@dataclasses.dataclass +class _MinimalApi: + services: dict[str, Any] + naming: _MinimalNaming = dataclasses.field(default_factory=_MinimalNaming) + has_location_mixin: bool = False + has_operations_mixin: bool = False + has_iam_mixin: bool = False + all_method_settings: dict[str, Any] = dataclasses.field(default_factory=dict) + mixin_api_methods: dict[str, Any] = dataclasses.field(default_factory=dict) + subpackages: dict[str, Any] = dataclasses.field(default_factory=dict) + + def get_extended_operations_services(self, service: Any) -> list[Any]: + return [] + + +def _render_base_transport(*, any_extended_operations_methods: bool) -> str: + opts = Options.build("transport=grpc+rest") + gen = generator.Generator(opts) + service = _MinimalService( + any_extended_operations_methods=any_extended_operations_methods + ) + api = _MinimalApi(services={"Instances": service}) + template = gen._env.get_template( + "%namespace/%name_%version/%sub/services/%service/transports/base.py.j2" + ) + return template.render(api=api, service=service, opts=opts) + + +@pytest.fixture(scope="module") +def inherit_universe_helper(): + """Extract and load _inherit_universe_in_client_options from rendered template.""" + rendered = _render_base_transport(any_extended_operations_methods=True) + tree = ast.parse(rendered) + func_node = next( + node + for node in tree.body + if isinstance(node, ast.FunctionDef) + and node.name == "_inherit_universe_in_client_options" + ) + module = ast.Module(body=[func_node], type_ignores=[]) + namespace: dict[str, Any] = { + "Any": Any, + "Mapping": Mapping, + "Optional": Optional, + "Union": Union, + "_DEFAULT_UNIVERSE": DEFAULT_UNIVERSE, + "client_options_lib": client_options_lib, + "copy": copy, + "os": os, + } + exec(compile(module, "", "exec"), namespace) + return namespace["_inherit_universe_in_client_options"] + + +@pytest.fixture(autouse=True) +def _clean_universe_env(monkeypatch): + monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) + + +def test_non_extended_ops_service_emits_no_extended_ops_helpers(): + rendered = _render_base_transport(any_extended_operations_methods=False) + + assert "_inherit_universe_in_client_options" not in rendered + assert "_extended_operations_client_options" not in rendered + assert "_configure_extended_operations_client_options" not in rendered + + +@pytest.mark.parametrize( + ( + "parent_universe", + "options_input", + "parent_api_endpoint", + "clear_credentials", + "expected", + ), + [ + pytest.param( + DEFAULT_UNIVERSE, + None, + PARENT_ENDPOINT, + False, + {"api_endpoint": PARENT_ENDPOINT}, + id="none_gdu_with_parent_endpoint_only", + ), + pytest.param( + CUSTOM_UNIVERSE, + None, + "", + False, + {"universe_domain": CUSTOM_UNIVERSE}, + id="none_custom_universe_with_empty_parent_endpoint", + ), + pytest.param( + CUSTOM_UNIVERSE, + None, + PARENT_ENDPOINT, + False, + { + "universe_domain": CUSTOM_UNIVERSE, + "api_endpoint": PARENT_ENDPOINT, + }, + id="none_inherits_universe_and_endpoint", + ), + pytest.param( + DEFAULT_UNIVERSE, + {}, + None, + False, + {}, + id="empty_mapping_gdu_leaves_universe_unset", + ), + pytest.param( + CUSTOM_UNIVERSE, + {"quota_project_id": QUOTA_PROJECT_ID, "api_key": API_KEY}, + PARENT_ENDPOINT, + True, + { + "universe_domain": CUSTOM_UNIVERSE, + "api_endpoint": PARENT_ENDPOINT, + "quota_project_id": QUOTA_PROJECT_ID, + }, + id="mapping_inherits_and_clears_api_key", + ), + pytest.param( + CUSTOM_UNIVERSE, + { + "quota_project_id": QUOTA_PROJECT_ID, + "credentials_file": CREDENTIALS_FILE, + }, + PARENT_ENDPOINT, + True, + { + "universe_domain": CUSTOM_UNIVERSE, + "api_endpoint": PARENT_ENDPOINT, + "quota_project_id": QUOTA_PROJECT_ID, + }, + id="mapping_inherits_and_clears_credentials_file", + ), + pytest.param( + CUSTOM_UNIVERSE, + {"api_endpoint": CHILD_ENDPOINT, "api_key": API_KEY}, + PARENT_ENDPOINT, + False, + { + "universe_domain": CUSTOM_UNIVERSE, + "api_endpoint": CHILD_ENDPOINT, + "api_key": API_KEY, + }, + id="mapping_child_endpoint_preserved_without_cred_clear", + ), + pytest.param( + DEFAULT_UNIVERSE, + {"universe_domain": CHILD_UNIVERSE, "api_key": API_KEY}, + PARENT_ENDPOINT, + False, + {"universe_domain": CHILD_UNIVERSE, "api_key": API_KEY}, + id="mapping_child_universe_blocks_parent_endpoint", + ), + pytest.param( + DEFAULT_UNIVERSE, + client_options_lib.ClientOptions(quota_project_id=QUOTA_PROJECT_ID), + PARENT_ENDPOINT, + False, + { + "api_endpoint": PARENT_ENDPOINT, + "quota_project_id": QUOTA_PROJECT_ID, + }, + id="client_options_gdu_inherits_endpoint_only", + ), + pytest.param( + CUSTOM_UNIVERSE, + client_options_lib.ClientOptions( + api_endpoint=CHILD_ENDPOINT, + api_key=API_KEY, + ), + PARENT_ENDPOINT, + False, + { + "universe_domain": CUSTOM_UNIVERSE, + "api_endpoint": CHILD_ENDPOINT, + "api_key": API_KEY, + }, + id="client_options_preserves_child_endpoint_and_credentials", + ), + pytest.param( + CUSTOM_UNIVERSE, + client_options_lib.ClientOptions(api_key=API_KEY), + PARENT_ENDPOINT, + True, + { + "universe_domain": CUSTOM_UNIVERSE, + "api_endpoint": PARENT_ENDPOINT, + }, + id="client_options_inherits_and_clears_api_key", + ), + pytest.param( + CUSTOM_UNIVERSE, + client_options_lib.ClientOptions(credentials_file=CREDENTIALS_FILE), + PARENT_ENDPOINT, + True, + { + "universe_domain": CUSTOM_UNIVERSE, + "api_endpoint": PARENT_ENDPOINT, + }, + id="client_options_inherits_and_clears_credentials_file", + ), + pytest.param( + CUSTOM_UNIVERSE, + client_options_lib.ClientOptions( + universe_domain=CHILD_UNIVERSE, + api_key=API_KEY, + ), + PARENT_ENDPOINT, + True, + {"universe_domain": CHILD_UNIVERSE}, + id="client_options_child_universe_blocks_parent_endpoint", + ), + ], +) +def test_inherit_universe_propagates_options( + inherit_universe_helper, + parent_universe, + options_input, + parent_api_endpoint, + clear_credentials, + expected, +): + options = copy.deepcopy(options_input) + + inherited = inherit_universe_helper( + parent_universe, + options, + parent_api_endpoint=parent_api_endpoint, + clear_credentials=clear_credentials, + ) + + assert inherited is not None + assert inherited.universe_domain == expected.get("universe_domain") + assert inherited.api_endpoint == expected.get("api_endpoint") + assert inherited.api_key == expected.get("api_key") + assert inherited.credentials_file == expected.get("credentials_file") + assert inherited.quota_project_id == expected.get("quota_project_id") + + +@pytest.mark.parametrize( + "parent_endpoint", + [ + pytest.param(None, id="none_parent_endpoint"), + pytest.param("", id="empty_parent_endpoint"), + ], +) +def test_inherit_universe_gdu_none_returns_none( + inherit_universe_helper, parent_endpoint +): + assert ( + inherit_universe_helper( + DEFAULT_UNIVERSE, None, parent_api_endpoint=parent_endpoint + ) + is None + ) + + +@pytest.mark.parametrize( + "clear_credentials", + [ + pytest.param(False, id="keep_credentials"), + pytest.param(True, id="clear_credentials_noop"), + ], +) +def test_inherit_universe_unchanged_returns_same_instance( + inherit_universe_helper, clear_credentials +): + unchanged_opts = client_options_lib.ClientOptions(quota_project_id=QUOTA_PROJECT_ID) + + inherited = inherit_universe_helper( + DEFAULT_UNIVERSE, + unchanged_opts, + clear_credentials=clear_credentials, + ) + + assert inherited is unchanged_opts + + +def test_inherit_universe_preserves_caller_inputs(inherit_universe_helper): + raw_dict = {"quota_project_id": QUOTA_PROJECT_ID, "api_key": API_KEY} + parent_opts = client_options_lib.ClientOptions(credentials_file=CREDENTIALS_FILE) + + inherited_from_dict = inherit_universe_helper( + CUSTOM_UNIVERSE, raw_dict, clear_credentials=True + ) + inherited_from_opts = inherit_universe_helper( + CUSTOM_UNIVERSE, parent_opts, clear_credentials=True + ) + + assert raw_dict == {"quota_project_id": QUOTA_PROJECT_ID, "api_key": API_KEY} + assert inherited_from_dict.api_key is None + assert inherited_from_opts is not parent_opts + assert parent_opts.credentials_file == CREDENTIALS_FILE + assert inherited_from_opts.credentials_file is None + + +@pytest.mark.parametrize( + "env_value,expected_universe", + [ + pytest.param(" googleapis.com ", None, id="whitespace_padded_gdu"), + pytest.param( + CUSTOM_UNIVERSE, DEFAULT_UNIVERSE, id="tpc_env_requires_explicit_gdu" + ), + pytest.param("", DEFAULT_UNIVERSE, id="empty_env_requires_explicit_gdu"), + pytest.param( + " ", DEFAULT_UNIVERSE, id="whitespace_env_requires_explicit_gdu" + ), + ], +) +def test_inherit_universe_env_override_and_whitespace( + inherit_universe_helper, monkeypatch, env_value, expected_universe +): + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", env_value) + + inherited = inherit_universe_helper(DEFAULT_UNIVERSE, None) + + if expected_universe is None: + assert inherited is None + else: + assert inherited is not None + assert inherited.universe_domain == expected_universe + assert inherited.api_endpoint is None + + +def test_inherit_universe_invalid_type_raises(inherit_universe_helper): + with pytest.raises( + TypeError, + match=r"ClientOptions instance, Mapping, or None; got str", + ): + inherit_universe_helper(DEFAULT_UNIVERSE, "invalid")