From 583ca76a5f70d025fde666acf37c32783c4d2a66 Mon Sep 17 00:00:00 2001 From: Sakthivel Subramanian Date: Tue, 24 Nov 2026 06:58:20 +0000 Subject: [PATCH 1/4] fix(spanner): validate credential universe domain and preserve client_options in Client.copy() Validate that credentials match the configured universe domain in spanner_v1.Client (sync and async) and CloudMonitoringMetricsExporter, and preserve client_options (clearing credentials_file and api_key), client_info, instance_type, and TLS settings in Client.copy(). --- .../google/cloud/spanner_v1/_async/client.py | 48 ++- .../google/cloud/spanner_v1/_helpers.py | 54 ++++ .../google/cloud/spanner_v1/client.py | 41 ++- .../spanner_v1/metrics/metrics_exporter.py | 23 +- .../tests/unit/_async/test_client.py | 286 ++++++++++++++++++ .../tests/unit/_async/test_instance_extra.py | 41 +++ .../tests/unit/test_client.py | 285 +++++++++++++++++ .../tests/unit/test_instance.py | 41 +++ .../tests/unit/test_metrics_exporter.py | 115 +++++++ 9 files changed, 926 insertions(+), 8 deletions(-) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/client.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/client.py index f996d3b215b9..9b7b86d5534d 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/client.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/client.py @@ -25,6 +25,7 @@ """ __CROSS_SYNC_OUTPUT__ = "google.cloud.spanner_v1.client" +import copy import logging import os import threading @@ -75,6 +76,7 @@ _merge_query_options, _metadata_with_prefix, _validate_client_context, + _validate_universe_domain, ) from google.cloud.spanner_v1.gapic_version import __version__ from google.cloud.spanner_v1.metrics.constants import METRIC_EXPORT_INTERVAL_MS @@ -429,6 +431,10 @@ def __init__( client_options=client_options, _http=None, ) + # Enforce credential-vs-universe validation before starting background + # metrics export because generated GAPIC stubs skip this check. + if not self._emulator_host and self._instance_type != "omni": + _validate_universe_domain(self._client_options, self._credentials) self._client_info = client_info env_query_options = ExecuteSqlRequest.QueryOptions( @@ -707,13 +713,49 @@ def directed_read_options(self): def copy(self): """Make a copy of this client. - Copies the local data stored as simple types but does not copy the - current state of any open connections with the Cloud Bigtable API. + Copies local client configuration (including ``client_options``, + ``client_info``, ``instance_type``, and TLS settings) without copying + open RPC connections. Clears ``credentials_file`` and ``api_key`` on + the copied ``client_options`` because resolved credentials are passed + directly. :rtype: :class:`.Client` :returns: A copy of the current client. """ - return self.__class__(project=self.project, credentials=self._credentials) + if not self._client_options: + client_options = None + elif isinstance(self._client_options, dict): + client_options = google.api_core.client_options.from_dict( + self._client_options + ) + else: + client_options = copy.copy(self._client_options) + + if client_options is not None: + # Resolved self._credentials is forwarded directly; keeping + # credentials_file or api_key would raise DuplicateCredentialArgs. + client_options.credentials_file = None + client_options.api_key = None + + if self._instance_type == "omni": + if client_options is None: + client_options = google.api_core.client_options.ClientOptions( + api_endpoint=self._host + ) + elif not client_options.api_endpoint: + client_options.api_endpoint = self._host + + return self.__class__( + project=self.project, + credentials=self._credentials, + client_info=self._client_info, + client_options=client_options, + instance_type=self._instance_type, + use_plain_text=self._use_plain_text, + ca_certificate=self._ca_certificate, + client_certificate=self._client_certificate, + client_key=self._client_key, + ) @CrossSync.convert async def list_instance_configs(self, page_size=None): diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/_helpers.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/_helpers.py index bea12b01c17e..0d63b90bd31b 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/_helpers.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/_helpers.py @@ -28,8 +28,11 @@ import uuid import proto +from google.api_core import client_options as client_options_lib from google.api_core import datetime_helpers +from google.api_core import universe as api_core_universe from google.api_core.exceptions import Aborted +from google.auth.credentials import AnonymousCredentials from google.protobuf.internal.enum_type_wrapper import EnumTypeWrapper from google.protobuf.message import DecodeError, Message from google.protobuf.struct_pb2 import NULL_VALUE, ListValue, Value @@ -1536,3 +1539,54 @@ def _drain_stream(iterator): while consuming trailing gRPC metadata so the stream terminates cleanly with status OK. """ _GLOBAL_STREAM_DRAINER.drain(iterator) + + +def _is_mock_object(value) -> bool: + """Return True when ``value`` is a ``unittest.mock`` or ``mock`` object. + + Args: + value: Any object to inspect. + + Returns: + bool: True if any class in ``value``'s MRO comes from + ``unittest.mock`` or ``mock.mock``. + """ + return any( + cls.__module__ in ("unittest.mock", "mock.mock") for cls in type(value).__mro__ + ) + + +def _validate_universe_domain(client_options, credentials) -> None: + """Validate that credentials belong to the configured universe domain. + + Normalizes ``dict`` ``client_options`` once at ingress, resolves the client + universe domain (``client_options.universe_domain`` -> + ``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` -> ``"googleapis.com"``), and verifies + compatibility via :func:`google.api_core.universe.compare_domains`. + + Skips validation when ``credentials`` is ``None``, + :class:`~google.auth.credentials.AnonymousCredentials`, or a mock object + whose ``universe_domain`` attribute is itself a mock. + + Args: + client_options: ``ClientOptions``, ``dict``, or ``None``. + credentials: Resolved credential instance or ``None``. + + Raises: + google.api_core.universe.EmptyUniverseError: If the configured universe + domain is an empty or whitespace-only string. + google.api_core.universe.UniverseMismatchError: If the credential's + universe domain does not match the configured universe domain. + """ + if credentials is None or isinstance(credentials, AnonymousCredentials): + return + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + client_universe = api_core_universe.determine_domain( + getattr(client_options, "universe_domain", None), + os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN"), + ) + creds_universe = getattr(credentials, "universe_domain", None) + if _is_mock_object(creds_universe): + return + api_core_universe.compare_domains(client_universe, credentials) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/client.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/client.py index cd37ac22718e..8fbdfb4a1c2f 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/client.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/client.py @@ -27,6 +27,7 @@ :class:`~google.cloud.spanner_v1.database.Database` """ +import copy import logging import os import threading @@ -60,6 +61,7 @@ _merge_query_options, _metadata_with_prefix, _validate_client_context, + _validate_universe_domain, ) from google.cloud.spanner_v1.gapic_version import __version__ from google.cloud.spanner_v1.instance import Instance @@ -378,6 +380,8 @@ def __init__( client_options=client_options, _http=None, ) + if not self._emulator_host and self._instance_type != "omni": + _validate_universe_domain(self._client_options, self._credentials) self._client_info = client_info env_query_options = ExecuteSqlRequest.QueryOptions( optimizer_version=_get_spanner_optimizer_version(), @@ -593,12 +597,43 @@ def directed_read_options(self): def copy(self): """Make a copy of this client. - Copies the local data stored as simple types but does not copy the - current state of any open connections with the Cloud Bigtable API. + Copies local client configuration (including ``client_options``, + ``client_info``, ``instance_type``, and TLS settings) without copying + open RPC connections. Clears ``credentials_file`` and ``api_key`` on + the copied ``client_options`` because resolved credentials are passed + directly. :rtype: :class:`.Client` :returns: A copy of the current client.""" - return self.__class__(project=self.project, credentials=self._credentials) + if not self._client_options: + client_options = None + elif isinstance(self._client_options, dict): + client_options = google.api_core.client_options.from_dict( + self._client_options + ) + else: + client_options = copy.copy(self._client_options) + if client_options is not None: + client_options.credentials_file = None + client_options.api_key = None + if self._instance_type == "omni": + if client_options is None: + client_options = google.api_core.client_options.ClientOptions( + api_endpoint=self._host + ) + elif not client_options.api_endpoint: + client_options.api_endpoint = self._host + return self.__class__( + project=self.project, + credentials=self._credentials, + client_info=self._client_info, + client_options=client_options, + instance_type=self._instance_type, + use_plain_text=self._use_plain_text, + ca_certificate=self._ca_certificate, + client_certificate=self._client_certificate, + client_key=self._client_key, + ) def list_instance_configs(self, page_size=None): """List available instance configurations for the client's project. diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/metrics/metrics_exporter.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/metrics/metrics_exporter.py index 02ae24ec542f..3050bd69a101 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/metrics/metrics_exporter.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/metrics/metrics_exporter.py @@ -40,6 +40,7 @@ # pylint: disable=no-name-in-module from google.protobuf.timestamp_pb2 import Timestamp +from google.cloud.spanner_v1._helpers import _validate_universe_domain from google.cloud.spanner_v1.gapic_version import __version__ from .constants import ( @@ -144,8 +145,13 @@ def __init__( if client is not None: self.client = client else: - # Re-scope credentials pinned to Spanner-only scopes for Cloud Monitoring. + # Validate explicit credentials before re-scoping or opening a + # transport because MetricServiceClient's generated stub is a no-op. monitoring_credentials = credentials + if monitoring_credentials is not None: + _validate_universe_domain(client_options, monitoring_credentials) + + # Re-scope credentials pinned to Spanner-only scopes for Cloud Monitoring. if ( isinstance(credentials, ga_credentials.Scoped) and not credentials.requires_scopes @@ -156,7 +162,7 @@ def __init__( ) # Pass transport/channel callables so MetricServiceClient resolves - # universe_domain and validates credentials while keeping _OPTIONS. + # universe_domain while keeping _OPTIONS. self.client = MetricServiceClient( credentials=monitoring_credentials, client_options=client_options, @@ -168,6 +174,19 @@ def __init__( ), ) + # Validate credentials resolved by MetricServiceClient (ADC or + # credentials_file) and close the transport on mismatch to avoid + # leaking a gRPC channel. + if monitoring_credentials is None: + resolved_credentials = getattr( + getattr(self.client, "transport", None), "_credentials", None + ) + try: + _validate_universe_domain(client_options, resolved_credentials) + except Exception: + self.client.transport.close() + raise + # Avoid ambient ADC project fallback when explicit credentials are provided. if not project_id: project_id = getattr(credentials, "project_id", None) diff --git a/packages/google-cloud-spanner/tests/unit/_async/test_client.py b/packages/google-cloud-spanner/tests/unit/_async/test_client.py index 9bf7a3751a87..ac5a414c2e57 100644 --- a/packages/google-cloud-spanner/tests/unit/_async/test_client.py +++ b/packages/google-cloud-spanner/tests/unit/_async/test_client.py @@ -1056,3 +1056,289 @@ async def test_constructor_w_omni_explicit_credentials_instance(self): credentials=creds, ) self.assertIs(client._credentials, creds) + + def _make_universe_credentials(self, universe_domain="googleapis.com"): + from google.auth import credentials as ga_credentials + + class _UniverseCredentials(ga_credentials.Credentials): + def __init__(self, universe): + super().__init__() + self._universe_domain = universe + + def refresh(self, request): + self.token = "token" + + def with_quota_project(self, quota_project_id): + return self + + return _UniverseCredentials(universe_domain) + + @CrossSync.pytest + async def test_constructor_universe_mismatch_raises_before_metrics(self): + from google.api_core.universe import UniverseMismatchError + + from google.cloud.spanner_v1._async import client as MUT + + tpc_creds = self._make_universe_credentials("tpc.example") + for client_options in (None, {}, {"universe_domain": "googleapis.com"}): + with ( + mock.patch.dict( + os.environ, + {"SPANNER_DISABLE_BUILTIN_METRICS": "false"}, + clear=False, + ), + mock.patch.object(MUT, "_initialize_metrics") as mock_init_metrics, + ): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + with self.assertRaises(UniverseMismatchError): + self._make_one( + project=self.PROJECT, + credentials=tpc_creds, + client_options=client_options, + ) + mock_init_metrics.assert_not_called() + + @CrossSync.pytest + async def test_constructor_empty_universe_domain_and_precedence(self): + from google.api_core.universe import EmptyUniverseError + + gdu_creds = self._make_universe_credentials("googleapis.com") + tpc_creds = self._make_universe_credentials("tpc.example") + + for blank in ("", " "): + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + with self.assertRaises(EmptyUniverseError): + self._make_one( + project=self.PROJECT, + credentials=gdu_creds, + client_options={"universe_domain": blank}, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": blank}, clear=False + ): + os.environ.pop("SPANNER_EMULATOR_HOST", None) + with self.assertRaises(EmptyUniverseError): + self._make_one( + project=self.PROJECT, + credentials=gdu_creds, + ) + + with mock.patch.dict( + os.environ, + {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "other.example"}, + clear=False, + ): + os.environ.pop("SPANNER_EMULATOR_HOST", None) + client = self._make_one( + project=self.PROJECT, + credentials=tpc_creds, + client_options={"universe_domain": "tpc.example"}, + ) + self.assertEqual(client._client_options.universe_domain, "tpc.example") + + @CrossSync.pytest + async def test_constructor_universe_match_adc_and_api_endpoint_only(self): + from google.api_core.universe import UniverseMismatchError + + tpc_creds = self._make_universe_credentials("tpc.example") + + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + client = self._make_one( + project=self.PROJECT, + credentials=tpc_creds, + client_options={"universe_domain": "tpc.example"}, + ) + self.assertEqual(client._client_options.universe_domain, "tpc.example") + + with mock.patch.dict( + os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.example"}, clear=False + ): + os.environ.pop("SPANNER_EMULATOR_HOST", None) + client = self._make_one(project=self.PROJECT, credentials=tpc_creds) + self.assertEqual(client.project, self.PROJECT) + + with ( + mock.patch.dict(os.environ, {}, clear=False), + mock.patch("google.auth.default", return_value=(tpc_creds, self.PROJECT)), + ): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + with self.assertRaises(UniverseMismatchError): + self._make_one(project=self.PROJECT) + + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + with self.assertRaises(UniverseMismatchError): + self._make_one( + project=self.PROJECT, + credentials=tpc_creds, + client_options={"api_endpoint": "spanner.tpc.example"}, + ) + + @CrossSync.pytest + async def test_constructor_skips_universe_validation_for_emulator_omni_anonymous( + self, + ): + from google.api_core.universe import UniverseMismatchError + + from google.cloud.spanner_v1._async.client import InstanceType + + gdu_creds = self._make_universe_credentials("googleapis.com") + # Contrast: without emulator/Omni/Anonymous, the same mismatched env fails closed. + with mock.patch.dict( + os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.example"}, clear=False + ): + os.environ.pop("SPANNER_EMULATOR_HOST", None) + with self.assertRaises(UniverseMismatchError): + self._make_one(project=self.PROJECT, credentials=gdu_creds) + with mock.patch.dict( + os.environ, + { + "GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.example", + "SPANNER_EMULATOR_HOST": "localhost:9010", + }, + clear=False, + ): + emu_client = self._make_one(project=self.PROJECT, credentials=gdu_creds) + self.assertEqual(emu_client._emulator_host, "localhost:9010") + + with mock.patch.dict( + os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.example"}, clear=False + ): + os.environ.pop("SPANNER_EMULATOR_HOST", None) + omni_client = self._make_one( + project=self.PROJECT, + client_options={"api_endpoint": "omni.host:15000"}, + instance_type=InstanceType.OMNI, + use_plain_text=True, + ) + self.assertEqual(omni_client._host, "omni.host:15000") + + anon_client = self._make_one( + project=self.PROJECT, + credentials=AnonymousCredentials(), + client_options={"api_endpoint": "localhost:9010"}, + ) + self.assertEqual(anon_client._emulator_host, "localhost:9010") + + @CrossSync.pytest + async def test_copy_preserves_client_options_and_tls_without_mutating_original( + self, + ): + from google.api_core.client_options import ClientOptions + from google.api_core.gapic_v1 import client_info as client_info_lib + + tpc_creds = self._make_universe_credentials("tpc.example") + custom_info = client_info_lib.ClientInfo(user_agent="custom-agent/1.0") + orig_options = ClientOptions( + universe_domain="tpc.example", + api_endpoint="spanner.tpc.example:443", + quota_project_id="quota-proj", + ) + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + client = self._make_one( + project=self.PROJECT, + credentials=tpc_creds, + client_info=custom_info, + client_options=orig_options, + use_plain_text=True, + ca_certificate="/tmp/ca.pem", + client_certificate="/tmp/cert.pem", + client_key="/tmp/key.pem", + ) + copied = client.copy() + + self.assertIsNot(copied, client) + self.assertIsNot(copied._client_options, orig_options) + self.assertEqual(copied._client_options.universe_domain, "tpc.example") + self.assertEqual(copied._client_options.api_endpoint, "spanner.tpc.example:443") + self.assertEqual(copied._host, "spanner.tpc.example:443") + self.assertIs(copied._client_info, custom_info) + self.assertTrue(copied._use_plain_text) + self.assertEqual(copied._ca_certificate, "/tmp/ca.pem") + self.assertEqual(copied._client_certificate, "/tmp/cert.pem") + self.assertEqual(copied._client_key, "/tmp/key.pem") + + gdu_creds = self._make_universe_credentials("googleapis.com") + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + empty_opt_client = self._make_one( + project=self.PROJECT, credentials=gdu_creds, client_options={} + ) + copied_empty = empty_opt_client.copy() + self.assertIsNone(copied_empty._client_options) + + @CrossSync.pytest + async def test_copy_clears_credential_options_and_handles_omni_and_anonymous(self): + import warnings + + from google.api_core.client_options import ClientOptions + + from google.cloud.spanner_v1._async.client import InstanceType + + gdu_creds = self._make_universe_credentials("googleapis.com") + with ( + mock.patch.dict(os.environ, {}, clear=False), + mock.patch( + "google.auth.load_credentials_from_file", + return_value=(gdu_creds, self.PROJECT), + ), + ): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + file_options = ClientOptions( + credentials_file="/tmp/fake-creds.json", + api_endpoint="spanner.custom.example", + ) + client_from_file = self._make_one( + project=self.PROJECT, client_options=file_options + ) + copied_file = client_from_file.copy() + self.assertIsNone(copied_file._client_options.credentials_file) + self.assertEqual(file_options.credentials_file, "/tmp/fake-creds.json") + self.assertEqual(copied_file._host, "spanner.custom.example") + + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + api_key_options = ClientOptions( + api_key="test-api-key", + api_endpoint="spanner.custom.example", + ) + client_api_key = self._make_one( + project=self.PROJECT, client_options=api_key_options + ) + copied_api_key = client_api_key.copy() + self.assertIsNone(copied_api_key._client_options.api_key) + self.assertEqual(api_key_options.api_key, "test-api-key") + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + omni_client = self._make_one( + project=self.PROJECT, + experimental_host="omni.host:15000", + use_plain_text=True, + ) + copied_omni = omni_client.copy() + self.assertEqual(copied_omni.instance_type, InstanceType.OMNI) + self.assertEqual(copied_omni._host, "omni.host:15000") + self.assertTrue(copied_omni._use_plain_text) + + anon_client = self._make_one( + project=self.PROJECT, + credentials=AnonymousCredentials(), + client_options={"api_endpoint": "localhost:9010"}, + ) + copied_anon = anon_client.copy() + self.assertEqual(copied_anon._emulator_host, "localhost:9010") + self.assertEqual(copied_anon._host, "localhost:9010") diff --git a/packages/google-cloud-spanner/tests/unit/_async/test_instance_extra.py b/packages/google-cloud-spanner/tests/unit/_async/test_instance_extra.py index 0f89a72dd51e..7bbdbba68362 100644 --- a/packages/google-cloud-spanner/tests/unit/_async/test_instance_extra.py +++ b/packages/google-cloud-spanner/tests/unit/_async/test_instance_extra.py @@ -191,6 +191,47 @@ def test_copy(self): inst_copy = self.instance.copy() self.assertEqual(inst_copy.instance_id, self.instance.instance_id) + def test_copy_preserves_client_options(self): + import os + + from google.auth import credentials as ga_credentials + + from google.cloud.spanner_v1._async.client import Client + + class _UniverseCredentials(ga_credentials.Credentials): + def __init__(self, universe): + super().__init__() + self._universe_domain = universe + + def refresh(self, request): + self.token = "token" + + tpc_creds = _UniverseCredentials("tpc.example") + with mock.patch.dict( + os.environ, {"SPANNER_DISABLE_BUILTIN_METRICS": "true"}, clear=False + ): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + client = Client( + project="project-id", + credentials=tpc_creds, + client_options={ + "universe_domain": "tpc.example", + "api_endpoint": "spanner.tpc.example:443", + }, + ) + instance = Instance("instance-id", client) + new_instance = instance.copy() + + self.assertIsNot(new_instance._client, client) + self.assertEqual( + new_instance._client._client_options.universe_domain, "tpc.example" + ) + self.assertEqual( + new_instance._client._client_options.api_endpoint, + "spanner.tpc.example:443", + ) + async def test_init_validation(self): # coverage for lines 133-137 from google.api_core.exceptions import InvalidArgument diff --git a/packages/google-cloud-spanner/tests/unit/test_client.py b/packages/google-cloud-spanner/tests/unit/test_client.py index adb1510a1612..a26204f114be 100644 --- a/packages/google-cloud-spanner/tests/unit/test_client.py +++ b/packages/google-cloud-spanner/tests/unit/test_client.py @@ -625,6 +625,291 @@ def test_copy(self): self.assertIs(new_client._credentials, client._credentials) self.assertEqual(new_client.project, client.project) + def _make_universe_credentials(self, universe_domain="googleapis.com"): + from google.auth import credentials as ga_credentials + + class _UniverseCredentials(ga_credentials.Credentials): + def __init__(self, universe): + super().__init__() + self._universe_domain = universe + + def refresh(self, request): + self.token = "token" + + def with_quota_project(self, quota_project_id): + return self + + return _UniverseCredentials(universe_domain) + + def test_constructor_universe_mismatch_raises_before_metrics(self): + from google.api_core.universe import UniverseMismatchError + + from google.cloud.spanner_v1 import client as MUT + + tpc_creds = self._make_universe_credentials("tpc.example") + for client_options in (None, {}, {"universe_domain": "googleapis.com"}): + with ( + mock.patch.dict( + os.environ, + {"SPANNER_DISABLE_BUILTIN_METRICS": "false"}, + clear=False, + ), + mock.patch.object(MUT, "_initialize_metrics") as mock_init_metrics, + ): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + with self.assertRaises(UniverseMismatchError): + self._make_one( + project=self.PROJECT, + credentials=tpc_creds, + client_options=client_options, + ) + mock_init_metrics.assert_not_called() + + def test_constructor_empty_universe_domain_and_precedence(self): + from google.api_core.universe import EmptyUniverseError + + gdu_creds = self._make_universe_credentials("googleapis.com") + tpc_creds = self._make_universe_credentials("tpc.example") + + for blank in ("", " "): + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + with self.assertRaises(EmptyUniverseError): + self._make_one( + project=self.PROJECT, + credentials=gdu_creds, + client_options={"universe_domain": blank}, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": blank}, clear=False + ): + os.environ.pop("SPANNER_EMULATOR_HOST", None) + with self.assertRaises(EmptyUniverseError): + self._make_one( + project=self.PROJECT, + credentials=gdu_creds, + ) + + # client_options.universe_domain takes precedence over env var. + with mock.patch.dict( + os.environ, + {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "other.example"}, + clear=False, + ): + os.environ.pop("SPANNER_EMULATOR_HOST", None) + client = self._make_one( + project=self.PROJECT, + credentials=tpc_creds, + client_options={"universe_domain": "tpc.example"}, + ) + self.assertEqual(client._client_options.universe_domain, "tpc.example") + + def test_constructor_universe_match_adc_and_api_endpoint_only(self): + from google.api_core.universe import UniverseMismatchError + + tpc_creds = self._make_universe_credentials("tpc.example") + + # Matching client_options.universe_domain succeeds. + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + client = self._make_one( + project=self.PROJECT, + credentials=tpc_creds, + client_options={"universe_domain": "tpc.example"}, + ) + self.assertEqual(client._client_options.universe_domain, "tpc.example") + + # Matching GOOGLE_CLOUD_UNIVERSE_DOMAIN env var succeeds. + with mock.patch.dict( + os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.example"}, clear=False + ): + os.environ.pop("SPANNER_EMULATOR_HOST", None) + client = self._make_one(project=self.PROJECT, credentials=tpc_creds) + self.assertEqual(client.project, self.PROJECT) + + # ADC (credentials=None) mismatch raises UniverseMismatchError. + with ( + mock.patch.dict(os.environ, {}, clear=False), + mock.patch("google.auth.default", return_value=(tpc_creds, self.PROJECT)), + ): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + with self.assertRaises(UniverseMismatchError): + self._make_one(project=self.PROJECT) + + # api_endpoint-only TPC client without universe_domain fails closed. + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + with self.assertRaises(UniverseMismatchError): + self._make_one( + project=self.PROJECT, + credentials=tpc_creds, + client_options={"api_endpoint": "spanner.tpc.example"}, + ) + + def test_constructor_skips_universe_validation_for_emulator_omni_anonymous(self): + from google.api_core.universe import UniverseMismatchError + + from google.cloud.spanner_v1.client import InstanceType + + gdu_creds = self._make_universe_credentials("googleapis.com") + # Contrast: without emulator/Omni/Anonymous, the same mismatched env fails closed. + with mock.patch.dict( + os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.example"}, clear=False + ): + os.environ.pop("SPANNER_EMULATOR_HOST", None) + with self.assertRaises(UniverseMismatchError): + self._make_one(project=self.PROJECT, credentials=gdu_creds) + with mock.patch.dict( + os.environ, + { + "GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.example", + "SPANNER_EMULATOR_HOST": "localhost:9010", + }, + clear=False, + ): + emu_client = self._make_one(project=self.PROJECT, credentials=gdu_creds) + self.assertEqual(emu_client._emulator_host, "localhost:9010") + + with mock.patch.dict( + os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.example"}, clear=False + ): + os.environ.pop("SPANNER_EMULATOR_HOST", None) + omni_client = self._make_one( + project=self.PROJECT, + client_options={"api_endpoint": "omni.host:15000"}, + instance_type=InstanceType.OMNI, + use_plain_text=True, + ) + self.assertEqual(omni_client._host, "omni.host:15000") + + anon_client = self._make_one( + project=self.PROJECT, + credentials=AnonymousCredentials(), + client_options={"api_endpoint": "localhost:9010"}, + ) + self.assertEqual(anon_client._emulator_host, "localhost:9010") + + def test_copy_preserves_client_options_and_tls_without_mutating_original(self): + from google.api_core.client_options import ClientOptions + from google.api_core.gapic_v1 import client_info as client_info_lib + + tpc_creds = self._make_universe_credentials("tpc.example") + custom_info = client_info_lib.ClientInfo(user_agent="custom-agent/1.0") + orig_options = ClientOptions( + universe_domain="tpc.example", + api_endpoint="spanner.tpc.example:443", + quota_project_id="quota-proj", + ) + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + client = self._make_one( + project=self.PROJECT, + credentials=tpc_creds, + client_info=custom_info, + client_options=orig_options, + use_plain_text=True, + ca_certificate="/tmp/ca.pem", + client_certificate="/tmp/cert.pem", + client_key="/tmp/key.pem", + ) + copied = client.copy() + + self.assertIsNot(copied, client) + self.assertIsNot(copied._client_options, orig_options) + self.assertEqual(copied._client_options.universe_domain, "tpc.example") + self.assertEqual(copied._client_options.api_endpoint, "spanner.tpc.example:443") + self.assertEqual(copied._host, "spanner.tpc.example:443") + self.assertIs(copied._client_info, custom_info) + self.assertTrue(copied._use_plain_text) + self.assertEqual(copied._ca_certificate, "/tmp/ca.pem") + self.assertEqual(copied._client_certificate, "/tmp/cert.pem") + self.assertEqual(copied._client_key, "/tmp/key.pem") + + # Empty dict client_options copies cleanly without error. + gdu_creds = self._make_universe_credentials("googleapis.com") + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + empty_opt_client = self._make_one( + project=self.PROJECT, credentials=gdu_creds, client_options={} + ) + copied_empty = empty_opt_client.copy() + self.assertIsNone(copied_empty._client_options) + + def test_copy_clears_credential_options_and_handles_omni_and_anonymous(self): + import warnings + + from google.api_core.client_options import ClientOptions + + from google.cloud.spanner_v1.client import InstanceType + + gdu_creds = self._make_universe_credentials("googleapis.com") + with ( + mock.patch.dict(os.environ, {}, clear=False), + mock.patch( + "google.auth.load_credentials_from_file", + return_value=(gdu_creds, self.PROJECT), + ), + ): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + file_options = ClientOptions( + credentials_file="/tmp/fake-creds.json", + api_endpoint="spanner.custom.example", + ) + client_from_file = self._make_one( + project=self.PROJECT, client_options=file_options + ) + copied_file = client_from_file.copy() + self.assertIsNone(copied_file._client_options.credentials_file) + self.assertEqual(file_options.credentials_file, "/tmp/fake-creds.json") + self.assertEqual(copied_file._host, "spanner.custom.example") + + # api_key in client_options is cleared on copy to avoid DuplicateCredentialArgs. + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + api_key_options = ClientOptions( + api_key="test-api-key", + api_endpoint="spanner.custom.example", + ) + client_api_key = self._make_one( + project=self.PROJECT, client_options=api_key_options + ) + copied_api_key = client_api_key.copy() + self.assertIsNone(copied_api_key._client_options.api_key) + self.assertEqual(api_key_options.api_key, "test-api-key") + + # Omni via deprecated experimental_host (with _client_options=None) copies cleanly. + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + omni_client = self._make_one( + project=self.PROJECT, + experimental_host="omni.host:15000", + use_plain_text=True, + ) + copied_omni = omni_client.copy() + self.assertEqual(copied_omni.instance_type, InstanceType.OMNI) + self.assertEqual(copied_omni._host, "omni.host:15000") + self.assertTrue(copied_omni._use_plain_text) + + # AnonymousCredentials + api_endpoint copies without AttributeError. + anon_client = self._make_one( + project=self.PROJECT, + credentials=AnonymousCredentials(), + client_options={"api_endpoint": "localhost:9010"}, + ) + copied_anon = anon_client.copy() + self.assertEqual(copied_anon._emulator_host, "localhost:9010") + self.assertEqual(copied_anon._host, "localhost:9010") + def test_credentials_property(self): credentials = build_scoped_credentials() client = self._make_one(project=self.PROJECT, credentials=credentials) diff --git a/packages/google-cloud-spanner/tests/unit/test_instance.py b/packages/google-cloud-spanner/tests/unit/test_instance.py index ac57c2e06ac5..3811c17a8b6b 100644 --- a/packages/google-cloud-spanner/tests/unit/test_instance.py +++ b/packages/google-cloud-spanner/tests/unit/test_instance.py @@ -93,6 +93,47 @@ def test_constructor_non_default(self): self.assertEqual(instance.display_name, DISPLAY_NAME) self.assertEqual(instance.labels, self.LABELS) + def test_copy_preserves_client_options(self): + import os + + from google.auth import credentials as ga_credentials + + from google.cloud.spanner_v1.client import Client + + class _UniverseCredentials(ga_credentials.Credentials): + def __init__(self, universe): + super().__init__() + self._universe_domain = universe + + def refresh(self, request): + self.token = "token" + + tpc_creds = _UniverseCredentials("tpc.example") + with mock.patch.dict( + os.environ, {"SPANNER_DISABLE_BUILTIN_METRICS": "true"}, clear=False + ): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("SPANNER_EMULATOR_HOST", None) + client = Client( + project=self.PROJECT, + credentials=tpc_creds, + client_options={ + "universe_domain": "tpc.example", + "api_endpoint": "spanner.tpc.example:443", + }, + ) + instance = self._make_one(self.INSTANCE_ID, client, self.CONFIG_NAME) + new_instance = instance.copy() + + self.assertIsNot(new_instance._client, client) + self.assertEqual( + new_instance._client._client_options.universe_domain, "tpc.example" + ) + self.assertEqual( + new_instance._client._client_options.api_endpoint, + "spanner.tpc.example:443", + ) + def test_copy(self): DISPLAY_NAME = "display_name" diff --git a/packages/google-cloud-spanner/tests/unit/test_metrics_exporter.py b/packages/google-cloud-spanner/tests/unit/test_metrics_exporter.py index cf93fee5fef6..4be7d0ad6461 100644 --- a/packages/google-cloud-spanner/tests/unit/test_metrics_exporter.py +++ b/packages/google-cloud-spanner/tests/unit/test_metrics_exporter.py @@ -766,3 +766,118 @@ def test_init_adc_project_fallback_when_no_credentials(self): client=mock_client, credentials=None, ) + + def _make_universe_credentials(self, universe_domain="googleapis.com"): + class _UniverseCredentials(Credentials): + def __init__(self, universe): + super().__init__() + self._universe_domain = universe + + def refresh(self, request): + self.token = "token" + + return _UniverseCredentials(universe_domain) + + def test_init_universe_mismatch_explicit_and_adc(self): + """Verify mismatched credentials fail pre-init (explicit) and close transport (ADC).""" + from google.api_core.universe import UniverseMismatchError + + tpc_creds = self._make_universe_credentials("tpc.example") + + # Explicit mismatched credentials must raise before MetricServiceClient is built. + with ( + patch.dict(os.environ, {}, clear=False), + patch( + "google.cloud.spanner_v1.metrics.metrics_exporter.MetricServiceClient" + ) as mock_msc, + ): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + with self.assertRaises(UniverseMismatchError): + CloudMonitoringMetricsExporter( + project_id=PROJECT_ID, + credentials=tpc_creds, + ) + mock_msc.assert_not_called() + + # ADC (credentials=None) mismatch must validate transport._credentials and close it. + fake_client = MagicMock() + fake_client.transport._credentials = tpc_creds + with ( + patch.dict(os.environ, {}, clear=False), + patch( + "google.cloud.spanner_v1.metrics.metrics_exporter.MetricServiceClient", + return_value=fake_client, + ), + ): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + with self.assertRaises(UniverseMismatchError): + CloudMonitoringMetricsExporter( + project_id=PROJECT_ID, + credentials=None, + ) + fake_client.transport.close.assert_called_once() + + def test_init_universe_dict_options_matching_blank_and_exemptions(self): + """Verify dict/ClientOptions/env universe matching, dict mismatch, blank error, and skips.""" + from google.api_core.universe import ( + EmptyUniverseError, + UniverseMismatchError, + ) + + tpc_creds = self._make_universe_credentials("tpc.example") + + # Matching dict client_options succeeds. + with ( + patch.dict( + os.environ, + { + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + "GOOGLE_API_USE_MTLS_ENDPOINT": "never", + }, + clear=False, + ), + patch( + "google.cloud.spanner_v1.metrics.metrics_exporter." + "MetricServiceGrpcTransport.create_channel", + return_value=MagicMock(), + ), + ): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + exporter = CloudMonitoringMetricsExporter( + project_id=PROJECT_ID, + credentials=tpc_creds, + client_options={"universe_domain": "tpc.example"}, + ) + self.assertEqual(exporter.client.universe_domain, "tpc.example") + + # Mismatched dict client_options raises UniverseMismatchError. + with patch.dict(os.environ, {}, clear=False): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + with self.assertRaises(UniverseMismatchError): + CloudMonitoringMetricsExporter( + project_id=PROJECT_ID, + credentials=tpc_creds, + client_options={"universe_domain": "other.example"}, + ) + + # Blank universe_domain raises EmptyUniverseError. + with patch.dict(os.environ, {}, clear=False): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + with self.assertRaises(EmptyUniverseError): + CloudMonitoringMetricsExporter( + project_id=PROJECT_ID, + credentials=tpc_creds, + client_options={"universe_domain": " "}, + ) + + # Custom injected client skips validation even with mismatched credentials. + custom_client = MagicMock() + custom_client.common_project_path.return_value = f"projects/{PROJECT_ID}" + with patch.dict(os.environ, {}, clear=False): + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + exporter = CloudMonitoringMetricsExporter( + project_id=PROJECT_ID, + client=custom_client, + credentials=tpc_creds, + ) + self.assertIs(exporter.client, custom_client) From 25254ca9e7a0c72b22f63fb794924cd59f75fa2a Mon Sep 17 00:00:00 2001 From: Sakthivel Subramanian Date: Tue, 24 Nov 2026 07:05:35 +0000 Subject: [PATCH 2/4] Addressed comments --- .../google/cloud/spanner_v1/_helpers.py | 23 ++----------------- .../google-cloud-spanner/tests/_builders.py | 10 ++++++-- .../tests/unit/_async/test_client_extra.py | 4 ++-- .../tests/unit/test_client.py | 4 ++-- 4 files changed, 14 insertions(+), 27 deletions(-) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/_helpers.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/_helpers.py index 0d63b90bd31b..18beb9581285 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/_helpers.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/_helpers.py @@ -1541,21 +1541,6 @@ def _drain_stream(iterator): _GLOBAL_STREAM_DRAINER.drain(iterator) -def _is_mock_object(value) -> bool: - """Return True when ``value`` is a ``unittest.mock`` or ``mock`` object. - - Args: - value: Any object to inspect. - - Returns: - bool: True if any class in ``value``'s MRO comes from - ``unittest.mock`` or ``mock.mock``. - """ - return any( - cls.__module__ in ("unittest.mock", "mock.mock") for cls in type(value).__mro__ - ) - - def _validate_universe_domain(client_options, credentials) -> None: """Validate that credentials belong to the configured universe domain. @@ -1564,9 +1549,8 @@ def _validate_universe_domain(client_options, credentials) -> None: ``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` -> ``"googleapis.com"``), and verifies compatibility via :func:`google.api_core.universe.compare_domains`. - Skips validation when ``credentials`` is ``None``, - :class:`~google.auth.credentials.AnonymousCredentials`, or a mock object - whose ``universe_domain`` attribute is itself a mock. + Skips validation when ``credentials`` is ``None`` or + :class:`~google.auth.credentials.AnonymousCredentials`. Args: client_options: ``ClientOptions``, ``dict``, or ``None``. @@ -1586,7 +1570,4 @@ def _validate_universe_domain(client_options, credentials) -> None: getattr(client_options, "universe_domain", None), os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN"), ) - creds_universe = getattr(credentials, "universe_domain", None) - if _is_mock_object(creds_universe): - return api_core_universe.compare_domains(client_universe, credentials) diff --git a/packages/google-cloud-spanner/tests/_builders.py b/packages/google-cloud-spanner/tests/_builders.py index 7719934ad49b..1bdaccd5a66c 100644 --- a/packages/google-cloud-spanner/tests/_builders.py +++ b/packages/google-cloud-spanner/tests/_builders.py @@ -249,13 +249,19 @@ def build_logger() -> Logger: return create_autospec(Logger, instance=True) -def build_scoped_credentials() -> Credentials: +def build_scoped_credentials(universe_domain: str = "googleapis.com") -> Credentials: """Builds and returns a mock scoped credentials for testing.""" class _ScopedCredentials(Credentials, Scoped): pass - return create_autospec(spec=_ScopedCredentials, instance=True) + creds = create_autospec(spec=_ScopedCredentials, instance=True) + creds.universe_domain = universe_domain + creds.with_scopes.return_value.universe_domain = universe_domain + creds.with_scopes.return_value.with_quota_project.return_value.universe_domain = ( + universe_domain + ) + return creds def build_spanner_api() -> SpannerClient: diff --git a/packages/google-cloud-spanner/tests/unit/_async/test_client_extra.py b/packages/google-cloud-spanner/tests/unit/_async/test_client_extra.py index 99632f9e1b85..b536ad5bc0db 100644 --- a/packages/google-cloud-spanner/tests/unit/_async/test_client_extra.py +++ b/packages/google-cloud-spanner/tests/unit/_async/test_client_extra.py @@ -410,7 +410,7 @@ def test_client_custom_api_endpoint_with_monitoring_host_env(self): from google.cloud.spanner_v1._async import client as MUT - creds = build_scoped_credentials() + creds = build_scoped_credentials(universe_domain="async.universe") with ( mock.patch.dict( os.environ, @@ -459,7 +459,7 @@ def test_client_passes_resolved_project_credentials_and_universe_domain(self): from google.cloud.spanner_v1._async import client as MUT - creds = build_scoped_credentials() + creds = build_scoped_credentials(universe_domain="async.universe") creds.project_id = "resolved-async-project" with ( mock.patch.dict(os.environ, {"SPANNER_DISABLE_BUILTIN_METRICS": "false"}), diff --git a/packages/google-cloud-spanner/tests/unit/test_client.py b/packages/google-cloud-spanner/tests/unit/test_client.py index a26204f114be..099c1e929a75 100644 --- a/packages/google-cloud-spanner/tests/unit/test_client.py +++ b/packages/google-cloud-spanner/tests/unit/test_client.py @@ -1562,7 +1562,7 @@ def test_client_passes_resolved_project_credentials_and_options_to_metrics( ): from google.cloud.spanner_v1 import client as MUT - creds = build_scoped_credentials() + creds = build_scoped_credentials(universe_domain="custom.universe") creds.project_id = "resolved-from-creds" MUT._metrics_monitor_initialized = False try: @@ -1630,7 +1630,7 @@ def test_client_custom_api_endpoint_with_monitoring_host_env( ): from google.cloud.spanner_v1 import client as MUT - creds = build_scoped_credentials() + creds = build_scoped_credentials(universe_domain="custom.universe") MUT._metrics_monitor_initialized = False try: MUT.Client( From 9207f5b72c5fb40dd3f12edabea99c474e31eb0d Mon Sep 17 00:00:00 2001 From: Sakthivel Subramanian Date: Tue, 24 Nov 2026 17:22:31 +0000 Subject: [PATCH 3/4] Addressed comments --- .../google/cloud/spanner_v1/_async/client.py | 5 - .../google/cloud/spanner_v1/_helpers.py | 35 ---- .../google/cloud/spanner_v1/client.py | 3 - .../spanner_v1/metrics/metrics_exporter.py | 23 +-- .../google-cloud-spanner/tests/_builders.py | 10 +- .../tests/unit/_async/test_client.py | 181 +++-------------- .../tests/unit/_async/test_client_extra.py | 4 +- .../tests/unit/_async/test_instance_extra.py | 41 ---- .../tests/unit/test_client.py | 185 +++--------------- .../tests/unit/test_instance.py | 41 ---- .../tests/unit/test_metrics_exporter.py | 115 ----------- 11 files changed, 59 insertions(+), 584 deletions(-) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/client.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/client.py index 9b7b86d5534d..e5d14623ade0 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/client.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/client.py @@ -76,7 +76,6 @@ _merge_query_options, _metadata_with_prefix, _validate_client_context, - _validate_universe_domain, ) from google.cloud.spanner_v1.gapic_version import __version__ from google.cloud.spanner_v1.metrics.constants import METRIC_EXPORT_INTERVAL_MS @@ -431,10 +430,6 @@ def __init__( client_options=client_options, _http=None, ) - # Enforce credential-vs-universe validation before starting background - # metrics export because generated GAPIC stubs skip this check. - if not self._emulator_host and self._instance_type != "omni": - _validate_universe_domain(self._client_options, self._credentials) self._client_info = client_info env_query_options = ExecuteSqlRequest.QueryOptions( diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/_helpers.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/_helpers.py index 18beb9581285..bea12b01c17e 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/_helpers.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/_helpers.py @@ -28,11 +28,8 @@ import uuid import proto -from google.api_core import client_options as client_options_lib from google.api_core import datetime_helpers -from google.api_core import universe as api_core_universe from google.api_core.exceptions import Aborted -from google.auth.credentials import AnonymousCredentials from google.protobuf.internal.enum_type_wrapper import EnumTypeWrapper from google.protobuf.message import DecodeError, Message from google.protobuf.struct_pb2 import NULL_VALUE, ListValue, Value @@ -1539,35 +1536,3 @@ def _drain_stream(iterator): while consuming trailing gRPC metadata so the stream terminates cleanly with status OK. """ _GLOBAL_STREAM_DRAINER.drain(iterator) - - -def _validate_universe_domain(client_options, credentials) -> None: - """Validate that credentials belong to the configured universe domain. - - Normalizes ``dict`` ``client_options`` once at ingress, resolves the client - universe domain (``client_options.universe_domain`` -> - ``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` -> ``"googleapis.com"``), and verifies - compatibility via :func:`google.api_core.universe.compare_domains`. - - Skips validation when ``credentials`` is ``None`` or - :class:`~google.auth.credentials.AnonymousCredentials`. - - Args: - client_options: ``ClientOptions``, ``dict``, or ``None``. - credentials: Resolved credential instance or ``None``. - - Raises: - google.api_core.universe.EmptyUniverseError: If the configured universe - domain is an empty or whitespace-only string. - google.api_core.universe.UniverseMismatchError: If the credential's - universe domain does not match the configured universe domain. - """ - if credentials is None or isinstance(credentials, AnonymousCredentials): - return - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - client_universe = api_core_universe.determine_domain( - getattr(client_options, "universe_domain", None), - os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN"), - ) - api_core_universe.compare_domains(client_universe, credentials) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/client.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/client.py index 8fbdfb4a1c2f..c93bd427bf5f 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/client.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/client.py @@ -61,7 +61,6 @@ _merge_query_options, _metadata_with_prefix, _validate_client_context, - _validate_universe_domain, ) from google.cloud.spanner_v1.gapic_version import __version__ from google.cloud.spanner_v1.instance import Instance @@ -380,8 +379,6 @@ def __init__( client_options=client_options, _http=None, ) - if not self._emulator_host and self._instance_type != "omni": - _validate_universe_domain(self._client_options, self._credentials) self._client_info = client_info env_query_options = ExecuteSqlRequest.QueryOptions( optimizer_version=_get_spanner_optimizer_version(), diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/metrics/metrics_exporter.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/metrics/metrics_exporter.py index 3050bd69a101..02ae24ec542f 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/metrics/metrics_exporter.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/metrics/metrics_exporter.py @@ -40,7 +40,6 @@ # pylint: disable=no-name-in-module from google.protobuf.timestamp_pb2 import Timestamp -from google.cloud.spanner_v1._helpers import _validate_universe_domain from google.cloud.spanner_v1.gapic_version import __version__ from .constants import ( @@ -145,13 +144,8 @@ def __init__( if client is not None: self.client = client else: - # Validate explicit credentials before re-scoping or opening a - # transport because MetricServiceClient's generated stub is a no-op. - monitoring_credentials = credentials - if monitoring_credentials is not None: - _validate_universe_domain(client_options, monitoring_credentials) - # Re-scope credentials pinned to Spanner-only scopes for Cloud Monitoring. + monitoring_credentials = credentials if ( isinstance(credentials, ga_credentials.Scoped) and not credentials.requires_scopes @@ -162,7 +156,7 @@ def __init__( ) # Pass transport/channel callables so MetricServiceClient resolves - # universe_domain while keeping _OPTIONS. + # universe_domain and validates credentials while keeping _OPTIONS. self.client = MetricServiceClient( credentials=monitoring_credentials, client_options=client_options, @@ -174,19 +168,6 @@ def __init__( ), ) - # Validate credentials resolved by MetricServiceClient (ADC or - # credentials_file) and close the transport on mismatch to avoid - # leaking a gRPC channel. - if monitoring_credentials is None: - resolved_credentials = getattr( - getattr(self.client, "transport", None), "_credentials", None - ) - try: - _validate_universe_domain(client_options, resolved_credentials) - except Exception: - self.client.transport.close() - raise - # Avoid ambient ADC project fallback when explicit credentials are provided. if not project_id: project_id = getattr(credentials, "project_id", None) diff --git a/packages/google-cloud-spanner/tests/_builders.py b/packages/google-cloud-spanner/tests/_builders.py index 1bdaccd5a66c..7719934ad49b 100644 --- a/packages/google-cloud-spanner/tests/_builders.py +++ b/packages/google-cloud-spanner/tests/_builders.py @@ -249,19 +249,13 @@ def build_logger() -> Logger: return create_autospec(Logger, instance=True) -def build_scoped_credentials(universe_domain: str = "googleapis.com") -> Credentials: +def build_scoped_credentials() -> Credentials: """Builds and returns a mock scoped credentials for testing.""" class _ScopedCredentials(Credentials, Scoped): pass - creds = create_autospec(spec=_ScopedCredentials, instance=True) - creds.universe_domain = universe_domain - creds.with_scopes.return_value.universe_domain = universe_domain - creds.with_scopes.return_value.with_quota_project.return_value.universe_domain = ( - universe_domain - ) - return creds + return create_autospec(spec=_ScopedCredentials, instance=True) def build_spanner_api() -> SpannerClient: diff --git a/packages/google-cloud-spanner/tests/unit/_async/test_client.py b/packages/google-cloud-spanner/tests/unit/_async/test_client.py index ac5a414c2e57..72a334b6f046 100644 --- a/packages/google-cloud-spanner/tests/unit/_async/test_client.py +++ b/packages/google-cloud-spanner/tests/unit/_async/test_client.py @@ -1065,6 +1065,10 @@ def __init__(self, universe): super().__init__() self._universe_domain = universe + @property + def universe_domain(self): + return self._universe_domain + def refresh(self, request): self.token = "token" @@ -1073,161 +1077,6 @@ def with_quota_project(self, quota_project_id): return _UniverseCredentials(universe_domain) - @CrossSync.pytest - async def test_constructor_universe_mismatch_raises_before_metrics(self): - from google.api_core.universe import UniverseMismatchError - - from google.cloud.spanner_v1._async import client as MUT - - tpc_creds = self._make_universe_credentials("tpc.example") - for client_options in (None, {}, {"universe_domain": "googleapis.com"}): - with ( - mock.patch.dict( - os.environ, - {"SPANNER_DISABLE_BUILTIN_METRICS": "false"}, - clear=False, - ), - mock.patch.object(MUT, "_initialize_metrics") as mock_init_metrics, - ): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - os.environ.pop("SPANNER_EMULATOR_HOST", None) - with self.assertRaises(UniverseMismatchError): - self._make_one( - project=self.PROJECT, - credentials=tpc_creds, - client_options=client_options, - ) - mock_init_metrics.assert_not_called() - - @CrossSync.pytest - async def test_constructor_empty_universe_domain_and_precedence(self): - from google.api_core.universe import EmptyUniverseError - - gdu_creds = self._make_universe_credentials("googleapis.com") - tpc_creds = self._make_universe_credentials("tpc.example") - - for blank in ("", " "): - with mock.patch.dict(os.environ, {}, clear=False): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - os.environ.pop("SPANNER_EMULATOR_HOST", None) - with self.assertRaises(EmptyUniverseError): - self._make_one( - project=self.PROJECT, - credentials=gdu_creds, - client_options={"universe_domain": blank}, - ) - - with mock.patch.dict( - os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": blank}, clear=False - ): - os.environ.pop("SPANNER_EMULATOR_HOST", None) - with self.assertRaises(EmptyUniverseError): - self._make_one( - project=self.PROJECT, - credentials=gdu_creds, - ) - - with mock.patch.dict( - os.environ, - {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "other.example"}, - clear=False, - ): - os.environ.pop("SPANNER_EMULATOR_HOST", None) - client = self._make_one( - project=self.PROJECT, - credentials=tpc_creds, - client_options={"universe_domain": "tpc.example"}, - ) - self.assertEqual(client._client_options.universe_domain, "tpc.example") - - @CrossSync.pytest - async def test_constructor_universe_match_adc_and_api_endpoint_only(self): - from google.api_core.universe import UniverseMismatchError - - tpc_creds = self._make_universe_credentials("tpc.example") - - with mock.patch.dict(os.environ, {}, clear=False): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - os.environ.pop("SPANNER_EMULATOR_HOST", None) - client = self._make_one( - project=self.PROJECT, - credentials=tpc_creds, - client_options={"universe_domain": "tpc.example"}, - ) - self.assertEqual(client._client_options.universe_domain, "tpc.example") - - with mock.patch.dict( - os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.example"}, clear=False - ): - os.environ.pop("SPANNER_EMULATOR_HOST", None) - client = self._make_one(project=self.PROJECT, credentials=tpc_creds) - self.assertEqual(client.project, self.PROJECT) - - with ( - mock.patch.dict(os.environ, {}, clear=False), - mock.patch("google.auth.default", return_value=(tpc_creds, self.PROJECT)), - ): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - os.environ.pop("SPANNER_EMULATOR_HOST", None) - with self.assertRaises(UniverseMismatchError): - self._make_one(project=self.PROJECT) - - with mock.patch.dict(os.environ, {}, clear=False): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - os.environ.pop("SPANNER_EMULATOR_HOST", None) - with self.assertRaises(UniverseMismatchError): - self._make_one( - project=self.PROJECT, - credentials=tpc_creds, - client_options={"api_endpoint": "spanner.tpc.example"}, - ) - - @CrossSync.pytest - async def test_constructor_skips_universe_validation_for_emulator_omni_anonymous( - self, - ): - from google.api_core.universe import UniverseMismatchError - - from google.cloud.spanner_v1._async.client import InstanceType - - gdu_creds = self._make_universe_credentials("googleapis.com") - # Contrast: without emulator/Omni/Anonymous, the same mismatched env fails closed. - with mock.patch.dict( - os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.example"}, clear=False - ): - os.environ.pop("SPANNER_EMULATOR_HOST", None) - with self.assertRaises(UniverseMismatchError): - self._make_one(project=self.PROJECT, credentials=gdu_creds) - with mock.patch.dict( - os.environ, - { - "GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.example", - "SPANNER_EMULATOR_HOST": "localhost:9010", - }, - clear=False, - ): - emu_client = self._make_one(project=self.PROJECT, credentials=gdu_creds) - self.assertEqual(emu_client._emulator_host, "localhost:9010") - - with mock.patch.dict( - os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.example"}, clear=False - ): - os.environ.pop("SPANNER_EMULATOR_HOST", None) - omni_client = self._make_one( - project=self.PROJECT, - client_options={"api_endpoint": "omni.host:15000"}, - instance_type=InstanceType.OMNI, - use_plain_text=True, - ) - self.assertEqual(omni_client._host, "omni.host:15000") - - anon_client = self._make_one( - project=self.PROJECT, - credentials=AnonymousCredentials(), - client_options={"api_endpoint": "localhost:9010"}, - ) - self.assertEqual(anon_client._emulator_host, "localhost:9010") - @CrossSync.pytest async def test_copy_preserves_client_options_and_tls_without_mutating_original( self, @@ -1308,7 +1157,10 @@ async def test_copy_clears_credential_options_and_handles_omni_and_anonymous(sel self.assertEqual(file_options.credentials_file, "/tmp/fake-creds.json") self.assertEqual(copied_file._host, "spanner.custom.example") - with mock.patch.dict(os.environ, {}, clear=False): + with ( + mock.patch.dict(os.environ, {}, clear=False), + mock.patch("google.auth.default", return_value=(gdu_creds, self.PROJECT)), + ): os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) os.environ.pop("SPANNER_EMULATOR_HOST", None) api_key_options = ClientOptions( @@ -1334,6 +1186,23 @@ async def test_copy_clears_credential_options_and_handles_omni_and_anonymous(sel self.assertEqual(copied_omni._host, "omni.host:15000") self.assertTrue(copied_omni._use_plain_text) + orig_omni_options = ClientOptions() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + omni_client_opts = self._make_one( + project=self.PROJECT, + experimental_host="omni.host:15000", + client_options=orig_omni_options, + use_plain_text=True, + ) + copied_omni_opts = omni_client_opts.copy() + self.assertEqual(copied_omni_opts.instance_type, InstanceType.OMNI) + self.assertEqual(copied_omni_opts._host, "omni.host:15000") + self.assertEqual( + copied_omni_opts._client_options.api_endpoint, "omni.host:15000" + ) + self.assertIsNone(orig_omni_options.api_endpoint) + anon_client = self._make_one( project=self.PROJECT, credentials=AnonymousCredentials(), diff --git a/packages/google-cloud-spanner/tests/unit/_async/test_client_extra.py b/packages/google-cloud-spanner/tests/unit/_async/test_client_extra.py index b536ad5bc0db..99632f9e1b85 100644 --- a/packages/google-cloud-spanner/tests/unit/_async/test_client_extra.py +++ b/packages/google-cloud-spanner/tests/unit/_async/test_client_extra.py @@ -410,7 +410,7 @@ def test_client_custom_api_endpoint_with_monitoring_host_env(self): from google.cloud.spanner_v1._async import client as MUT - creds = build_scoped_credentials(universe_domain="async.universe") + creds = build_scoped_credentials() with ( mock.patch.dict( os.environ, @@ -459,7 +459,7 @@ def test_client_passes_resolved_project_credentials_and_universe_domain(self): from google.cloud.spanner_v1._async import client as MUT - creds = build_scoped_credentials(universe_domain="async.universe") + creds = build_scoped_credentials() creds.project_id = "resolved-async-project" with ( mock.patch.dict(os.environ, {"SPANNER_DISABLE_BUILTIN_METRICS": "false"}), diff --git a/packages/google-cloud-spanner/tests/unit/_async/test_instance_extra.py b/packages/google-cloud-spanner/tests/unit/_async/test_instance_extra.py index 7bbdbba68362..0f89a72dd51e 100644 --- a/packages/google-cloud-spanner/tests/unit/_async/test_instance_extra.py +++ b/packages/google-cloud-spanner/tests/unit/_async/test_instance_extra.py @@ -191,47 +191,6 @@ def test_copy(self): inst_copy = self.instance.copy() self.assertEqual(inst_copy.instance_id, self.instance.instance_id) - def test_copy_preserves_client_options(self): - import os - - from google.auth import credentials as ga_credentials - - from google.cloud.spanner_v1._async.client import Client - - class _UniverseCredentials(ga_credentials.Credentials): - def __init__(self, universe): - super().__init__() - self._universe_domain = universe - - def refresh(self, request): - self.token = "token" - - tpc_creds = _UniverseCredentials("tpc.example") - with mock.patch.dict( - os.environ, {"SPANNER_DISABLE_BUILTIN_METRICS": "true"}, clear=False - ): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - os.environ.pop("SPANNER_EMULATOR_HOST", None) - client = Client( - project="project-id", - credentials=tpc_creds, - client_options={ - "universe_domain": "tpc.example", - "api_endpoint": "spanner.tpc.example:443", - }, - ) - instance = Instance("instance-id", client) - new_instance = instance.copy() - - self.assertIsNot(new_instance._client, client) - self.assertEqual( - new_instance._client._client_options.universe_domain, "tpc.example" - ) - self.assertEqual( - new_instance._client._client_options.api_endpoint, - "spanner.tpc.example:443", - ) - async def test_init_validation(self): # coverage for lines 133-137 from google.api_core.exceptions import InvalidArgument diff --git a/packages/google-cloud-spanner/tests/unit/test_client.py b/packages/google-cloud-spanner/tests/unit/test_client.py index 099c1e929a75..4cbb1c2326d1 100644 --- a/packages/google-cloud-spanner/tests/unit/test_client.py +++ b/packages/google-cloud-spanner/tests/unit/test_client.py @@ -633,6 +633,10 @@ def __init__(self, universe): super().__init__() self._universe_domain = universe + @property + def universe_domain(self): + return self._universe_domain + def refresh(self, request): self.token = "token" @@ -641,160 +645,6 @@ def with_quota_project(self, quota_project_id): return _UniverseCredentials(universe_domain) - def test_constructor_universe_mismatch_raises_before_metrics(self): - from google.api_core.universe import UniverseMismatchError - - from google.cloud.spanner_v1 import client as MUT - - tpc_creds = self._make_universe_credentials("tpc.example") - for client_options in (None, {}, {"universe_domain": "googleapis.com"}): - with ( - mock.patch.dict( - os.environ, - {"SPANNER_DISABLE_BUILTIN_METRICS": "false"}, - clear=False, - ), - mock.patch.object(MUT, "_initialize_metrics") as mock_init_metrics, - ): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - os.environ.pop("SPANNER_EMULATOR_HOST", None) - with self.assertRaises(UniverseMismatchError): - self._make_one( - project=self.PROJECT, - credentials=tpc_creds, - client_options=client_options, - ) - mock_init_metrics.assert_not_called() - - def test_constructor_empty_universe_domain_and_precedence(self): - from google.api_core.universe import EmptyUniverseError - - gdu_creds = self._make_universe_credentials("googleapis.com") - tpc_creds = self._make_universe_credentials("tpc.example") - - for blank in ("", " "): - with mock.patch.dict(os.environ, {}, clear=False): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - os.environ.pop("SPANNER_EMULATOR_HOST", None) - with self.assertRaises(EmptyUniverseError): - self._make_one( - project=self.PROJECT, - credentials=gdu_creds, - client_options={"universe_domain": blank}, - ) - - with mock.patch.dict( - os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": blank}, clear=False - ): - os.environ.pop("SPANNER_EMULATOR_HOST", None) - with self.assertRaises(EmptyUniverseError): - self._make_one( - project=self.PROJECT, - credentials=gdu_creds, - ) - - # client_options.universe_domain takes precedence over env var. - with mock.patch.dict( - os.environ, - {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "other.example"}, - clear=False, - ): - os.environ.pop("SPANNER_EMULATOR_HOST", None) - client = self._make_one( - project=self.PROJECT, - credentials=tpc_creds, - client_options={"universe_domain": "tpc.example"}, - ) - self.assertEqual(client._client_options.universe_domain, "tpc.example") - - def test_constructor_universe_match_adc_and_api_endpoint_only(self): - from google.api_core.universe import UniverseMismatchError - - tpc_creds = self._make_universe_credentials("tpc.example") - - # Matching client_options.universe_domain succeeds. - with mock.patch.dict(os.environ, {}, clear=False): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - os.environ.pop("SPANNER_EMULATOR_HOST", None) - client = self._make_one( - project=self.PROJECT, - credentials=tpc_creds, - client_options={"universe_domain": "tpc.example"}, - ) - self.assertEqual(client._client_options.universe_domain, "tpc.example") - - # Matching GOOGLE_CLOUD_UNIVERSE_DOMAIN env var succeeds. - with mock.patch.dict( - os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.example"}, clear=False - ): - os.environ.pop("SPANNER_EMULATOR_HOST", None) - client = self._make_one(project=self.PROJECT, credentials=tpc_creds) - self.assertEqual(client.project, self.PROJECT) - - # ADC (credentials=None) mismatch raises UniverseMismatchError. - with ( - mock.patch.dict(os.environ, {}, clear=False), - mock.patch("google.auth.default", return_value=(tpc_creds, self.PROJECT)), - ): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - os.environ.pop("SPANNER_EMULATOR_HOST", None) - with self.assertRaises(UniverseMismatchError): - self._make_one(project=self.PROJECT) - - # api_endpoint-only TPC client without universe_domain fails closed. - with mock.patch.dict(os.environ, {}, clear=False): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - os.environ.pop("SPANNER_EMULATOR_HOST", None) - with self.assertRaises(UniverseMismatchError): - self._make_one( - project=self.PROJECT, - credentials=tpc_creds, - client_options={"api_endpoint": "spanner.tpc.example"}, - ) - - def test_constructor_skips_universe_validation_for_emulator_omni_anonymous(self): - from google.api_core.universe import UniverseMismatchError - - from google.cloud.spanner_v1.client import InstanceType - - gdu_creds = self._make_universe_credentials("googleapis.com") - # Contrast: without emulator/Omni/Anonymous, the same mismatched env fails closed. - with mock.patch.dict( - os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.example"}, clear=False - ): - os.environ.pop("SPANNER_EMULATOR_HOST", None) - with self.assertRaises(UniverseMismatchError): - self._make_one(project=self.PROJECT, credentials=gdu_creds) - with mock.patch.dict( - os.environ, - { - "GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.example", - "SPANNER_EMULATOR_HOST": "localhost:9010", - }, - clear=False, - ): - emu_client = self._make_one(project=self.PROJECT, credentials=gdu_creds) - self.assertEqual(emu_client._emulator_host, "localhost:9010") - - with mock.patch.dict( - os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "tpc.example"}, clear=False - ): - os.environ.pop("SPANNER_EMULATOR_HOST", None) - omni_client = self._make_one( - project=self.PROJECT, - client_options={"api_endpoint": "omni.host:15000"}, - instance_type=InstanceType.OMNI, - use_plain_text=True, - ) - self.assertEqual(omni_client._host, "omni.host:15000") - - anon_client = self._make_one( - project=self.PROJECT, - credentials=AnonymousCredentials(), - client_options={"api_endpoint": "localhost:9010"}, - ) - self.assertEqual(anon_client._emulator_host, "localhost:9010") - def test_copy_preserves_client_options_and_tls_without_mutating_original(self): from google.api_core.client_options import ClientOptions from google.api_core.gapic_v1 import client_info as client_info_lib @@ -873,7 +723,10 @@ def test_copy_clears_credential_options_and_handles_omni_and_anonymous(self): self.assertEqual(copied_file._host, "spanner.custom.example") # api_key in client_options is cleared on copy to avoid DuplicateCredentialArgs. - with mock.patch.dict(os.environ, {}, clear=False): + with ( + mock.patch.dict(os.environ, {}, clear=False), + mock.patch("google.auth.default", return_value=(gdu_creds, self.PROJECT)), + ): os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) os.environ.pop("SPANNER_EMULATOR_HOST", None) api_key_options = ClientOptions( @@ -900,6 +753,24 @@ def test_copy_clears_credential_options_and_handles_omni_and_anonymous(self): self.assertEqual(copied_omni._host, "omni.host:15000") self.assertTrue(copied_omni._use_plain_text) + # Omni via experimental_host with endpoint-less ClientOptions copies cleanly. + orig_omni_options = ClientOptions() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + omni_client_opts = self._make_one( + project=self.PROJECT, + experimental_host="omni.host:15000", + client_options=orig_omni_options, + use_plain_text=True, + ) + copied_omni_opts = omni_client_opts.copy() + self.assertEqual(copied_omni_opts.instance_type, InstanceType.OMNI) + self.assertEqual(copied_omni_opts._host, "omni.host:15000") + self.assertEqual( + copied_omni_opts._client_options.api_endpoint, "omni.host:15000" + ) + self.assertIsNone(orig_omni_options.api_endpoint) + # AnonymousCredentials + api_endpoint copies without AttributeError. anon_client = self._make_one( project=self.PROJECT, @@ -1562,7 +1433,7 @@ def test_client_passes_resolved_project_credentials_and_options_to_metrics( ): from google.cloud.spanner_v1 import client as MUT - creds = build_scoped_credentials(universe_domain="custom.universe") + creds = build_scoped_credentials() creds.project_id = "resolved-from-creds" MUT._metrics_monitor_initialized = False try: @@ -1630,7 +1501,7 @@ def test_client_custom_api_endpoint_with_monitoring_host_env( ): from google.cloud.spanner_v1 import client as MUT - creds = build_scoped_credentials(universe_domain="custom.universe") + creds = build_scoped_credentials() MUT._metrics_monitor_initialized = False try: MUT.Client( diff --git a/packages/google-cloud-spanner/tests/unit/test_instance.py b/packages/google-cloud-spanner/tests/unit/test_instance.py index 3811c17a8b6b..ac57c2e06ac5 100644 --- a/packages/google-cloud-spanner/tests/unit/test_instance.py +++ b/packages/google-cloud-spanner/tests/unit/test_instance.py @@ -93,47 +93,6 @@ def test_constructor_non_default(self): self.assertEqual(instance.display_name, DISPLAY_NAME) self.assertEqual(instance.labels, self.LABELS) - def test_copy_preserves_client_options(self): - import os - - from google.auth import credentials as ga_credentials - - from google.cloud.spanner_v1.client import Client - - class _UniverseCredentials(ga_credentials.Credentials): - def __init__(self, universe): - super().__init__() - self._universe_domain = universe - - def refresh(self, request): - self.token = "token" - - tpc_creds = _UniverseCredentials("tpc.example") - with mock.patch.dict( - os.environ, {"SPANNER_DISABLE_BUILTIN_METRICS": "true"}, clear=False - ): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - os.environ.pop("SPANNER_EMULATOR_HOST", None) - client = Client( - project=self.PROJECT, - credentials=tpc_creds, - client_options={ - "universe_domain": "tpc.example", - "api_endpoint": "spanner.tpc.example:443", - }, - ) - instance = self._make_one(self.INSTANCE_ID, client, self.CONFIG_NAME) - new_instance = instance.copy() - - self.assertIsNot(new_instance._client, client) - self.assertEqual( - new_instance._client._client_options.universe_domain, "tpc.example" - ) - self.assertEqual( - new_instance._client._client_options.api_endpoint, - "spanner.tpc.example:443", - ) - def test_copy(self): DISPLAY_NAME = "display_name" diff --git a/packages/google-cloud-spanner/tests/unit/test_metrics_exporter.py b/packages/google-cloud-spanner/tests/unit/test_metrics_exporter.py index 4be7d0ad6461..cf93fee5fef6 100644 --- a/packages/google-cloud-spanner/tests/unit/test_metrics_exporter.py +++ b/packages/google-cloud-spanner/tests/unit/test_metrics_exporter.py @@ -766,118 +766,3 @@ def test_init_adc_project_fallback_when_no_credentials(self): client=mock_client, credentials=None, ) - - def _make_universe_credentials(self, universe_domain="googleapis.com"): - class _UniverseCredentials(Credentials): - def __init__(self, universe): - super().__init__() - self._universe_domain = universe - - def refresh(self, request): - self.token = "token" - - return _UniverseCredentials(universe_domain) - - def test_init_universe_mismatch_explicit_and_adc(self): - """Verify mismatched credentials fail pre-init (explicit) and close transport (ADC).""" - from google.api_core.universe import UniverseMismatchError - - tpc_creds = self._make_universe_credentials("tpc.example") - - # Explicit mismatched credentials must raise before MetricServiceClient is built. - with ( - patch.dict(os.environ, {}, clear=False), - patch( - "google.cloud.spanner_v1.metrics.metrics_exporter.MetricServiceClient" - ) as mock_msc, - ): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - with self.assertRaises(UniverseMismatchError): - CloudMonitoringMetricsExporter( - project_id=PROJECT_ID, - credentials=tpc_creds, - ) - mock_msc.assert_not_called() - - # ADC (credentials=None) mismatch must validate transport._credentials and close it. - fake_client = MagicMock() - fake_client.transport._credentials = tpc_creds - with ( - patch.dict(os.environ, {}, clear=False), - patch( - "google.cloud.spanner_v1.metrics.metrics_exporter.MetricServiceClient", - return_value=fake_client, - ), - ): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - with self.assertRaises(UniverseMismatchError): - CloudMonitoringMetricsExporter( - project_id=PROJECT_ID, - credentials=None, - ) - fake_client.transport.close.assert_called_once() - - def test_init_universe_dict_options_matching_blank_and_exemptions(self): - """Verify dict/ClientOptions/env universe matching, dict mismatch, blank error, and skips.""" - from google.api_core.universe import ( - EmptyUniverseError, - UniverseMismatchError, - ) - - tpc_creds = self._make_universe_credentials("tpc.example") - - # Matching dict client_options succeeds. - with ( - patch.dict( - os.environ, - { - "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", - "GOOGLE_API_USE_MTLS_ENDPOINT": "never", - }, - clear=False, - ), - patch( - "google.cloud.spanner_v1.metrics.metrics_exporter." - "MetricServiceGrpcTransport.create_channel", - return_value=MagicMock(), - ), - ): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - exporter = CloudMonitoringMetricsExporter( - project_id=PROJECT_ID, - credentials=tpc_creds, - client_options={"universe_domain": "tpc.example"}, - ) - self.assertEqual(exporter.client.universe_domain, "tpc.example") - - # Mismatched dict client_options raises UniverseMismatchError. - with patch.dict(os.environ, {}, clear=False): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - with self.assertRaises(UniverseMismatchError): - CloudMonitoringMetricsExporter( - project_id=PROJECT_ID, - credentials=tpc_creds, - client_options={"universe_domain": "other.example"}, - ) - - # Blank universe_domain raises EmptyUniverseError. - with patch.dict(os.environ, {}, clear=False): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - with self.assertRaises(EmptyUniverseError): - CloudMonitoringMetricsExporter( - project_id=PROJECT_ID, - credentials=tpc_creds, - client_options={"universe_domain": " "}, - ) - - # Custom injected client skips validation even with mismatched credentials. - custom_client = MagicMock() - custom_client.common_project_path.return_value = f"projects/{PROJECT_ID}" - with patch.dict(os.environ, {}, clear=False): - os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) - exporter = CloudMonitoringMetricsExporter( - project_id=PROJECT_ID, - client=custom_client, - credentials=tpc_creds, - ) - self.assertIs(exporter.client, custom_client) From 6c448e69058c765db9c139d5790b49c1c588f206 Mon Sep 17 00:00:00 2001 From: Sakthivel Subramanian Date: Tue, 24 Nov 2026 18:05:32 +0000 Subject: [PATCH 4/4] Addressed comments --- .../google/cloud/spanner_v1/_async/client.py | 27 ++- .../google/cloud/spanner_v1/client.py | 27 ++- .../tests/unit/_async/test_client.py | 187 ++++++++++++----- .../tests/unit/test_client.py | 194 +++++++++++++----- 4 files changed, 314 insertions(+), 121 deletions(-) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/client.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/client.py index e5d14623ade0..7da2b7227f61 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/client.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/_async/client.py @@ -446,6 +446,7 @@ def __init__( "http://" in self._emulator_host or "https://" in self._emulator_host ): warnings.warn(_EMULATOR_HOST_HTTP_SCHEME) + self._disable_builtin_metrics = disable_builtin_metrics if ( _get_spanner_enable_builtin_metrics_env() and not disable_builtin_metrics @@ -705,24 +706,23 @@ def directed_read_options(self): """ return self._directed_read_options - def copy(self): + def copy(self) -> "Client": """Make a copy of this client. Copies local client configuration (including ``client_options``, - ``client_info``, ``instance_type``, and TLS settings) without copying - open RPC connections. Clears ``credentials_file`` and ``api_key`` on - the copied ``client_options`` because resolved credentials are passed - directly. + ``client_info``, ``query_options``, ``route_to_leader_enabled``, + ``directed_read_options``, ``observability_options``, + ``default_transaction_options``, ``disable_builtin_metrics``, + ``client_context``, ``instance_type``, and TLS settings) without + copying open RPC connections. Clears ``credentials_file`` and + ``api_key`` on the copied ``client_options`` because resolved + credentials are passed directly. :rtype: :class:`.Client` :returns: A copy of the current client. """ if not self._client_options: client_options = None - elif isinstance(self._client_options, dict): - client_options = google.api_core.client_options.from_dict( - self._client_options - ) else: client_options = copy.copy(self._client_options) @@ -737,7 +737,7 @@ def copy(self): client_options = google.api_core.client_options.ClientOptions( api_endpoint=self._host ) - elif not client_options.api_endpoint: + else: client_options.api_endpoint = self._host return self.__class__( @@ -745,6 +745,13 @@ def copy(self): credentials=self._credentials, client_info=self._client_info, client_options=client_options, + query_options=self._query_options, + route_to_leader_enabled=self._route_to_leader_enabled, + directed_read_options=copy.copy(self._directed_read_options), + observability_options=copy.copy(self._observability_options), + default_transaction_options=self._default_transaction_options, + disable_builtin_metrics=self._disable_builtin_metrics, + client_context=self._client_context, instance_type=self._instance_type, use_plain_text=self._use_plain_text, ca_certificate=self._ca_certificate, diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/client.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/client.py index c93bd427bf5f..b1df5773f4dd 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/client.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/client.py @@ -390,6 +390,7 @@ def __init__( "http://" in self._emulator_host or "https://" in self._emulator_host ): warnings.warn(_EMULATOR_HOST_HTTP_SCHEME) + self._disable_builtin_metrics = disable_builtin_metrics if ( _get_spanner_enable_builtin_metrics_env() and (not disable_builtin_metrics) @@ -591,23 +592,22 @@ def directed_read_options(self): :returns: The directed_read_options for the client.""" return self._directed_read_options - def copy(self): + def copy(self) -> "Client": """Make a copy of this client. Copies local client configuration (including ``client_options``, - ``client_info``, ``instance_type``, and TLS settings) without copying - open RPC connections. Clears ``credentials_file`` and ``api_key`` on - the copied ``client_options`` because resolved credentials are passed - directly. + ``client_info``, ``query_options``, ``route_to_leader_enabled``, + ``directed_read_options``, ``observability_options``, + ``default_transaction_options``, ``disable_builtin_metrics``, + ``client_context``, ``instance_type``, and TLS settings) without + copying open RPC connections. Clears ``credentials_file`` and + ``api_key`` on the copied ``client_options`` because resolved + credentials are passed directly. :rtype: :class:`.Client` :returns: A copy of the current client.""" if not self._client_options: client_options = None - elif isinstance(self._client_options, dict): - client_options = google.api_core.client_options.from_dict( - self._client_options - ) else: client_options = copy.copy(self._client_options) if client_options is not None: @@ -618,13 +618,20 @@ def copy(self): client_options = google.api_core.client_options.ClientOptions( api_endpoint=self._host ) - elif not client_options.api_endpoint: + else: client_options.api_endpoint = self._host return self.__class__( project=self.project, credentials=self._credentials, client_info=self._client_info, client_options=client_options, + query_options=self._query_options, + route_to_leader_enabled=self._route_to_leader_enabled, + directed_read_options=copy.copy(self._directed_read_options), + observability_options=copy.copy(self._observability_options), + default_transaction_options=self._default_transaction_options, + disable_builtin_metrics=self._disable_builtin_metrics, + client_context=self._client_context, instance_type=self._instance_type, use_plain_text=self._use_plain_text, ca_certificate=self._ca_certificate, diff --git a/packages/google-cloud-spanner/tests/unit/_async/test_client.py b/packages/google-cloud-spanner/tests/unit/_async/test_client.py index 72a334b6f046..db2e07e9a7d6 100644 --- a/packages/google-cloud-spanner/tests/unit/_async/test_client.py +++ b/packages/google-cloud-spanner/tests/unit/_async/test_client.py @@ -1057,96 +1057,128 @@ async def test_constructor_w_omni_explicit_credentials_instance(self): ) self.assertIs(client._credentials, creds) - def _make_universe_credentials(self, universe_domain="googleapis.com"): + def _make_credentials(self): from google.auth import credentials as ga_credentials - class _UniverseCredentials(ga_credentials.Credentials): - def __init__(self, universe): - super().__init__() - self._universe_domain = universe - - @property - def universe_domain(self): - return self._universe_domain - + class _TestCredentials(ga_credentials.Credentials): def refresh(self, request): self.token = "token" def with_quota_project(self, quota_project_id): return self - return _UniverseCredentials(universe_domain) + return _TestCredentials() @CrossSync.pytest - async def test_copy_preserves_client_options_and_tls_without_mutating_original( + async def test_copy_preserves_client_options_and_configuration_without_mutating_original( self, ): from google.api_core.client_options import ClientOptions from google.api_core.gapic_v1 import client_info as client_info_lib - tpc_creds = self._make_universe_credentials("tpc.example") + from google.cloud.spanner_v1._async import client as MUT + from google.cloud.spanner_v1.types import RequestOptions + + credentials = self._make_credentials() custom_info = client_info_lib.ClientInfo(user_agent="custom-agent/1.0") - orig_options = ClientOptions( - universe_domain="tpc.example", - api_endpoint="spanner.tpc.example:443", + original_options = ClientOptions( + universe_domain="custom.example", + api_endpoint="spanner.custom.example:443", quota_project_id="quota-proj", ) - with mock.patch.dict(os.environ, {}, clear=False): + original_observability_options = {"enable_extended_tracing": False} + original_directed_read_options = { + "include_replicas": { + "replica_selections": [{"location": "us-east1"}], + "auto_failover_disabled": True, + } + } + client_context = RequestOptions.ClientContext(secure_context={"key": "value"}) + + with ( + mock.patch.dict( + os.environ, + {"SPANNER_DISABLE_BUILTIN_METRICS": "false"}, + clear=False, + ), + mock.patch.object(MUT, "_initialize_metrics") as mock_initialize_metrics, + ): os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) os.environ.pop("SPANNER_EMULATOR_HOST", None) client = self._make_one( project=self.PROJECT, - credentials=tpc_creds, + credentials=credentials, client_info=custom_info, - client_options=orig_options, + client_options=original_options, + query_options={"optimizer_version": "4"}, + route_to_leader_enabled=False, + directed_read_options=original_directed_read_options, + observability_options=original_observability_options, + default_transaction_options=self.DEFAULT_TRANSACTION_OPTIONS, + disable_builtin_metrics=True, + client_context=client_context, use_plain_text=True, ca_certificate="/tmp/ca.pem", client_certificate="/tmp/cert.pem", client_key="/tmp/key.pem", ) + client._instance_admin_api = mock.Mock() + client._database_admin_api = mock.Mock() copied = client.copy() + mock_initialize_metrics.assert_not_called() self.assertIsNot(copied, client) - self.assertIsNot(copied._client_options, orig_options) - self.assertEqual(copied._client_options.universe_domain, "tpc.example") - self.assertEqual(copied._client_options.api_endpoint, "spanner.tpc.example:443") - self.assertEqual(copied._host, "spanner.tpc.example:443") + self.assertIsNot(copied._client_options, original_options) + self.assertEqual(copied._client_options.universe_domain, "custom.example") + self.assertEqual( + copied._client_options.api_endpoint, "spanner.custom.example:443" + ) + self.assertEqual(copied._client_options.quota_project_id, "quota-proj") + self.assertEqual(copied._host, "spanner.custom.example:443") self.assertIs(copied._client_info, custom_info) + self.assertEqual(copied._query_options, client._query_options) + self.assertFalse(copied.route_to_leader_enabled) + self.assertEqual(copied.directed_read_options, original_directed_read_options) + self.assertIsNot(copied.directed_read_options, original_directed_read_options) + self.assertEqual(copied._observability_options, original_observability_options) + self.assertIsNot(copied._observability_options, original_observability_options) + self.assertEqual( + copied.default_transaction_options, self.DEFAULT_TRANSACTION_OPTIONS + ) + self.assertTrue(copied._disable_builtin_metrics) + self.assertEqual(copied._client_context, client._client_context) self.assertTrue(copied._use_plain_text) self.assertEqual(copied._ca_certificate, "/tmp/ca.pem") self.assertEqual(copied._client_certificate, "/tmp/cert.pem") self.assertEqual(copied._client_key, "/tmp/key.pem") + self.assertIsNone(copied._instance_admin_api) + self.assertIsNone(copied._database_admin_api) - gdu_creds = self._make_universe_credentials("googleapis.com") with mock.patch.dict(os.environ, {}, clear=False): os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) os.environ.pop("SPANNER_EMULATOR_HOST", None) - empty_opt_client = self._make_one( - project=self.PROJECT, credentials=gdu_creds, client_options={} + empty_options_client = self._make_one( + project=self.PROJECT, credentials=credentials, client_options={} ) - copied_empty = empty_opt_client.copy() + copied_empty = empty_options_client.copy() self.assertIsNone(copied_empty._client_options) @CrossSync.pytest - async def test_copy_clears_credential_options_and_handles_omni_and_anonymous(self): - import warnings - + async def test_copy_clears_credential_options_without_mutating_original(self): from google.api_core.client_options import ClientOptions - from google.cloud.spanner_v1._async.client import InstanceType - - gdu_creds = self._make_universe_credentials("googleapis.com") + credentials = self._make_credentials() with ( mock.patch.dict(os.environ, {}, clear=False), mock.patch( "google.auth.load_credentials_from_file", - return_value=(gdu_creds, self.PROJECT), + return_value=(credentials, self.PROJECT), ), ): os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) os.environ.pop("SPANNER_EMULATOR_HOST", None) file_options = ClientOptions( - credentials_file="/tmp/fake-creds.json", + credentials_file="/tmp/fake-credentials.json", api_endpoint="spanner.custom.example", ) client_from_file = self._make_one( @@ -1154,12 +1186,14 @@ async def test_copy_clears_credential_options_and_handles_omni_and_anonymous(sel ) copied_file = client_from_file.copy() self.assertIsNone(copied_file._client_options.credentials_file) - self.assertEqual(file_options.credentials_file, "/tmp/fake-creds.json") + self.assertEqual( + file_options.credentials_file, "/tmp/fake-credentials.json" + ) self.assertEqual(copied_file._host, "spanner.custom.example") with ( mock.patch.dict(os.environ, {}, clear=False), - mock.patch("google.auth.default", return_value=(gdu_creds, self.PROJECT)), + mock.patch("google.auth.default", return_value=(credentials, self.PROJECT)), ): os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) os.environ.pop("SPANNER_EMULATOR_HOST", None) @@ -1174,6 +1208,41 @@ async def test_copy_clears_credential_options_and_handles_omni_and_anonymous(sel self.assertIsNone(copied_api_key._client_options.api_key) self.assertEqual(api_key_options.api_key, "test-api-key") + @CrossSync.pytest + async def test_copy_preserves_omni_configuration(self): + import warnings + + from google.api_core.client_options import ClientOptions + + from google.cloud.spanner_v1._async.client import InstanceType + from google.cloud.spanner_v1.omni.credentials import ( + SpannerOmniCredentials, + ) + + standard_omni_client = self._make_one( + project=self.PROJECT, + instance_type=InstanceType.OMNI, + client_options={"api_endpoint": "omni.host:15000"}, + username="omni_user", + password="omni_password", + ca_certificate="/tmp/omni-ca.pem", + client_certificate="/tmp/omni-cert.pem", + client_key="/tmp/omni-key.pem", + ) + copied_standard_omni = standard_omni_client.copy() + self.assertEqual(copied_standard_omni.instance_type, InstanceType.OMNI) + self.assertEqual(copied_standard_omni._host, "omni.host:15000") + self.assertEqual( + copied_standard_omni._client_options.api_endpoint, "omni.host:15000" + ) + self.assertIsInstance(copied_standard_omni._credentials, SpannerOmniCredentials) + self.assertIs( + copied_standard_omni._credentials, standard_omni_client._credentials + ) + self.assertEqual(copied_standard_omni._ca_certificate, "/tmp/omni-ca.pem") + self.assertEqual(copied_standard_omni._client_certificate, "/tmp/omni-cert.pem") + self.assertEqual(copied_standard_omni._client_key, "/tmp/omni-key.pem") + with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) omni_client = self._make_one( @@ -1184,30 +1253,50 @@ async def test_copy_clears_credential_options_and_handles_omni_and_anonymous(sel copied_omni = omni_client.copy() self.assertEqual(copied_omni.instance_type, InstanceType.OMNI) self.assertEqual(copied_omni._host, "omni.host:15000") + self.assertEqual(copied_omni._client_options.api_endpoint, "omni.host:15000") self.assertTrue(copied_omni._use_plain_text) - orig_omni_options = ClientOptions() + original_omni_options = ClientOptions() with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) - omni_client_opts = self._make_one( + omni_client_options = self._make_one( project=self.PROJECT, experimental_host="omni.host:15000", - client_options=orig_omni_options, + client_options=original_omni_options, use_plain_text=True, ) - copied_omni_opts = omni_client_opts.copy() - self.assertEqual(copied_omni_opts.instance_type, InstanceType.OMNI) - self.assertEqual(copied_omni_opts._host, "omni.host:15000") + copied_omni_options = omni_client_options.copy() + self.assertEqual(copied_omni_options.instance_type, InstanceType.OMNI) + self.assertEqual(copied_omni_options._host, "omni.host:15000") self.assertEqual( - copied_omni_opts._client_options.api_endpoint, "omni.host:15000" + copied_omni_options._client_options.api_endpoint, "omni.host:15000" ) - self.assertIsNone(orig_omni_options.api_endpoint) + self.assertIsNone(original_omni_options.api_endpoint) - anon_client = self._make_one( + conflicting_omni_options = ClientOptions(api_endpoint="other.host:443") + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + conflicting_omni_client = self._make_one( + project=self.PROJECT, + experimental_host="omni.host:15000", + client_options=conflicting_omni_options, + use_plain_text=True, + ) + copied_conflicting_omni = conflicting_omni_client.copy() + self.assertEqual(copied_conflicting_omni._host, "omni.host:15000") + self.assertEqual( + copied_conflicting_omni._client_options.api_endpoint, + "omni.host:15000", + ) + self.assertEqual(conflicting_omni_options.api_endpoint, "other.host:443") + + @CrossSync.pytest + async def test_copy_preserves_anonymous_credentials_client(self): + anonymous_client = self._make_one( project=self.PROJECT, credentials=AnonymousCredentials(), client_options={"api_endpoint": "localhost:9010"}, ) - copied_anon = anon_client.copy() - self.assertEqual(copied_anon._emulator_host, "localhost:9010") - self.assertEqual(copied_anon._host, "localhost:9010") + copied_anonymous = anonymous_client.copy() + self.assertEqual(copied_anonymous._emulator_host, "localhost:9010") + self.assertEqual(copied_anonymous._host, "localhost:9010") diff --git a/packages/google-cloud-spanner/tests/unit/test_client.py b/packages/google-cloud-spanner/tests/unit/test_client.py index 4cbb1c2326d1..a75a4b96a7c3 100644 --- a/packages/google-cloud-spanner/tests/unit/test_client.py +++ b/packages/google-cloud-spanner/tests/unit/test_client.py @@ -625,93 +625,127 @@ def test_copy(self): self.assertIs(new_client._credentials, client._credentials) self.assertEqual(new_client.project, client.project) - def _make_universe_credentials(self, universe_domain="googleapis.com"): + def _make_credentials(self): from google.auth import credentials as ga_credentials - class _UniverseCredentials(ga_credentials.Credentials): - def __init__(self, universe): - super().__init__() - self._universe_domain = universe - - @property - def universe_domain(self): - return self._universe_domain - + class _TestCredentials(ga_credentials.Credentials): def refresh(self, request): self.token = "token" def with_quota_project(self, quota_project_id): return self - return _UniverseCredentials(universe_domain) + return _TestCredentials() - def test_copy_preserves_client_options_and_tls_without_mutating_original(self): + def test_copy_preserves_client_options_and_configuration_without_mutating_original( + self, + ): from google.api_core.client_options import ClientOptions from google.api_core.gapic_v1 import client_info as client_info_lib - tpc_creds = self._make_universe_credentials("tpc.example") + from google.cloud.spanner_v1 import client as MUT + from google.cloud.spanner_v1.types import RequestOptions + + credentials = self._make_credentials() custom_info = client_info_lib.ClientInfo(user_agent="custom-agent/1.0") - orig_options = ClientOptions( - universe_domain="tpc.example", - api_endpoint="spanner.tpc.example:443", + original_options = ClientOptions( + universe_domain="custom.example", + api_endpoint="spanner.custom.example:443", quota_project_id="quota-proj", ) - with mock.patch.dict(os.environ, {}, clear=False): + original_observability_options = {"enable_extended_tracing": False} + original_directed_read_options = { + "include_replicas": { + "replica_selections": [{"location": "us-east1"}], + "auto_failover_disabled": True, + } + } + client_context = RequestOptions.ClientContext(secure_context={"key": "value"}) + + with ( + mock.patch.dict( + os.environ, + {"SPANNER_DISABLE_BUILTIN_METRICS": "false"}, + clear=False, + ), + mock.patch.object(MUT, "_initialize_metrics") as mock_initialize_metrics, + ): os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) os.environ.pop("SPANNER_EMULATOR_HOST", None) client = self._make_one( project=self.PROJECT, - credentials=tpc_creds, + credentials=credentials, client_info=custom_info, - client_options=orig_options, + client_options=original_options, + query_options={"optimizer_version": "4"}, + route_to_leader_enabled=False, + directed_read_options=original_directed_read_options, + observability_options=original_observability_options, + default_transaction_options=self.DEFAULT_TRANSACTION_OPTIONS, + disable_builtin_metrics=True, + client_context=client_context, use_plain_text=True, ca_certificate="/tmp/ca.pem", client_certificate="/tmp/cert.pem", client_key="/tmp/key.pem", ) + client._instance_admin_api = mock.Mock() + client._database_admin_api = mock.Mock() copied = client.copy() + mock_initialize_metrics.assert_not_called() self.assertIsNot(copied, client) - self.assertIsNot(copied._client_options, orig_options) - self.assertEqual(copied._client_options.universe_domain, "tpc.example") - self.assertEqual(copied._client_options.api_endpoint, "spanner.tpc.example:443") - self.assertEqual(copied._host, "spanner.tpc.example:443") + self.assertIsNot(copied._client_options, original_options) + self.assertEqual(copied._client_options.universe_domain, "custom.example") + self.assertEqual( + copied._client_options.api_endpoint, "spanner.custom.example:443" + ) + self.assertEqual(copied._client_options.quota_project_id, "quota-proj") + self.assertEqual(copied._host, "spanner.custom.example:443") self.assertIs(copied._client_info, custom_info) + self.assertEqual(copied._query_options, client._query_options) + self.assertFalse(copied.route_to_leader_enabled) + self.assertEqual(copied.directed_read_options, original_directed_read_options) + self.assertIsNot(copied.directed_read_options, original_directed_read_options) + self.assertEqual(copied._observability_options, original_observability_options) + self.assertIsNot(copied._observability_options, original_observability_options) + self.assertEqual( + copied.default_transaction_options, self.DEFAULT_TRANSACTION_OPTIONS + ) + self.assertTrue(copied._disable_builtin_metrics) + self.assertEqual(copied._client_context, client._client_context) self.assertTrue(copied._use_plain_text) self.assertEqual(copied._ca_certificate, "/tmp/ca.pem") self.assertEqual(copied._client_certificate, "/tmp/cert.pem") self.assertEqual(copied._client_key, "/tmp/key.pem") + self.assertIsNone(copied._instance_admin_api) + self.assertIsNone(copied._database_admin_api) # Empty dict client_options copies cleanly without error. - gdu_creds = self._make_universe_credentials("googleapis.com") with mock.patch.dict(os.environ, {}, clear=False): os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) os.environ.pop("SPANNER_EMULATOR_HOST", None) - empty_opt_client = self._make_one( - project=self.PROJECT, credentials=gdu_creds, client_options={} + empty_options_client = self._make_one( + project=self.PROJECT, credentials=credentials, client_options={} ) - copied_empty = empty_opt_client.copy() + copied_empty = empty_options_client.copy() self.assertIsNone(copied_empty._client_options) - def test_copy_clears_credential_options_and_handles_omni_and_anonymous(self): - import warnings - + def test_copy_clears_credential_options_without_mutating_original(self): from google.api_core.client_options import ClientOptions - from google.cloud.spanner_v1.client import InstanceType - - gdu_creds = self._make_universe_credentials("googleapis.com") + credentials = self._make_credentials() with ( mock.patch.dict(os.environ, {}, clear=False), mock.patch( "google.auth.load_credentials_from_file", - return_value=(gdu_creds, self.PROJECT), + return_value=(credentials, self.PROJECT), ), ): os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) os.environ.pop("SPANNER_EMULATOR_HOST", None) file_options = ClientOptions( - credentials_file="/tmp/fake-creds.json", + credentials_file="/tmp/fake-credentials.json", api_endpoint="spanner.custom.example", ) client_from_file = self._make_one( @@ -719,13 +753,15 @@ def test_copy_clears_credential_options_and_handles_omni_and_anonymous(self): ) copied_file = client_from_file.copy() self.assertIsNone(copied_file._client_options.credentials_file) - self.assertEqual(file_options.credentials_file, "/tmp/fake-creds.json") + self.assertEqual( + file_options.credentials_file, "/tmp/fake-credentials.json" + ) self.assertEqual(copied_file._host, "spanner.custom.example") # api_key in client_options is cleared on copy to avoid DuplicateCredentialArgs. with ( mock.patch.dict(os.environ, {}, clear=False), - mock.patch("google.auth.default", return_value=(gdu_creds, self.PROJECT)), + mock.patch("google.auth.default", return_value=(credentials, self.PROJECT)), ): os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) os.environ.pop("SPANNER_EMULATOR_HOST", None) @@ -740,7 +776,42 @@ def test_copy_clears_credential_options_and_handles_omni_and_anonymous(self): self.assertIsNone(copied_api_key._client_options.api_key) self.assertEqual(api_key_options.api_key, "test-api-key") - # Omni via deprecated experimental_host (with _client_options=None) copies cleanly. + def test_copy_preserves_omni_configuration(self): + import warnings + + from google.api_core.client_options import ClientOptions + + from google.cloud.spanner_v1.client import InstanceType + from google.cloud.spanner_v1.omni.credentials import ( + SpannerOmniCredentials, + ) + + # Standard Omni client with api_endpoint, username/password, and TLS certs. + standard_omni_client = self._make_one( + project=self.PROJECT, + instance_type=InstanceType.OMNI, + client_options={"api_endpoint": "omni.host:15000"}, + username="omni_user", + password="omni_password", + ca_certificate="/tmp/omni-ca.pem", + client_certificate="/tmp/omni-cert.pem", + client_key="/tmp/omni-key.pem", + ) + copied_standard_omni = standard_omni_client.copy() + self.assertEqual(copied_standard_omni.instance_type, InstanceType.OMNI) + self.assertEqual(copied_standard_omni._host, "omni.host:15000") + self.assertEqual( + copied_standard_omni._client_options.api_endpoint, "omni.host:15000" + ) + self.assertIsInstance(copied_standard_omni._credentials, SpannerOmniCredentials) + self.assertIs( + copied_standard_omni._credentials, standard_omni_client._credentials + ) + self.assertEqual(copied_standard_omni._ca_certificate, "/tmp/omni-ca.pem") + self.assertEqual(copied_standard_omni._client_certificate, "/tmp/omni-cert.pem") + self.assertEqual(copied_standard_omni._client_key, "/tmp/omni-key.pem") + + # Omni via deprecated experimental_host with client_options=None. with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) omni_client = self._make_one( @@ -751,35 +822,54 @@ def test_copy_clears_credential_options_and_handles_omni_and_anonymous(self): copied_omni = omni_client.copy() self.assertEqual(copied_omni.instance_type, InstanceType.OMNI) self.assertEqual(copied_omni._host, "omni.host:15000") + self.assertEqual(copied_omni._client_options.api_endpoint, "omni.host:15000") self.assertTrue(copied_omni._use_plain_text) - # Omni via experimental_host with endpoint-less ClientOptions copies cleanly. - orig_omni_options = ClientOptions() + # Omni via experimental_host with endpoint-less ClientOptions. + original_omni_options = ClientOptions() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + omni_client_options = self._make_one( + project=self.PROJECT, + experimental_host="omni.host:15000", + client_options=original_omni_options, + use_plain_text=True, + ) + copied_omni_options = omni_client_options.copy() + self.assertEqual(copied_omni_options.instance_type, InstanceType.OMNI) + self.assertEqual(copied_omni_options._host, "omni.host:15000") + self.assertEqual( + copied_omni_options._client_options.api_endpoint, "omni.host:15000" + ) + self.assertIsNone(original_omni_options.api_endpoint) + + # experimental_host takes precedence over client_options.api_endpoint on copy. + conflicting_omni_options = ClientOptions(api_endpoint="other.host:443") with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) - omni_client_opts = self._make_one( + conflicting_omni_client = self._make_one( project=self.PROJECT, experimental_host="omni.host:15000", - client_options=orig_omni_options, + client_options=conflicting_omni_options, use_plain_text=True, ) - copied_omni_opts = omni_client_opts.copy() - self.assertEqual(copied_omni_opts.instance_type, InstanceType.OMNI) - self.assertEqual(copied_omni_opts._host, "omni.host:15000") + copied_conflicting_omni = conflicting_omni_client.copy() + self.assertEqual(copied_conflicting_omni._host, "omni.host:15000") self.assertEqual( - copied_omni_opts._client_options.api_endpoint, "omni.host:15000" + copied_conflicting_omni._client_options.api_endpoint, + "omni.host:15000", ) - self.assertIsNone(orig_omni_options.api_endpoint) + self.assertEqual(conflicting_omni_options.api_endpoint, "other.host:443") - # AnonymousCredentials + api_endpoint copies without AttributeError. - anon_client = self._make_one( + def test_copy_preserves_anonymous_credentials_client(self): + anonymous_client = self._make_one( project=self.PROJECT, credentials=AnonymousCredentials(), client_options={"api_endpoint": "localhost:9010"}, ) - copied_anon = anon_client.copy() - self.assertEqual(copied_anon._emulator_host, "localhost:9010") - self.assertEqual(copied_anon._host, "localhost:9010") + copied_anonymous = anonymous_client.copy() + self.assertEqual(copied_anonymous._emulator_host, "localhost:9010") + self.assertEqual(copied_anonymous._host, "localhost:9010") def test_credentials_property(self): credentials = build_scoped_credentials()