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..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 @@ -78,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 }} @@ -476,6 +479,42 @@ 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 + ): + configure_ext_ops = getattr( + self._transport, + "_configure_extended_operations_client_options", + None, + ) + 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 get_api_endpoint( @@ -523,6 +562,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 +613,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..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 @@ -3,14 +3,25 @@ {% 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, + {% endif %} ) _ASYNC_WRAP_METHOD_SUPPORTS_TRACING = _WRAP_METHOD_SUPPORTS_TRACING _WRAP_METHOD_SUPPORTS_KIND = _WRAP_METHOD_SUPPORTS_TRACING @@ -63,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): @@ -75,6 +167,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 +269,34 @@ 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") + 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] = {} @property @@ -494,6 +619,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=self._credentials is not None, + ) + 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 +660,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..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 @@ -64,6 +64,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 @@ -75,6 +78,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 @@ -2856,5 +2862,317 @@ 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_TRANSPORT_HOST = "custom.transport.test:443" +EXTENDED_OPS_EXPLICIT_ENDPOINT = "explicit.options.test:443" +EXTENDED_OPS_CREDENTIALS_FILE = "creds.json" +EXTENDED_OPS_API_KEY = "test-api-key" + + +@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 + + +@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' %} +{% 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 %} + ], +) +@pytest.mark.parametrize( + "env_value,raw_options,expected_universe,expected_endpoint", + [ + pytest.param( + None, + client_options.ClientOptions( + universe_domain=EXTENDED_OPS_CUSTOM_UNIVERSE, + quota_project_id="qp-ext", + ), + EXTENDED_OPS_CUSTOM_UNIVERSE, + {{ op_tpclp_endpoint }}, + id="client_options_tpc", + ), + pytest.param( + None, + {"api_endpoint": EXTENDED_OPS_EXPLICIT_ENDPOINT}, + EXTENDED_OPS_DEFAULT_UNIVERSE, + EXTENDED_OPS_EXPLICIT_ENDPOINT, + id="dict_endpoint_only", + ), + pytest.param( + EXTENDED_OPS_CUSTOM_UNIVERSE, + None, + EXTENDED_OPS_CUSTOM_UNIVERSE, + {{ op_tpclp_endpoint }}, + 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_empty_env", + ), + ], +) +def test_{{ service.name|snake_case }}_extended_operations_{{ operations_service.name|snake_case }}_client_options_propagation( + clean_universe_env, + transport_name, + env_value, + raw_options, + expected_universe, + expected_endpoint, +): + 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=creds, + transport=transport_name, + client_options=raw_options, + ) + clean_universe_env.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) + 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 == expected_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 %} + ], +) +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, + "load_credentials_from_file", + autospec=True, + spec_set=True, + return_value=(ga_credentials.AnonymousCredentials(), None), + ): + client_file = {{ service.client_name }}( + transport=transport_name, client_options=file_opts + ) + client_key = {{ service.client_name }}( + transport=transport_name, client_options=key_opts + ) + + 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( + "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 +): + creds = ga_credentials.AnonymousCredentials() + t_custom = transport_class( + host=EXTENDED_OPS_TRANSPORT_HOST, + credentials=creds, + client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + ) + 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}, + ) + + 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( + clean_universe_env, mock_default_credentials +): + user_channel_transport = transports.{{ service.grpc_transport_name }}( + host="ignored.channel.test:443", + channel=mock.create_autospec(grpc.Channel, instance=True, spec_set=True), + 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_and_callable_transport( + clean_universe_env, mock_default_credentials, transport_class +): + creds = ga_credentials.AnonymousCredentials() + prebuilt = transport_class(host=EXTENDED_OPS_TRANSPORT_HOST, credentials=creds) + stale_op = prebuilt.{{ op_prop }} + + client_tpc = {{ service.client_name }}( + transport=prebuilt, + client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + ) + assert client_tpc.transport.{{ op_prop }} is not stale_op + assert client_tpc.transport.{{ op_prop }}.api_endpoint == prebuilt.host + + client_gdu = {{ service.client_name }}( + transport=prebuilt, + client_options={"api_endpoint": EXTENDED_OPS_EXPLICIT_ENDPOINT}, + ) + assert client_gdu.transport.{{ op_prop }}.api_endpoint == EXTENDED_OPS_EXPLICIT_ENDPOINT + + configured = transport_class( + credentials=creds, + client_options={"universe_domain": EXTENDED_OPS_DEFAULT_UNIVERSE}, + ) + 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 + ) + 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_t, + client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + ) + autospec_t._configure_extended_operations_client_options.assert_called_once() + + 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 }}_custom_transport_and_helper_boundaries( + 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_t = CustomTransport() + assert ( + {{ service.client_name }}( + transport=custom_t, + client_options={"universe_domain": EXTENDED_OPS_CUSTOM_UNIVERSE}, + ).transport + is custom_t + ) + 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 + ) + assert ( + _inherit_universe_in_client_options( + EXTENDED_OPS_CUSTOM_UNIVERSE, + None, + parent_api_endpoint=EXTENDED_OPS_TRANSPORT_HOST, + ).api_endpoint + == EXTENDED_OPS_TRANSPORT_HOST + ) + 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")