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 9c93aaea9c1d..3ce984d3dca7 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 @@ -8,6 +8,7 @@ from typing import {% if service.any_extended_operations_methods %}Any, {% endif {% 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 ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -64,6 +65,22 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_vers DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class {{ service.name }}Transport(abc.ABC): """Abstract transport class for {{ service.name }}.""" @@ -162,6 +179,23 @@ class {{ service.name }}Transport(abc.ABC): host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} 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 136319c7ced0..a56da1e894b5 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 @@ -996,7 +996,7 @@ def test_{{ service.name|snake_case }}_grpc_transport_otel_channel_interceptor() client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -1070,7 +1070,9 @@ def test_{{ service.name|snake_case }}_grpc_asyncio_transport_otel_channel_inter client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -2498,6 +2500,98 @@ def test_{{ service.name|snake_case }}_base_transport_wrap_method_modern_api_cor assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_{{ service.name|snake_case }}_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.{{ service.name }}Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_{{ service.name|snake_case }}_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.{{ service.name }}Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_{{ service.name|snake_case }}_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.{{ service.name }}Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_{{ service.name|snake_case }}_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.{{ service.name }}Transport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_{{ service.name|snake_case }}_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py index 515c173224af..1c983a7b6c9c 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/transports/base.py @@ -18,6 +18,7 @@ from google.cloud.asset_v1 import gapic_version as package_version from google.cloud.asset_v1._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -43,6 +44,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class AssetServiceTransport(abc.ABC): """Abstract transport class for AssetService.""" @@ -133,6 +150,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py index 17fc4c8a5c07..9d2c8e0ce996 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py @@ -851,7 +851,7 @@ def test_asset_service_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -925,7 +925,9 @@ def test_asset_service_grpc_asyncio_transport_otel_channel_interceptor(): client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -18433,6 +18435,98 @@ def test_asset_service_base_transport_wrap_method_modern_api_core(monkeypatch): assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_asset_service_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.AssetServiceTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_asset_service_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.AssetServiceTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_asset_service_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.AssetServiceTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_asset_service_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.AssetServiceTransport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_asset_service_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py index 9ad2c974a10c..b01ed15fa856 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/transports/base.py @@ -18,6 +18,7 @@ from google.iam.credentials_v1 import gapic_version as package_version from google.iam.credentials_v1._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -40,6 +41,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class IAMCredentialsTransport(abc.ABC): """Abstract transport class for IAMCredentials.""" @@ -130,6 +147,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py index f39f23ababfa..335044510b6f 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py @@ -841,7 +841,7 @@ def test_iam_credentials_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -915,7 +915,9 @@ def test_iam_credentials_grpc_asyncio_transport_otel_channel_interceptor(): client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -4479,6 +4481,98 @@ def test_iam_credentials_base_transport_wrap_method_modern_api_core(monkeypatch) assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_iam_credentials_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.IAMCredentialsTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_iam_credentials_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.IAMCredentialsTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_iam_credentials_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.IAMCredentialsTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_iam_credentials_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.IAMCredentialsTransport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_iam_credentials_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py index 963fc7ddb134..47083faecb65 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/transports/base.py @@ -18,6 +18,7 @@ from google.cloud.eventarc_v1 import gapic_version as package_version from google.cloud.eventarc_v1._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -55,6 +56,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class EventarcTransport(abc.ABC): """Abstract transport class for Eventarc.""" @@ -145,6 +162,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py index b5e055c25ec9..5813de209667 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py @@ -872,7 +872,7 @@ def test_eventarc_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -946,7 +946,9 @@ def test_eventarc_grpc_asyncio_transport_otel_channel_interceptor(): client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -33536,6 +33538,98 @@ def test_eventarc_base_transport_wrap_method_modern_api_core(monkeypatch): assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_eventarc_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.EventarcTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_eventarc_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.EventarcTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_eventarc_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.EventarcTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_eventarc_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.EventarcTransport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_eventarc_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py index 4a5dbf0b6ca1..39e779508c30 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/transports/base.py @@ -18,6 +18,7 @@ from google.cloud.logging_v2 import gapic_version as package_version from google.cloud.logging_v2._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -43,6 +44,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class ConfigServiceV2Transport(abc.ABC): """Abstract transport class for ConfigServiceV2.""" @@ -136,6 +153,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py index 4f1882897e01..34c0dab36412 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/transports/base.py @@ -18,6 +18,7 @@ from google.cloud.logging_v2 import gapic_version as package_version from google.cloud.logging_v2._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -42,6 +43,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class LoggingServiceV2Transport(abc.ABC): """Abstract transport class for LoggingServiceV2.""" @@ -136,6 +153,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py index 98e6b8826af6..75129f39de39 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py @@ -18,6 +18,7 @@ from google.cloud.logging_v2 import gapic_version as package_version from google.cloud.logging_v2._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -42,6 +43,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class MetricsServiceV2Transport(abc.ABC): """Abstract transport class for MetricsServiceV2.""" @@ -136,6 +153,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py index acea90dd0a47..33f3bb9ec412 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py @@ -827,7 +827,7 @@ def test_config_service_v2_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -901,7 +901,9 @@ def test_config_service_v2_grpc_asyncio_transport_otel_channel_interceptor(): client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -14030,6 +14032,98 @@ def test_config_service_v2_base_transport_wrap_method_modern_api_core(monkeypatc assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_config_service_v2_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.ConfigServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_config_service_v2_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.ConfigServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_config_service_v2_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.ConfigServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_config_service_v2_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.ConfigServiceV2Transport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_config_service_v2_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py index 433ff946bd8b..4e8db85de8cc 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py @@ -828,7 +828,7 @@ def test_logging_service_v2_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -902,7 +902,9 @@ def test_logging_service_v2_grpc_asyncio_transport_otel_channel_interceptor(): client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -4470,6 +4472,98 @@ def test_logging_service_v2_base_transport_wrap_method_modern_api_core(monkeypat assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_logging_service_v2_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.LoggingServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_logging_service_v2_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.LoggingServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_logging_service_v2_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.LoggingServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_logging_service_v2_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.LoggingServiceV2Transport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_logging_service_v2_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py index c3809e05816a..e1f2519e74b9 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py @@ -826,7 +826,7 @@ def test_metrics_service_v2_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -900,7 +900,9 @@ def test_metrics_service_v2_grpc_asyncio_transport_otel_channel_interceptor(): client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -4270,6 +4272,98 @@ def test_metrics_service_v2_base_transport_wrap_method_modern_api_core(monkeypat assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_metrics_service_v2_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.MetricsServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_metrics_service_v2_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.MetricsServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_metrics_service_v2_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.MetricsServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_metrics_service_v2_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.MetricsServiceV2Transport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_metrics_service_v2_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py index 4a5dbf0b6ca1..39e779508c30 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/transports/base.py @@ -18,6 +18,7 @@ from google.cloud.logging_v2 import gapic_version as package_version from google.cloud.logging_v2._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -43,6 +44,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class ConfigServiceV2Transport(abc.ABC): """Abstract transport class for ConfigServiceV2.""" @@ -136,6 +153,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py index 4f1882897e01..34c0dab36412 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/transports/base.py @@ -18,6 +18,7 @@ from google.cloud.logging_v2 import gapic_version as package_version from google.cloud.logging_v2._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -42,6 +43,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class LoggingServiceV2Transport(abc.ABC): """Abstract transport class for LoggingServiceV2.""" @@ -136,6 +153,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py index 98e6b8826af6..75129f39de39 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/transports/base.py @@ -18,6 +18,7 @@ from google.cloud.logging_v2 import gapic_version as package_version from google.cloud.logging_v2._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -42,6 +43,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class MetricsServiceV2Transport(abc.ABC): """Abstract transport class for MetricsServiceV2.""" @@ -136,6 +153,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py index 5d7d971258ae..b3e9f0f93138 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py @@ -827,7 +827,7 @@ def test_config_service_v2_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -901,7 +901,9 @@ def test_config_service_v2_grpc_asyncio_transport_otel_channel_interceptor(): client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -14030,6 +14032,98 @@ def test_config_service_v2_base_transport_wrap_method_modern_api_core(monkeypatc assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_config_service_v2_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.ConfigServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_config_service_v2_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.ConfigServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_config_service_v2_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.ConfigServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_config_service_v2_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.ConfigServiceV2Transport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_config_service_v2_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py index 433ff946bd8b..4e8db85de8cc 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py @@ -828,7 +828,7 @@ def test_logging_service_v2_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -902,7 +902,9 @@ def test_logging_service_v2_grpc_asyncio_transport_otel_channel_interceptor(): client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -4470,6 +4472,98 @@ def test_logging_service_v2_base_transport_wrap_method_modern_api_core(monkeypat assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_logging_service_v2_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.LoggingServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_logging_service_v2_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.LoggingServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_logging_service_v2_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.LoggingServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_logging_service_v2_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.LoggingServiceV2Transport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_logging_service_v2_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py index 5fc12c22406b..ab376d187ebd 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py @@ -826,7 +826,7 @@ def test_metrics_service_v2_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -900,7 +900,9 @@ def test_metrics_service_v2_grpc_asyncio_transport_otel_channel_interceptor(): client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -4270,6 +4272,98 @@ def test_metrics_service_v2_base_transport_wrap_method_modern_api_core(monkeypat assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_metrics_service_v2_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.MetricsServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_metrics_service_v2_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.MetricsServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_metrics_service_v2_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.MetricsServiceV2Transport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_metrics_service_v2_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.MetricsServiceV2Transport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_metrics_service_v2_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py index 7164fc0bfe5f..3da74b7acd7b 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/transports/base.py @@ -18,6 +18,7 @@ from google.cloud.redis_v1 import gapic_version as package_version from google.cloud.redis_v1._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -43,6 +44,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class CloudRedisTransport(abc.ABC): """Abstract transport class for CloudRedis.""" @@ -133,6 +150,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py index e2215a295660..876aeac3b5fc 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -859,7 +859,7 @@ def test_cloud_redis_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -933,7 +933,9 @@ def test_cloud_redis_grpc_asyncio_transport_otel_channel_interceptor(): client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -13324,6 +13326,98 @@ def test_cloud_redis_base_transport_wrap_method_modern_api_core(monkeypatch): assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_cloud_redis_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.CloudRedisTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_cloud_redis_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.CloudRedisTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_cloud_redis_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.CloudRedisTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_cloud_redis_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.CloudRedisTransport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_cloud_redis_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py index da37256c19e4..36189e3ab34c 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/transports/base.py @@ -18,6 +18,7 @@ from google.cloud.redis_v1 import gapic_version as package_version from google.cloud.redis_v1._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -43,6 +44,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class CloudRedisTransport(abc.ABC): """Abstract transport class for CloudRedis.""" @@ -133,6 +150,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py index 7b29386993ee..6bfd827cf357 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -859,7 +859,7 @@ def test_cloud_redis_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -933,7 +933,9 @@ def test_cloud_redis_grpc_asyncio_transport_otel_channel_interceptor(): client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -8544,6 +8546,98 @@ def test_cloud_redis_base_transport_wrap_method_modern_api_core(monkeypatch): assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_cloud_redis_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.CloudRedisTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_cloud_redis_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.CloudRedisTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_cloud_redis_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.CloudRedisTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_cloud_redis_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.CloudRedisTransport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_cloud_redis_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/echo/transports/base.py b/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/echo/transports/base.py index f5e34a9f9aa7..b20a002caac8 100755 --- a/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/echo/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/echo/transports/base.py @@ -18,6 +18,7 @@ from google.showcase_v1beta1 import gapic_version as package_version from google.showcase_v1beta1._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -45,6 +46,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class EchoTransport(abc.ABC): """Abstract transport class for Echo.""" @@ -134,6 +151,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/identity/transports/base.py b/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/identity/transports/base.py index 8f44d529f6dd..8c43821e3efe 100755 --- a/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/identity/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/identity/transports/base.py @@ -18,6 +18,7 @@ from google.showcase_v1beta1 import gapic_version as package_version from google.showcase_v1beta1._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -45,6 +46,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class IdentityTransport(abc.ABC): """Abstract transport class for Identity.""" @@ -134,6 +151,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/messaging/transports/base.py b/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/messaging/transports/base.py index c783a24ea331..6eed3807b57d 100755 --- a/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/messaging/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/messaging/transports/base.py @@ -18,6 +18,7 @@ from google.showcase_v1beta1 import gapic_version as package_version from google.showcase_v1beta1._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -46,6 +47,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class MessagingTransport(abc.ABC): """Abstract transport class for Messaging.""" @@ -135,6 +152,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/resumable_upload_service/transports/base.py b/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/resumable_upload_service/transports/base.py index b9ca386076b2..0afaf052f740 100755 --- a/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/resumable_upload_service/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/resumable_upload_service/transports/base.py @@ -18,6 +18,7 @@ from google.showcase_v1beta1 import gapic_version as package_version from google.showcase_v1beta1._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -45,6 +46,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class ResumableUploadServiceTransport(abc.ABC): """Abstract transport class for ResumableUploadService.""" @@ -135,6 +152,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/sequence_service/transports/base.py b/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/sequence_service/transports/base.py index f6b79c09fa5f..fff8f7a70e06 100755 --- a/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/sequence_service/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/sequence_service/transports/base.py @@ -18,6 +18,7 @@ from google.showcase_v1beta1 import gapic_version as package_version from google.showcase_v1beta1._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -46,6 +47,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class SequenceServiceTransport(abc.ABC): """Abstract transport class for SequenceService.""" @@ -135,6 +152,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/testing/transports/base.py b/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/testing/transports/base.py index f0fc08e3ef55..fd44ffb5a593 100755 --- a/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/testing/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/showcase/google/showcase_v1beta1/services/testing/transports/base.py @@ -18,6 +18,7 @@ from google.showcase_v1beta1 import gapic_version as package_version from google.showcase_v1beta1._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -45,6 +46,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class TestingTransport(abc.ABC): """Abstract transport class for Testing.""" @@ -134,6 +151,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_echo.py b/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_echo.py index 526eb660d4ff..183be032c2eb 100755 --- a/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_echo.py +++ b/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_echo.py @@ -1148,7 +1148,7 @@ def test_echo_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -1222,7 +1222,9 @@ def test_echo_grpc_asyncio_transport_otel_channel_interceptor(): client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -9803,6 +9805,98 @@ def test_echo_base_transport_wrap_method_modern_api_core(monkeypatch): assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_echo_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.EchoTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_echo_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.EchoTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_echo_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.EchoTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_echo_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.EchoTransport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_echo_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_identity.py b/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_identity.py index 28a7dd420d23..1c84b8be9ede 100755 --- a/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_identity.py +++ b/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_identity.py @@ -849,7 +849,7 @@ def test_identity_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -923,7 +923,9 @@ def test_identity_grpc_asyncio_transport_otel_channel_interceptor(): client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -6910,6 +6912,98 @@ def test_identity_base_transport_wrap_method_modern_api_core(monkeypatch): assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_identity_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.IdentityTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_identity_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.IdentityTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_identity_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.IdentityTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_identity_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.IdentityTransport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_identity_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_messaging.py b/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_messaging.py index 84906c414aa2..319ff39361ef 100755 --- a/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_messaging.py +++ b/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_messaging.py @@ -853,7 +853,7 @@ def test_messaging_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -927,7 +927,9 @@ def test_messaging_grpc_asyncio_transport_otel_channel_interceptor(): client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -11810,6 +11812,98 @@ def test_messaging_base_transport_wrap_method_modern_api_core(monkeypatch): assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_messaging_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.MessagingTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_messaging_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.MessagingTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_messaging_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.MessagingTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_messaging_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.MessagingTransport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_messaging_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_resumable_upload_service.py b/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_resumable_upload_service.py index 3d2f99ea1ef7..97fb6781b76b 100755 --- a/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_resumable_upload_service.py +++ b/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_resumable_upload_service.py @@ -854,7 +854,7 @@ def test_resumable_upload_service_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -928,7 +928,9 @@ def test_resumable_upload_service_grpc_asyncio_transport_otel_channel_intercepto client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -4503,6 +4505,98 @@ def test_resumable_upload_service_base_transport_wrap_method_modern_api_core(mon assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_resumable_upload_service_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.ResumableUploadServiceTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_resumable_upload_service_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.ResumableUploadServiceTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_resumable_upload_service_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.ResumableUploadServiceTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_resumable_upload_service_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.ResumableUploadServiceTransport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_resumable_upload_service_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_sequence_service.py b/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_sequence_service.py index 444a6f91969a..1371e23c9217 100755 --- a/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_sequence_service.py +++ b/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_sequence_service.py @@ -850,7 +850,7 @@ def test_sequence_service_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -924,7 +924,9 @@ def test_sequence_service_grpc_asyncio_transport_otel_channel_interceptor(): client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -7592,6 +7594,98 @@ def test_sequence_service_base_transport_wrap_method_modern_api_core(monkeypatch assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_sequence_service_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.SequenceServiceTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_sequence_service_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.SequenceServiceTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_sequence_service_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.SequenceServiceTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_sequence_service_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.SequenceServiceTransport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_sequence_service_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_testing.py b/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_testing.py index dbda59a14f09..209e9a760a7e 100755 --- a/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_testing.py +++ b/packages/gapic-generator/tests/integration/goldens/showcase/tests/unit/gapic/showcase_v1beta1/test_testing.py @@ -847,7 +847,7 @@ def test_testing_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -921,7 +921,9 @@ def test_testing_grpc_asyncio_transport_otel_channel_interceptor(): client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -7781,6 +7783,98 @@ def test_testing_base_transport_wrap_method_modern_api_core(monkeypatch): assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_testing_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.TestingTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_testing_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.TestingTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_testing_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.TestingTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_testing_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.TestingTransport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_testing_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py index 5cf929454825..7410f62d990a 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/transports/base.py @@ -18,6 +18,7 @@ from google.cloud.storagebatchoperations_v1 import gapic_version as package_version from google.cloud.storagebatchoperations_v1._compat import ( + _observability, ASYNC_WRAP_METHOD_SUPPORTS_KIND as _ASYNC_WRAP_METHOD_SUPPORTS_KIND, WRAP_METHOD_SUPPORTS_TRACING as _WRAP_METHOD_SUPPORTS_TRACING, ) @@ -45,6 +46,22 @@ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ +class _TransportClientOptions(client_options_lib.ClientOptions): + """Internal ClientOptions subclass that attaches the resolved transport host + as a separate ``_host`` attribute without mutating ``api_endpoint``.""" + + def __init__( + self, + base_options: Optional[client_options_lib.ClientOptions] = None, + *, + _host: Optional[str] = None, + ) -> None: + super().__init__() + if base_options is not None: + self.__dict__.update(base_options.__dict__) + self._host = _host + + class StorageBatchOperationsTransport(abc.ABC): """Abstract transport class for StorageBatchOperations.""" @@ -135,6 +152,23 @@ def __init__( host += ':443' self._host = host + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + + # Attach the resolved transport host on an internal ClientOptions subclass + # so OpenTelemetry spans can fall back to _host without mutating api_endpoint. + # Skip when _ignore_credentials is True (e.g., when a pre-constructed gRPC + # channel is supplied and self._host does not reflect the channel target). + if not self._ignore_credentials and ( + client_options is not None + or ( + _observability is not None + and _observability.is_otel_capabilities_enabled(None) + ) + ): + client_options = _TransportClientOptions( + client_options, _host=self._host + ) self._client_options = client_options self._wrapped_methods: Dict[Callable, Callable] = {} diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py index c1f5ed51ac5c..ccd43107ddfc 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py @@ -851,7 +851,7 @@ def test_storage_batch_operations_grpc_transport_otel_channel_interceptor(): client_options=options, ) - mock_get_interceptor.assert_called_once_with(options) + mock_get_interceptor.assert_called_once_with(transport._client_options) mock_apply_interceptors.assert_called_once_with( mock_channel, [mock_otel_interceptor] ) @@ -925,7 +925,9 @@ def test_storage_batch_operations_grpc_asyncio_transport_otel_channel_intercepto client_options=options, ) - mock_apply_async_interceptors.assert_called_once_with(mock_channel, options) + mock_apply_async_interceptors.assert_called_once_with( + mock_channel, transport._client_options + ) assert mock_create_channel.call_count == 1 assert transport.grpc_channel == mock_channel @@ -8480,6 +8482,98 @@ def test_storage_batch_operations_base_transport_wrap_method_modern_api_core(mon assert "client_options" in mock_wrap.call_args.kwargs +@pytest.mark.parametrize( + "otel_enabled,expected_host", + [ + pytest.param(False, None, id="otel_disabled"), + pytest.param(True, "default.example.com:443", id="otel_enabled"), + ], +) +def test_storage_batch_operations_base_transport_client_options_none( + monkeypatch, otel_enabled, expected_host +): + fake_observability = mock.MagicMock() + fake_observability.is_otel_capabilities_enabled.return_value = otel_enabled + monkeypatch.setattr(transports.base, "_observability", fake_observability) + + transport = transports.StorageBatchOperationsTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=None, + ) + assert getattr(transport._client_options, "api_endpoint", None) is None + assert getattr(transport._client_options, "_host", None) == expected_host + + +@pytest.mark.parametrize( + "initial_endpoint", + [ + pytest.param(None, id="unset_api_endpoint"), + pytest.param("custom.example.com:443", id="explicit_api_endpoint"), + ], +) +def test_storage_batch_operations_base_transport_client_options_object( + initial_endpoint, +): + options = client_options.ClientOptions(api_endpoint=initial_endpoint) + transport = transports.StorageBatchOperationsTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == initial_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options.api_endpoint == initial_endpoint + assert not hasattr(options, "_host") + + +@pytest.mark.parametrize( + "initial_options,expected_endpoint", + [ + pytest.param( + {}, + None, + id="unset_api_endpoint", + ), + pytest.param( + {"api_endpoint": "custom.example.com:443"}, + "custom.example.com:443", + id="explicit_api_endpoint", + ), + ], +) +def test_storage_batch_operations_base_transport_client_options_dict( + initial_options, expected_endpoint +): + options = dict(initial_options) + transport = transports.StorageBatchOperationsTransport( + host="default.example.com:443", + credentials=ga_credentials.AnonymousCredentials(), + client_options=options, + ) + assert isinstance(transport._client_options, client_options.ClientOptions) + assert transport._client_options.api_endpoint == expected_endpoint + assert transport._client_options._host == "default.example.com:443" + assert options == initial_options + + +def test_storage_batch_operations_base_transport_client_options_ignored_when_ignore_credentials(): + class _CustomChannelTransport(transports.StorageBatchOperationsTransport): + def __init__(self, **kwargs): + self._ignore_credentials = True + super().__init__(**kwargs) + + options = client_options.ClientOptions() + transport = _CustomChannelTransport( + host="default.example.com:443", + client_options=options, + ) + assert transport._client_options is options + assert transport._client_options.api_endpoint is None + assert not hasattr(transport._client_options, "_host") + + def test_storage_batch_operations_base_transport_wrap_method_older_api_core_fallbacks(monkeypatch): monkeypatch.setattr(transports.base, "_WRAP_METHOD_SUPPORTS_TRACING", False) with mock.patch.object(transports.base.gapic_v1.method, "wrap_method"): diff --git a/packages/gapic-generator/tests/system/telemetry_requirements_matrix.csv b/packages/gapic-generator/tests/system/telemetry_requirements_matrix.csv index 6b52380bc2c6..9aa07baf72aa 100644 --- a/packages/gapic-generator/tests/system/telemetry_requirements_matrix.csv +++ b/packages/gapic-generator/tests/system/telemetry_requirements_matrix.csv @@ -6,28 +6,28 @@ F1.4,Client Timeout (HTTP),T4,0,HTTP/REST,Client Timeout,1,CLIENT,POST /v1beta1/ F1.5a,Retry Recovery - Attempt 1 (HTTP),T4,0,HTTP/REST,Retry Recovery,2,CLIENT,POST /v1beta1/{name=sequences/*},ERROR,http,NOT SET,NOT SET,POST,503,NOT SET,googleapis.com,/v1beta1/{name=sequences/*},localhost,7469,503,Temporary glitch,NOT SET,T3.span_id,url.full F1.5b,Retry Recovery - Attempt 2 (HTTP),T4,1,HTTP/REST,Retry Recovery,2,CLIENT,POST /v1beta1/{name=sequences/*},UNSET,http,NOT SET,NOT SET,POST,200,NOT SET,googleapis.com,/v1beta1/{name=sequences/*},localhost,7469,NOT SET,NOT SET,NOT SET,T3.span_id,url.full F1.6,Tracing Off (gRPC),T4,N/A,gRPC,Tracing Off,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,No spans emitted -F1.7,Unary Success (gRPC),T4,0,gRPC,Happy Path,1,CLIENT,google.showcase.v1beta1.Echo/Echo,UNSET,grpc,google.showcase.v1beta1.Echo/Echo,OK,NOT SET,NOT SET,0,googleapis.com,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,T3.span_id,"rpc.system, rpc.service" -F1.8,Server Error (gRPC),T4,0,gRPC,Server Failure,1,CLIENT,google.showcase.v1beta1.Echo/Echo,ERROR,grpc,google.showcase.v1beta1.Echo/Echo,NOT SET,NOT SET,NOT SET,3,googleapis.com,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,T3.span_id,"rpc.system, rpc.service" -F1.9,Client Timeout (gRPC),T4,0,gRPC,Client Timeout,1,CLIENT,google.showcase.v1beta1.Echo/Block,ERROR,grpc,google.showcase.v1beta1.Echo/Block,NOT SET,NOT SET,NOT SET,4,googleapis.com,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,T3.span_id,"rpc.system, rpc.service" -F1.10a,Retry Recovery - Attempt 1 (gRPC),T4,0,gRPC,Retry Recovery,2,CLIENT,google.showcase.v1beta1.SequenceService/AttemptSequence,ERROR,grpc,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,14,googleapis.com,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,T3.span_id,"rpc.system, rpc.service" -F1.10b,Retry Recovery - Attempt 2 (gRPC),T4,1,gRPC,Retry Recovery,2,CLIENT,google.showcase.v1beta1.SequenceService/AttemptSequence,UNSET,grpc,google.showcase.v1beta1.SequenceService/AttemptSequence,OK,NOT SET,NOT SET,0,googleapis.com,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,T3.span_id,"rpc.system, rpc.service" +F1.7,Unary Success (gRPC),T4,0,gRPC,Happy Path,1,CLIENT,google.showcase.v1beta1.Echo/Echo,UNSET,grpc,google.showcase.v1beta1.Echo/Echo,OK,NOT SET,NOT SET,0,googleapis.com,NOT SET,localhost,7469,NOT SET,NOT SET,NOT SET,T3.span_id,"rpc.system, rpc.service" +F1.8,Server Error (gRPC),T4,0,gRPC,Server Failure,1,CLIENT,google.showcase.v1beta1.Echo/Echo,ERROR,grpc,google.showcase.v1beta1.Echo/Echo,NOT SET,NOT SET,NOT SET,3,googleapis.com,NOT SET,localhost,7469,NOT SET,NOT SET,NOT SET,T3.span_id,"rpc.system, rpc.service" +F1.9,Client Timeout (gRPC),T4,0,gRPC,Client Timeout,1,CLIENT,google.showcase.v1beta1.Echo/Block,ERROR,grpc,google.showcase.v1beta1.Echo/Block,NOT SET,NOT SET,NOT SET,4,googleapis.com,NOT SET,localhost,7469,NOT SET,NOT SET,NOT SET,T3.span_id,"rpc.system, rpc.service" +F1.10a,Retry Recovery - Attempt 1 (gRPC),T4,0,gRPC,Retry Recovery,2,CLIENT,google.showcase.v1beta1.SequenceService/AttemptSequence,ERROR,grpc,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,14,googleapis.com,NOT SET,localhost,7469,NOT SET,NOT SET,NOT SET,T3.span_id,"rpc.system, rpc.service" +F1.10b,Retry Recovery - Attempt 2 (gRPC),T4,1,gRPC,Retry Recovery,2,CLIENT,google.showcase.v1beta1.SequenceService/AttemptSequence,UNSET,grpc,google.showcase.v1beta1.SequenceService/AttemptSequence,OK,NOT SET,NOT SET,0,googleapis.com,NOT SET,localhost,7469,NOT SET,NOT SET,NOT SET,T3.span_id,"rpc.system, rpc.service" F2.1,Tracing Off (HTTP),T3,N/A,HTTP/REST,Tracing Off,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,No spans emitted -F2.2,Unary Success (HTTP),T3,0,HTTP/REST,Happy Path,1,INTERNAL,google.showcase.v1beta1.Echo/Echo,UNSET,http,google.showcase.v1beta1.Echo/Echo,OK,NOT SET,200,NOT SET,googleapis.com,/v1beta1/echo:echo,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,None (Root),Strict ceiling (no unknown attrs) -F2.3,Server Error (HTTP),T3,0,HTTP/REST,Server Failure,1,INTERNAL,google.showcase.v1beta1.Echo/Echo,ERROR,http,google.showcase.v1beta1.Echo/Echo,BAD_REQUEST,NOT SET,400,NOT SET,googleapis.com,/v1beta1/echo:echo,NOT SET,NOT SET,400,Simulated unretryable invalid argument error.,NOT SET,None (Root),"gcp.errors.domain, gcp.errors.metadata.*" -F2.4,Client Timeout (HTTP),T3,0,HTTP/REST,Client Timeout,1,INTERNAL,google.showcase.v1beta1.Echo/Block,ERROR,http,google.showcase.v1beta1.Echo/Block,ReadTimeout,NOT SET,NOT SET,NOT SET,googleapis.com,/v1beta1/echo:block,NOT SET,NOT SET,ReadTimeout,"HTTPConnectionPool(host='localhost', port=7469): Read timed out. (read timeout=0.2)",NOT SET,None (Root),gcp.errors.domain +F2.2,Unary Success (HTTP),T3,0,HTTP/REST,Happy Path,1,INTERNAL,google.showcase.v1beta1.Echo/Echo,UNSET,http,google.showcase.v1beta1.Echo/Echo,OK,NOT SET,200,NOT SET,googleapis.com,/v1beta1/echo:echo,localhost,7469,NOT SET,NOT SET,NOT SET,None (Root),Strict ceiling (no unknown attrs) +F2.3,Server Error (HTTP),T3,0,HTTP/REST,Server Failure,1,INTERNAL,google.showcase.v1beta1.Echo/Echo,ERROR,http,google.showcase.v1beta1.Echo/Echo,BAD_REQUEST,NOT SET,400,NOT SET,googleapis.com,/v1beta1/echo:echo,localhost,7469,400,Simulated unretryable invalid argument error.,NOT SET,None (Root),"gcp.errors.domain, gcp.errors.metadata.*" +F2.4,Client Timeout (HTTP),T3,0,HTTP/REST,Client Timeout,1,INTERNAL,google.showcase.v1beta1.Echo/Block,ERROR,http,google.showcase.v1beta1.Echo/Block,ReadTimeout,NOT SET,NOT SET,NOT SET,googleapis.com,/v1beta1/echo:block,localhost,7469,ReadTimeout,"HTTPConnectionPool(host='localhost', port=7469): Read timed out. (read timeout=0.2)",NOT SET,None (Root),gcp.errors.domain F2.5,Tracing Off (gRPC),T3,N/A,gRPC,Tracing Off,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,No spans emitted -F2.6,Unary Success (gRPC),T3,0,gRPC,Happy Path,1,INTERNAL,google.showcase.v1beta1.Echo/Echo,UNSET,grpc,google.showcase.v1beta1.Echo/Echo,OK,NOT SET,NOT SET,NOT SET,googleapis.com,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,None (Root),Strict ceiling (no unknown attrs) -F2.7,Server Error (gRPC),T3,0,gRPC,Server Failure,1,INTERNAL,google.showcase.v1beta1.Echo/Echo,ERROR,grpc,google.showcase.v1beta1.Echo/Echo,INVALID_ARGUMENT,NOT SET,NOT SET,NOT SET,googleapis.com,NOT SET,NOT SET,NOT SET,INVALID_ARGUMENT,Simulated unretryable invalid argument error.,NOT SET,None (Root),"gcp.errors.domain, gcp.errors.metadata.*" -F2.8,Client Timeout (gRPC),T3,0,gRPC,Client Timeout,1,INTERNAL,google.showcase.v1beta1.Echo/Block,ERROR,grpc,google.showcase.v1beta1.Echo/Block,DEADLINE_EXCEEDED,NOT SET,NOT SET,NOT SET,googleapis.com,NOT SET,NOT SET,NOT SET,DEADLINE_EXCEEDED,Deadline Exceeded,NOT SET,None (Root),gcp.errors.domain -F3.1a,Retry Succeeds - Root (HTTP),T3,0,HTTP/REST,Retry Recovery,1,INTERNAL,google.showcase.v1beta1.SequenceService/AttemptSequence,UNSET,http,google.showcase.v1beta1.SequenceService/AttemptSequence,OK,NOT SET,200,NOT SET,googleapis.com,/v1beta1/{name=sequences/*},NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,None (Root),Parent aggregates OK; T4 children nested under T3 +F2.6,Unary Success (gRPC),T3,0,gRPC,Happy Path,1,INTERNAL,google.showcase.v1beta1.Echo/Echo,UNSET,grpc,google.showcase.v1beta1.Echo/Echo,OK,NOT SET,NOT SET,NOT SET,googleapis.com,NOT SET,localhost,7469,NOT SET,NOT SET,NOT SET,None (Root),Strict ceiling (no unknown attrs) +F2.7,Server Error (gRPC),T3,0,gRPC,Server Failure,1,INTERNAL,google.showcase.v1beta1.Echo/Echo,ERROR,grpc,google.showcase.v1beta1.Echo/Echo,INVALID_ARGUMENT,NOT SET,NOT SET,NOT SET,googleapis.com,NOT SET,localhost,7469,INVALID_ARGUMENT,Simulated unretryable invalid argument error.,NOT SET,None (Root),"gcp.errors.domain, gcp.errors.metadata.*" +F2.8,Client Timeout (gRPC),T3,0,gRPC,Client Timeout,1,INTERNAL,google.showcase.v1beta1.Echo/Block,ERROR,grpc,google.showcase.v1beta1.Echo/Block,DEADLINE_EXCEEDED,NOT SET,NOT SET,NOT SET,googleapis.com,NOT SET,localhost,7469,DEADLINE_EXCEEDED,Deadline Exceeded,NOT SET,None (Root),gcp.errors.domain +F3.1a,Retry Succeeds - Root (HTTP),T3,0,HTTP/REST,Retry Recovery,1,INTERNAL,google.showcase.v1beta1.SequenceService/AttemptSequence,UNSET,http,google.showcase.v1beta1.SequenceService/AttemptSequence,OK,NOT SET,200,NOT SET,googleapis.com,/v1beta1/{name=sequences/*},localhost,7469,NOT SET,NOT SET,NOT SET,None (Root),Parent aggregates OK; T4 children nested under T3 F3.1b,Retry Succeeds - Attempt 1 (HTTP),T4,0,HTTP/REST,Retry Recovery,2,CLIENT,POST /v1beta1/{name=sequences/*},ERROR,http,NOT SET,NOT SET,POST,503,NOT SET,googleapis.com,/v1beta1/{name=sequences/*},localhost,7469,503,Temporary glitch,NOT SET,T3.span_id,Parent aggregates OK; T4 children nested under T3 F3.1c,Retry Succeeds - Attempt 2 (HTTP),T4,1,HTTP/REST,Retry Recovery,2,CLIENT,POST /v1beta1/{name=sequences/*},UNSET,http,NOT SET,NOT SET,POST,200,NOT SET,googleapis.com,/v1beta1/{name=sequences/*},localhost,7469,NOT SET,NOT SET,NOT SET,T3.span_id,Parent aggregates OK; T4 children nested under T3 -F3.2a,Retries Exhausted - Root (HTTP),T3,0,HTTP/REST,Retries Exhausted,1,INTERNAL,google.showcase.v1beta1.SequenceService/AttemptSequence,ERROR,http,google.showcase.v1beta1.SequenceService/AttemptSequence,UNAVAILABLE,NOT SET,503,NOT SET,googleapis.com,/v1beta1/{name=sequences/*},NOT SET,NOT SET,503,Persistent outage,NOT SET,None (Root),Parent aggregates UNAVAILABLE; all T4 children nested under T3 +F3.2a,Retries Exhausted - Root (HTTP),T3,0,HTTP/REST,Retries Exhausted,1,INTERNAL,google.showcase.v1beta1.SequenceService/AttemptSequence,ERROR,http,google.showcase.v1beta1.SequenceService/AttemptSequence,UNAVAILABLE,NOT SET,503,NOT SET,googleapis.com,/v1beta1/{name=sequences/*},localhost,7469,503,Persistent outage,NOT SET,None (Root),Parent aggregates UNAVAILABLE; all T4 children nested under T3 F3.2b,Retries Exhausted - Attempt 1 (HTTP),T4,0,HTTP/REST,Retries Exhausted,2,CLIENT,POST /v1beta1/{name=sequences/*},ERROR,http,NOT SET,NOT SET,POST,503,NOT SET,googleapis.com,/v1beta1/{name=sequences/*},localhost,7469,503,Persistent outage,NOT SET,T3.span_id,Parent aggregates UNAVAILABLE; all T4 children nested under T3 F3.2c,Retries Exhausted - Attempt 2 (HTTP),T4,1,HTTP/REST,Retries Exhausted,2,CLIENT,POST /v1beta1/{name=sequences/*},ERROR,http,NOT SET,NOT SET,POST,503,NOT SET,googleapis.com,/v1beta1/{name=sequences/*},localhost,7469,503,Persistent outage,NOT SET,T3.span_id,Parent aggregates UNAVAILABLE; all T4 children nested under T3 -F3.3a,Retry Succeeds - Root (gRPC),T3,0,gRPC,Retry Recovery,1,INTERNAL,google.showcase.v1beta1.SequenceService/AttemptSequence,UNSET,grpc,google.showcase.v1beta1.SequenceService/AttemptSequence,OK,NOT SET,NOT SET,NOT SET,googleapis.com,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,None (Root),Parent aggregates OK; T4 children nested under T3 -F3.3b,Retry Succeeds - Attempt 1 (gRPC),T4,0,gRPC,Retry Recovery,2,CLIENT,google.showcase.v1beta1.SequenceService/AttemptSequence,ERROR,grpc,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,14,googleapis.com,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,T3.span_id,Parent aggregates OK; T4 children nested under T3 -F3.3c,Retry Succeeds - Attempt 2 (gRPC),T4,1,gRPC,Retry Recovery,2,CLIENT,google.showcase.v1beta1.SequenceService/AttemptSequence,UNSET,grpc,google.showcase.v1beta1.SequenceService/AttemptSequence,OK,NOT SET,NOT SET,0,googleapis.com,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,T3.span_id,Parent aggregates OK; T4 children nested under T3 -F3.4a,Retries Exhausted - Root (gRPC),T3,0,gRPC,Retries Exhausted,1,INTERNAL,google.showcase.v1beta1.SequenceService/AttemptSequence,ERROR,grpc,google.showcase.v1beta1.SequenceService/AttemptSequence,UNAVAILABLE,NOT SET,NOT SET,NOT SET,googleapis.com,NOT SET,NOT SET,NOT SET,UNAVAILABLE,Persistent outage,NOT SET,None (Root),Parent aggregates UNAVAILABLE; all T4 children nested under T3 -F3.4b,Retries Exhausted - Attempt 1 (gRPC),T4,0,gRPC,Retries Exhausted,2,CLIENT,google.showcase.v1beta1.SequenceService/AttemptSequence,ERROR,grpc,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,14,googleapis.com,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,T3.span_id,Parent aggregates UNAVAILABLE; all T4 children nested under T3 -F3.4c,Retries Exhausted - Attempt 2 (gRPC),T4,1,gRPC,Retries Exhausted,2,CLIENT,google.showcase.v1beta1.SequenceService/AttemptSequence,ERROR,grpc,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,14,googleapis.com,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,T3.span_id,Parent aggregates UNAVAILABLE; all T4 children nested under T3 +F3.3a,Retry Succeeds - Root (gRPC),T3,0,gRPC,Retry Recovery,1,INTERNAL,google.showcase.v1beta1.SequenceService/AttemptSequence,UNSET,grpc,google.showcase.v1beta1.SequenceService/AttemptSequence,OK,NOT SET,NOT SET,NOT SET,googleapis.com,NOT SET,localhost,7469,NOT SET,NOT SET,NOT SET,None (Root),Parent aggregates OK; T4 children nested under T3 +F3.3b,Retry Succeeds - Attempt 1 (gRPC),T4,0,gRPC,Retry Recovery,2,CLIENT,google.showcase.v1beta1.SequenceService/AttemptSequence,ERROR,grpc,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,14,googleapis.com,NOT SET,localhost,7469,NOT SET,NOT SET,NOT SET,T3.span_id,Parent aggregates OK; T4 children nested under T3 +F3.3c,Retry Succeeds - Attempt 2 (gRPC),T4,1,gRPC,Retry Recovery,2,CLIENT,google.showcase.v1beta1.SequenceService/AttemptSequence,UNSET,grpc,google.showcase.v1beta1.SequenceService/AttemptSequence,OK,NOT SET,NOT SET,0,googleapis.com,NOT SET,localhost,7469,NOT SET,NOT SET,NOT SET,T3.span_id,Parent aggregates OK; T4 children nested under T3 +F3.4a,Retries Exhausted - Root (gRPC),T3,0,gRPC,Retries Exhausted,1,INTERNAL,google.showcase.v1beta1.SequenceService/AttemptSequence,ERROR,grpc,google.showcase.v1beta1.SequenceService/AttemptSequence,UNAVAILABLE,NOT SET,NOT SET,NOT SET,googleapis.com,NOT SET,localhost,7469,UNAVAILABLE,Persistent outage,NOT SET,None (Root),Parent aggregates UNAVAILABLE; all T4 children nested under T3 +F3.4b,Retries Exhausted - Attempt 1 (gRPC),T4,0,gRPC,Retries Exhausted,2,CLIENT,google.showcase.v1beta1.SequenceService/AttemptSequence,ERROR,grpc,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,14,googleapis.com,NOT SET,localhost,7469,NOT SET,NOT SET,NOT SET,T3.span_id,Parent aggregates UNAVAILABLE; all T4 children nested under T3 +F3.4c,Retries Exhausted - Attempt 2 (gRPC),T4,1,gRPC,Retries Exhausted,2,CLIENT,google.showcase.v1beta1.SequenceService/AttemptSequence,ERROR,grpc,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,14,googleapis.com,NOT SET,localhost,7469,NOT SET,NOT SET,NOT SET,T3.span_id,Parent aggregates UNAVAILABLE; all T4 children nested under T3 diff --git a/packages/gapic-generator/tests/system/test_span_compliance.py b/packages/gapic-generator/tests/system/test_span_compliance.py index cc1a87a66a5a..18443ebc86c2 100644 --- a/packages/gapic-generator/tests/system/test_span_compliance.py +++ b/packages/gapic-generator/tests/system/test_span_compliance.py @@ -201,6 +201,20 @@ def span_exporter(monkeypatch): # --------------------------------------------------------------------------- +def _insecure_channel_factory(host: str, **kwargs: Any) -> Any: + """Callable channel factory for local Showcase gRPC daemon testing. + + Passing a callable factory instead of a pre-constructed ``grpc.Channel`` + instance ensures ``EchoGrpcTransport`` resolves ``self._host`` from its + ``DEFAULT_HOST`` ("localhost:7469") through the standard host-managed path + (``self._ignore_credentials = False``) while still creating an insecure + channel to the local Showcase server. + """ + import grpc + + return grpc.insecure_channel(host) + + def construct_observability_client( client_class, transport: str, @@ -227,11 +241,15 @@ def construct_observability_client( Returns: An instantiated, ready-to-call Showcase client instance. """ + channel = ( + _insecure_channel_factory if (transport == "grpc" and not use_mtls) else None + ) return conftest.construct_client( client_class, use_mtls=use_mtls, transport_name=transport, client_options=client_options, + channel=channel, ) diff --git a/packages/google-api-core/google/api_core/_observability.py b/packages/google-api-core/google/api_core/_observability.py index 38874b666b6e..68aac8da6927 100644 --- a/packages/google-api-core/google/api_core/_observability.py +++ b/packages/google-api-core/google/api_core/_observability.py @@ -92,10 +92,12 @@ def _extract_endpoint_attributes( universe_domain = None if isinstance(client_options, dict): - endpoint = client_options.get("api_endpoint") + endpoint = client_options.get("api_endpoint") or client_options.get("_host") universe_domain = client_options.get("universe_domain") elif client_options is not None: - endpoint = getattr(client_options, "api_endpoint", None) + endpoint = getattr(client_options, "api_endpoint", None) or getattr( + client_options, "_host", None + ) universe_domain = getattr(client_options, "universe_domain", None) attrs["url.domain"] = universe_domain or "googleapis.com" diff --git a/packages/google-api-core/tests/unit/test_observability.py b/packages/google-api-core/tests/unit/test_observability.py index 1f18428102b8..51fca263b9c6 100644 --- a/packages/google-api-core/tests/unit/test_observability.py +++ b/packages/google-api-core/tests/unit/test_observability.py @@ -379,6 +379,58 @@ def test_extract_endpoint_attributes(client_options, expected_attrs): assert _observability._extract_endpoint_attributes(client_options) == expected_attrs +@pytest.mark.parametrize( + "client_options,expected_attrs", + [ + pytest.param( + {"_host": "localhost:7469"}, + { + "server.address": "localhost", + "server.port": 7469, + "url.domain": "googleapis.com", + }, + id="dict_host_fallback", + ), + pytest.param( + {"api_endpoint": "custom.example.com:8443", "_host": "localhost:7469"}, + { + "server.address": "custom.example.com", + "server.port": 8443, + "url.domain": "googleapis.com", + }, + id="dict_api_endpoint_overrides_host", + ), + pytest.param( + types.SimpleNamespace( + api_endpoint=None, _host="localhost:7469", universe_domain=None + ), + { + "server.address": "localhost", + "server.port": 7469, + "url.domain": "googleapis.com", + }, + id="object_host_fallback", + ), + pytest.param( + types.SimpleNamespace( + api_endpoint="custom.example.com:8443", + _host="localhost:7469", + universe_domain="custom.domain", + ), + { + "server.address": "custom.example.com", + "server.port": 8443, + "url.domain": "custom.domain", + }, + id="object_api_endpoint_overrides_host", + ), + ], +) +def test_extract_endpoint_attributes_host_fallback(client_options, expected_attrs): + """Proves that _extract_endpoint_attributes falls back to _host when api_endpoint is not set.""" + assert _observability._extract_endpoint_attributes(client_options) == expected_attrs + + def test_grpc_client_request_hook(): """Proves that _grpc_client_request_hook attaches extracted T4 attributes to recording spans, normalizes span names, sets fully qualified rpc.method, and allows legacy rpc.system to coexist.