diff --git a/packages/google-cloud-bigquery/google/cloud/bigquery/_arrow_query.py b/packages/google-cloud-bigquery/google/cloud/bigquery/_arrow_query.py index 7508e7a0836f..8c17b37be871 100644 --- a/packages/google-cloud-bigquery/google/cloud/bigquery/_arrow_query.py +++ b/packages/google-cloud-bigquery/google/cloud/bigquery/_arrow_query.py @@ -17,11 +17,9 @@ from __future__ import annotations import base64 -from typing import Any, Dict, Iterator, Optional, Sequence, Tuple, TYPE_CHECKING +from typing import TYPE_CHECKING, Any, Dict, Iterator, Optional, Sequence, Tuple -from google.cloud.bigquery import _versions_helpers -from google.cloud.bigquery import enums -from google.cloud.bigquery import exceptions +from google.cloud.bigquery import _versions_helpers, enums, exceptions try: import pyarrow # type: ignore @@ -303,6 +301,12 @@ def download_arrow_from_job( raise ValueError("RowIterator client is None.") bqstorage_client = row_iterator.client._get_shared_bqstorage_client() if bqstorage_client is None: + if getattr(row_iterator.client, "_has_custom_api_endpoint", False): + raise ValueError( + "Cannot read multi-page Arrow results with a custom BigQuery " + "api_endpoint or BIGQUERY_EMULATOR_HOST without an explicit " + "bqstorage_client." + ) raise ValueError( "The google-cloud-bigquery-storage library is required to read Arrow results." ) diff --git a/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py b/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py index 00a2ef25605c..31c7186ae631 100644 --- a/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py +++ b/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py @@ -15,27 +15,43 @@ """Shared helper functions for BigQuery API classes.""" import base64 +import copy import datetime import decimal import json import math -import re import os +import re import textwrap import warnings +from collections.abc import Mapping from typing import Any, Optional, Tuple, Type, Union from dateutil import relativedelta -from google.cloud._helpers import UTC # type: ignore -from google.cloud._helpers import _date_from_iso8601_date -from google.cloud._helpers import _datetime_from_microseconds -from google.cloud._helpers import _RFC3339_MICROS -from google.cloud._helpers import _RFC3339_NO_FRACTION -from google.cloud._helpers import _to_bytes +from google.api_core import client_options as client_options_lib +from google.api_core.universe import UniverseMismatchError +from google.auth import compute_engine +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud._helpers import ( + _RFC3339_MICROS, + _RFC3339_NO_FRACTION, + UTC, # type: ignore + _date_from_iso8601_date, + _datetime_from_microseconds, + _to_bytes, +) + from google.cloud.bigquery import enums -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import client_options as client_options_lib +try: + from google.auth.aio import credentials as _aio_credentials + + _ANONYMOUS_CREDENTIAL_TYPES: tuple[type[Any], ...] = ( + ga_credentials.AnonymousCredentials, + _aio_credentials.AnonymousCredentials, + ) +except ImportError: # pragma: NO COVER + _ANONYMOUS_CREDENTIAL_TYPES = (ga_credentials.AnonymousCredentials,) TimeoutType = Union[float, None] @@ -77,7 +93,7 @@ def _get_client_universe( - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] + client_options: client_options_lib.ClientOptions | Mapping[str, Any] | None, ) -> str: """Retrieves the specified universe setting. @@ -87,7 +103,7 @@ def _get_client_universe( str: resolved universe setting. """ - if isinstance(client_options, dict): + if isinstance(client_options, Mapping): client_options = client_options_lib.from_dict(client_options) universe = _DEFAULT_UNIVERSE options_universe = getattr(client_options, "universe_domain", None) @@ -104,27 +120,77 @@ def _get_client_universe( return universe -def _validate_universe(client_universe: str, credentials: ga_credentials.Credentials): +# TODO(universe-domain): Replace with google.api_core.universe.validate_credentials_universe +# once minimum allowed google-api-core version exceeds 2.44.0. +def _validate_universe( + client_universe: str, credentials: ga_credentials.Credentials | None +) -> None: """Validates that client provided universe and universe embedded in credentials match. Args: client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. + credentials (ga_credentials.Credentials | None): The credentials being + used in the client. Validation is skipped when ``None``, + ``AnonymousCredentials`` (sync or async), or uncached + ``compute_engine.Credentials``. Raises: - ValueError: when client_universe does not match the universe in credentials. + google.api_core.universe.UniverseMismatchError: (subclass of ``ValueError``) + when ``client_universe`` does not match the universe in ``credentials``. """ - if hasattr(credentials, "universe_domain"): - cred_universe = getattr(credentials, "universe_domain") - if isinstance(cred_universe, str): - if client_universe != cred_universe: - raise ValueError( - "The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({cred_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{_DEFAULT_UNIVERSE}` is the default." - ) + if credentials is None or isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES): + return + if isinstance(credentials, compute_engine.Credentials) and not getattr( + credentials, "_universe_domain_cached", False + ): + return + cred_universe = getattr(credentials, "universe_domain", None) + if isinstance(cred_universe, str) and client_universe != cred_universe: + raise UniverseMismatchError(client_universe, cred_universe) + + +def _inherit_universe_in_client_options( + parent_universe: str, + client_options: client_options_lib.ClientOptions | Mapping[str, Any] | None = None, +) -> client_options_lib.ClientOptions | None: + """Inherit parent universe domain when child client_options leaves it unset. + + Caller-supplied mappings and ``ClientOptions`` instances are not mutated. + + Args: + parent_universe: The resolved universe domain of the parent client. + client_options: Optional child client options mapping or object. + When ``None``, a new ``ClientOptions`` is created only if + inheritance is needed. + + Returns: + A ``ClientOptions`` instance with ``universe_domain`` populated when + needed, or ``None`` when ``client_options`` is ``None`` and the + parent uses the default universe with no overriding env var. + """ + should_inherit = ( + parent_universe != _DEFAULT_UNIVERSE + or _get_client_universe(None) != parent_universe + ) + if client_options is None: + if should_inherit: + return client_options_lib.ClientOptions(universe_domain=parent_universe) + return None + if isinstance(client_options, Mapping): + opts = client_options_lib.from_dict(client_options) + if not opts.universe_domain and (should_inherit or opts.universe_domain == ""): + opts.universe_domain = parent_universe + return opts + if isinstance(client_options, client_options_lib.ClientOptions): + if not client_options.universe_domain and ( + should_inherit or client_options.universe_domain == "" + ): + opts = copy.copy(client_options) + opts.universe_domain = parent_universe + return opts + return client_options + # Preserve non-ClientOptions objects (such as unittest.mock sentinels in caller tests). + return client_options def _get_bigquery_host(): @@ -648,7 +714,7 @@ def _range_field_to_json(range_element_type, value): end = value.get("end") else: raise ValueError( - f"Unsupported type of RANGE value {value}, must be " "string or dict" + f"Unsupported type of RANGE value {value}, must be string or dict" ) start = _range_element_to_json(start, range_element_type) diff --git a/packages/google-cloud-bigquery/google/cloud/bigquery/client.py b/packages/google-cloud-bigquery/google/cloud/bigquery/client.py index 72f7e4bf3dd4..33ab933260a4 100644 --- a/packages/google-cloud-bigquery/google/cloud/bigquery/client.py +++ b/packages/google-cloud-bigquery/google/cloud/bigquery/client.py @@ -49,11 +49,9 @@ import google.api_core.exceptions as core_exceptions import google.cloud._helpers # type: ignore import requests -from google import resumable_media # type: ignore from google.api_core import page_iterator from google.api_core import retry as retries from google.api_core.iam import Policy -from google.cloud import exceptions # pytype: disable=import-error from google.cloud.client import ( ClientWithProject, # type: ignore # pytype: disable=import-error ) @@ -62,6 +60,9 @@ ResumableUpload, ) +from google import resumable_media # type: ignore +from google.cloud import exceptions # pytype: disable=import-error + try: from google.cloud.bigquery_storage_v1.services.big_query_read.client import ( DEFAULT_CLIENT_INFO as DEFAULT_BQSTORAGE_CLIENT_INFO, @@ -71,6 +72,7 @@ from google.auth.credentials import Credentials + from google.cloud.bigquery import ( _job_helpers, _pandas_helpers, @@ -90,6 +92,7 @@ _get_bigquery_host, _get_client_universe, _get_sub_prop, + _inherit_universe_in_client_options, _record_field_to_json, _str_or_none, _validate_universe, @@ -133,9 +136,9 @@ ) pyarrow = _versions_helpers.PYARROW_VERSIONS.try_import() -pandas = ( - _versions_helpers.PANDAS_VERSIONS.try_import() -) # mypy check fails because pandas import is outside module, there are type: ignore comments related to this +# mypy check fails because pandas import is outside module; related +# `type: ignore` comments appear below. +pandas = _versions_helpers.PANDAS_VERSIONS.try_import() ResumableTimeoutType = Union[ @@ -143,6 +146,9 @@ ] # for resumable media methods if typing.TYPE_CHECKING: # pragma: NO COVER + import google.api_core.gapic_v1.client_info + import google.cloud.bigquery_storage + PathType = Union[str, bytes, os.PathLike[str], os.PathLike[bytes], io.IOBase] _DEFAULT_CHUNKSIZE = 100 * 1024 * 1024 # 100 MB _MAX_MULTIPART_SIZE = 5 * 1024 * 1024 @@ -295,13 +301,13 @@ def __init__( default_load_job_config: Optional[LoadJobConfig] = None, client_info: Optional[google.api_core.client_info.ClientInfo] = None, client_options: Optional[ - Union[google.api_core.client_options.ClientOptions, Dict[str, Any]] + Union[google.api_core.client_options.ClientOptions, Mapping[str, Any]] ] = None, default_job_creation_mode: Optional[str] = None, ) -> None: if client_options is None: client_options = {} - if isinstance(client_options, dict): + if isinstance(client_options, Mapping): client_options = google.api_core.client_options.from_dict(client_options) # assert isinstance(client_options, google.api_core.client_options.ClientOptions) @@ -314,23 +320,26 @@ def __init__( kw_args: Dict[str, Any] = {"client_info": client_info} bq_host = _get_bigquery_host() - kw_args["api_endpoint"] = bq_host if bq_host != _DEFAULT_HOST else None - client_universe = None + has_emulator_endpoint = bool(bq_host) and bq_host.rstrip("/") != _DEFAULT_HOST + kw_args["api_endpoint"] = bq_host if has_emulator_endpoint else None + client_universe = _get_client_universe(client_options) + default_universe_endpoint = _DEFAULT_HOST_TEMPLATE.replace( + "{UNIVERSE_DOMAIN}", client_universe + ) if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - kw_args["api_endpoint"] = api_endpoint - else: - client_universe = _get_client_universe(client_options) - if client_universe != _DEFAULT_UNIVERSE: - kw_args["api_endpoint"] = _DEFAULT_HOST_TEMPLATE.replace( - "{UNIVERSE_DOMAIN}", client_universe - ) - # Ensure credentials and universe are not in conflict. - if hasattr(self, "_credentials") and client_universe is not None: - _validate_universe(client_universe, self._credentials) + kw_args["api_endpoint"] = client_options.api_endpoint + elif not has_emulator_endpoint and client_universe != _DEFAULT_UNIVERSE: + kw_args["api_endpoint"] = default_universe_endpoint + # Ensure credentials and universe are not in conflict, even when + # client_options.api_endpoint is set. + _validate_universe(client_universe, getattr(self, "_credentials", None)) self._connection = Connection(self, **kw_args) - self._universe_domain = _get_client_universe(client_options) + self._universe_domain = client_universe + effective_base_url = self._connection.API_BASE_URL or _DEFAULT_HOST + self._has_custom_api_endpoint = ( + effective_base_url.rstrip("/") != default_universe_endpoint + ) self._location = location self._default_load_job_config = copy.deepcopy(default_load_job_config) self.default_job_creation_mode = default_job_creation_mode @@ -350,6 +359,11 @@ def location(self): """Default location for jobs / datasets / tables.""" return self._location + @property + def universe_domain(self) -> str: + """The universe domain used by the client instance.""" + return self._universe_domain + @property def default_job_creation_mode(self): """Default job creation mode used for query execution.""" @@ -643,15 +657,15 @@ def dataset( def _ensure_bqstorage_client( self, - bqstorage_client: Optional[ - "google.cloud.bigquery_storage.BigQueryReadClient" - ] = None, - client_options: Optional[google.api_core.client_options.ClientOptions] = None, - client_info: Optional[ - "google.api_core.gapic_v1.client_info.ClientInfo" - ] = DEFAULT_BQSTORAGE_CLIENT_INFO, - transport: Optional[Callable[..., Any]] = None, - ) -> Optional["google.cloud.bigquery_storage.BigQueryReadClient"]: + bqstorage_client: google.cloud.bigquery_storage.BigQueryReadClient + | None = None, + client_options: google.api_core.client_options.ClientOptions + | Mapping[str, Any] + | None = None, + client_info: google.api_core.gapic_v1.client_info.ClientInfo + | None = DEFAULT_BQSTORAGE_CLIENT_INFO, + transport: Callable[..., Any] | None = None, + ) -> google.cloud.bigquery_storage.BigQueryReadClient | None: """Create a BigQuery Storage API client using this client's credentials. Args: @@ -660,8 +674,8 @@ def _ensure_bqstorage_client( instance is created and returned. client_options: Custom options used with a new BigQuery Storage client instance - if one is created. If ``None``, the new client uses this - client's universe domain. + if one is created. If ``None`` or its ``universe_domain`` is + unset, the new client inherits this client's universe domain. client_info: The client info used with a new BigQuery Storage client instance if one is created. @@ -670,7 +684,15 @@ def _ensure_bqstorage_client( client instance. If ``None``, the default transport is used. Returns: - A BigQuery Storage API client. + A BigQuery Storage API client, or ``None`` if + ``google-cloud-bigquery-storage`` is missing/outdated or if a + custom BigQuery endpoint is configured without an explicit + BigQuery Storage ``api_endpoint``. + + Raises: + google.api_core.universe.UniverseMismatchError: If ``client_options`` + specifies a ``universe_domain`` that conflicts with this + client's credentials. """ try: @@ -731,10 +753,24 @@ def _ensure_bqstorage_client( ) if bqstorage_client is None: - if client_options is None and self._universe_domain != _DEFAULT_UNIVERSE: - # Without this, the BigQuery Storage client uses googleapis.com. - client_options = google.api_core.client_options.ClientOptions( - universe_domain=self._universe_domain + client_options = _inherit_universe_in_client_options( + self._universe_domain, client_options + ) + if self._has_custom_api_endpoint and not getattr( + client_options, "api_endpoint", None + ): + warnings.warn( + "Cannot create a BigQuery Storage client when a custom BigQuery " + "api_endpoint or BIGQUERY_EMULATOR_HOST is configured without an " + "explicit BigQuery Storage api_endpoint (or matching " + "universe_domain on Client); falling back to REST.", + UserWarning, + stacklevel=2, + ) + return None + if isinstance(client_options, google.api_core.client_options.ClientOptions): + _validate_universe( + _get_client_universe(client_options), self._credentials ) bqstorage_client = bigquery_storage.BigQueryReadClient( credentials=self._credentials, @@ -758,7 +794,8 @@ def _get_shared_bqstorage_client( Returns: A BigQuery Storage API client, or ``None`` if - google-cloud-bigquery-storage is missing or outdated. + ``google-cloud-bigquery-storage`` is missing/outdated or cannot be + configured for a custom BigQuery endpoint. """ with self._shared_bqstorage_client_lock: if self._shared_bqstorage_client is None: diff --git a/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py b/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py new file mode 100644 index 000000000000..04cc11618cff --- /dev/null +++ b/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py @@ -0,0 +1,786 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Universe-domain conformance and BigQuery Storage sub-client routing tests.""" + +from types import MappingProxyType +from typing import Any +from unittest import mock + +import google.auth +import pytest +import requests +from google.api_core import client_options as client_options_lib +from google.api_core.universe import UniverseMismatchError +from google.auth import compute_engine +from google.auth import credentials as auth_credentials + +from google.cloud import bigquery +from google.cloud.bigquery import _helpers, dbapi, schema +from google.cloud.bigquery import table as bq_table + +DEFAULT_PROJECT_ID = "test-proj" +DEFAULT_DATASET_ID = "ds" +DEFAULT_TABLE_ID = "tbl" +DEFAULT_UNIVERSE = "googleapis.com" +TPC_UNIVERSE = "apis-tpclp.goog" +OTHER_TPC_UNIVERSE = "other-tpc.goog" +TPC_BQ_API_ENDPOINT = f"https://bigquery.{TPC_UNIVERSE}" +TPC_BQSTORAGE_API_ENDPOINT = f"bigquerystorage.{TPC_UNIVERSE}:443" +EMULATOR_HOST = "http://localhost:9050" + + +class FakeScopedQuotaCredentials( + auth_credentials.Scoped, auth_credentials.CredentialsWithQuotaProject +): + """In-memory fake Credentials supporting scopes, quota project, and universe_domain.""" + + def __init__( + self, + universe_domain: str = DEFAULT_UNIVERSE, + quota_project_id: str | None = None, + scopes: tuple[str, ...] | None = None, + ) -> None: + super().__init__() + self._universe_domain = universe_domain + self._quota_project_id = quota_project_id + self._scopes = scopes + self.token = "fake-token" + + @property + def universe_domain(self) -> str: + return self._universe_domain + + @property + def requires_scopes(self) -> bool: + return False + + def refresh(self, request) -> None: # pragma: NO COVER + self.token = "fake-token" + + def with_scopes(self, scopes, default_scopes=None): # pragma: NO COVER + return FakeScopedQuotaCredentials( + universe_domain=self._universe_domain, + quota_project_id=self._quota_project_id, + scopes=tuple(scopes or default_scopes or ()), + ) + + def with_quota_project(self, quota_project_id: str | None): # pragma: NO COVER + return FakeScopedQuotaCredentials( + universe_domain=self._universe_domain, + quota_project_id=quota_project_id, + scopes=self._scopes, + ) + + +def make_fake_credentials( + universe_domain: str = DEFAULT_UNIVERSE, +) -> FakeScopedQuotaCredentials: + """Create fake Credentials configured for the given universe_domain.""" + return FakeScopedQuotaCredentials(universe_domain=universe_domain) + + +@pytest.fixture(autouse=True) +def clean_tpc_env(monkeypatch): + """Clear ambient universe and endpoint environment variables for each test.""" + monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) + monkeypatch.delenv("GOOGLE_API_USE_MTLS_ENDPOINT", raising=False) + monkeypatch.delenv("BIGQUERY_EMULATOR_HOST", raising=False) + monkeypatch.delenv( + "GOOGLE_CLOUD_ENABLE_DIRECT_PATH_XDS_OVER_INTERCONNECT", raising=False + ) + + +@pytest.fixture +def assert_no_googleapis_calls(monkeypatch): + """Fail if requests or gRPC channels dial *.googleapis.com during a test.""" + unexpected_calls: list[str] = [] + + def _guard_host(target_or_url: str) -> None: + if "googleapis.com" in target_or_url.lower(): # pragma: NO COVER + unexpected_calls.append(target_or_url) + raise ConnectionRefusedError( + f"Unexpected googleapis.com call toward: {target_or_url}" + ) + + def _guarded_send(self, request, *args, **kwargs): # pragma: NO COVER + _guard_host(request.url) + resp = requests.Response() + resp.status_code = 200 + resp._content = b"{}" + return resp + + monkeypatch.setattr(requests.Session, "send", _guarded_send) + + try: + import grpc + + def _guarded_channel(target, *args, **kwargs): + _guard_host(target) + return mock.create_autospec(grpc.Channel, instance=True, spec_set=True) + + monkeypatch.setattr(grpc, "secure_channel", _guarded_channel) + monkeypatch.setattr(grpc, "insecure_channel", _guarded_channel) + if hasattr(grpc, "aio"): # pragma: NO COVER + + def _guarded_aio_channel(target, *args, **kwargs): + _guard_host(target) + return mock.create_autospec( + grpc.aio.Channel, instance=True, spec_set=True + ) + + monkeypatch.setattr(grpc.aio, "secure_channel", _guarded_aio_channel) + monkeypatch.setattr(grpc.aio, "insecure_channel", _guarded_aio_channel) + except ImportError: # pragma: NO COVER + pass + + yield + assert unexpected_calls == [] + + +class TPCClientConformanceMixin: + """Reusable baseline conformance suite for client and veneer classes.""" + + def _make_client(self, **kwargs): # pragma: NO COVER + raise NotImplementedError + + def _get_effective_endpoint(self, client) -> str: # pragma: NO COVER + raise NotImplementedError + + @pytest.mark.parametrize( + "client_options", + [ + pytest.param( + {"universe_domain": TPC_UNIVERSE}, + id="dict_options", + ), + pytest.param( + MappingProxyType({"universe_domain": TPC_UNIVERSE}), + id="mapping_proxy_options", + ), + pytest.param( + client_options_lib.ClientOptions(universe_domain=TPC_UNIVERSE), + id="client_options_object", + ), + ], + ) + def test_explicit_tpc_client_options_routes_to_tpc( + self, assert_no_googleapis_calls, client_options + ): + creds = make_fake_credentials(TPC_UNIVERSE) + + client = self._make_client( + credentials=creds, + client_options=client_options, + ) + + endpoint = self._get_effective_endpoint(client) + assert client.universe_domain == TPC_UNIVERSE + assert TPC_UNIVERSE in endpoint + assert "googleapis.com" not in endpoint + + def test_universe_domain_is_read_only(self, assert_no_googleapis_calls): + creds = make_fake_credentials(TPC_UNIVERSE) + client = self._make_client( + credentials=creds, + client_options={"universe_domain": TPC_UNIVERSE}, + ) + + with pytest.raises(AttributeError): + setattr(client, "universe_domain", DEFAULT_UNIVERSE) + + def test_env_var_universe_with_adc_routes_to_tpc( + self, monkeypatch, assert_no_googleapis_calls + ): + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", TPC_UNIVERSE) + tpc_adc = make_fake_credentials(TPC_UNIVERSE) + + with mock.patch.object( + google.auth, + "default", + autospec=True, + spec_set=True, + return_value=(tpc_adc, DEFAULT_PROJECT_ID), + ): + client = self._make_client() + + endpoint = self._get_effective_endpoint(client) + assert client.universe_domain == TPC_UNIVERSE + assert TPC_UNIVERSE in endpoint + assert "googleapis.com" not in endpoint + + @pytest.mark.parametrize( + ("creds_universe", "client_options", "expected_pattern"), + [ + pytest.param( + TPC_UNIVERSE, + None, + rf"\(googleapis\.com\).*\({TPC_UNIVERSE}\)", + id="tpc_creds_on_default_gdu_client", + ), + pytest.param( + DEFAULT_UNIVERSE, + client_options_lib.ClientOptions(universe_domain=TPC_UNIVERSE), + rf"\({TPC_UNIVERSE}\).*\(googleapis\.com\)", + id="gdu_creds_on_tpc_client_options", + ), + pytest.param( + TPC_UNIVERSE, + {"api_endpoint": TPC_BQ_API_ENDPOINT}, + rf"\(googleapis\.com\).*\({TPC_UNIVERSE}\)", + id="tpc_creds_with_custom_api_endpoint_only", + ), + ], + ) + def test_mismatched_credentials_and_client_universe_fails_closed( + self, + assert_no_googleapis_calls, + creds_universe, + client_options, + expected_pattern, + ): + creds = make_fake_credentials(creds_universe) + + with pytest.raises(UniverseMismatchError, match=expected_pattern): + self._make_client(credentials=creds, client_options=client_options) + + def test_empty_client_options_and_bare_mock_creds_default_to_gdu(self): + bare_mock = mock.create_autospec( + FakeScopedQuotaCredentials, instance=True, spec_set=True + ) + bare_mock.requires_scopes = False + bare_mock.with_scopes.return_value = bare_mock + mock.seal(bare_mock) + + client = self._make_client( + credentials=bare_mock, + client_options=client_options_lib.ClientOptions(), + ) + + assert client.universe_domain == DEFAULT_UNIVERSE + + def test_anonymous_credentials_exempt_in_tpc(self, assert_no_googleapis_calls): + anon = auth_credentials.AnonymousCredentials() + + client = self._make_client( + credentials=anon, + client_options={"universe_domain": TPC_UNIVERSE}, + ) + + assert client.universe_domain == TPC_UNIVERSE + assert TPC_UNIVERSE in self._get_effective_endpoint(client) + + +class TestBigQueryClientTPCConformance(TPCClientConformanceMixin): + def _make_client(self, **kwargs): + return bigquery.Client(project=DEFAULT_PROJECT_ID, **kwargs) + + def _get_effective_endpoint(self, client) -> str: + return client._connection.API_BASE_URL + + +class TestEnsureBqStorageClientTPC: + """Tests for _ensure_bqstorage_client universe propagation and endpoint routing.""" + + @pytest.fixture + def bigquery_storage(self): + return pytest.importorskip("google.cloud.bigquery_storage") + + @pytest.fixture + def tpc_client(self, bigquery_storage): + return bigquery.Client( + project=DEFAULT_PROJECT_ID, + credentials=make_fake_credentials(TPC_UNIVERSE), + client_options={"universe_domain": TPC_UNIVERSE}, + ) + + @pytest.fixture + def custom_endpoint_client(self, bigquery_storage): + return bigquery.Client( + project=DEFAULT_PROJECT_ID, + credentials=make_fake_credentials(DEFAULT_UNIVERSE), + client_options={"api_endpoint": TPC_BQ_API_ENDPOINT}, + ) + + @pytest.mark.parametrize( + "make_options", + [ + pytest.param(lambda: None, id="none_options"), + pytest.param(dict, id="empty_dict_options"), + pytest.param( + lambda: {"universe_domain": ""}, + id="empty_string_universe_dict", + ), + pytest.param( + client_options_lib.ClientOptions, + id="empty_client_options_obj", + ), + pytest.param( + lambda: client_options_lib.ClientOptions(universe_domain=""), + id="empty_string_universe_obj", + ), + ], + ) + def test_inherits_parent_tpc_universe_when_child_universe_unset( + self, assert_no_googleapis_calls, tpc_client, make_options + ): + bqstorage_client = tpc_client._ensure_bqstorage_client( + client_options=make_options() + ) + + assert bqstorage_client is not None + assert bqstorage_client.universe_domain == TPC_UNIVERSE + assert TPC_UNIVERSE in bqstorage_client.api_endpoint + assert "googleapis.com" not in bqstorage_client.api_endpoint + + @pytest.mark.parametrize( + ("make_caller_options", "expected_quota_project"), + [ + pytest.param( + lambda: client_options_lib.ClientOptions(quota_project_id="qp-1"), + "qp-1", + id="client_options_obj", + ), + pytest.param( + lambda: {"quota_project_id": "qp-2"}, + "qp-2", + id="client_options_dict", + ), + pytest.param( + lambda: MappingProxyType({"quota_project_id": "qp-3"}), + "qp-3", + id="client_options_mapping_proxy", + ), + ], + ) + def test_inherit_universe_preserves_sibling_options_without_mutation( + self, make_caller_options, expected_quota_project + ): + caller_options = make_caller_options() + + propagated = _helpers._inherit_universe_in_client_options( + TPC_UNIVERSE, caller_options + ) + + assert propagated is not None + assert propagated.universe_domain == TPC_UNIVERSE + assert propagated.quota_project_id == expected_quota_project + if isinstance(caller_options, MappingProxyType): + assert dict(caller_options) == {"quota_project_id": expected_quota_project} + elif isinstance(caller_options, dict): + assert caller_options == {"quota_project_id": expected_quota_project} + else: + assert caller_options.universe_domain is None + assert caller_options.quota_project_id == expected_quota_project + + @pytest.mark.parametrize( + "make_caller_options", + [ + pytest.param( + lambda: client_options_lib.ClientOptions(quota_project_id="qp-1"), + id="client_options_obj", + ), + pytest.param( + lambda: {"quota_project_id": "qp-2"}, + id="client_options_dict", + ), + pytest.param( + lambda: MappingProxyType({"quota_project_id": "qp-3"}), + id="client_options_mapping_proxy", + ), + ], + ) + def test_ensure_bqstorage_client_inherits_universe_without_mutating_caller_options( + self, assert_no_googleapis_calls, tpc_client, make_caller_options + ): + caller_options = make_caller_options() + + bqs_client = tpc_client._ensure_bqstorage_client(client_options=caller_options) + + assert bqs_client is not None + assert bqs_client.universe_domain == TPC_UNIVERSE + assert getattr(caller_options, "universe_domain", None) is None + if isinstance(caller_options, (dict, MappingProxyType)): + assert "universe_domain" not in caller_options + + def test_get_client_universe_accepts_non_dict_mapping(self): + assert ( + _helpers._get_client_universe( + MappingProxyType({"universe_domain": TPC_UNIVERSE}) + ) + == TPC_UNIVERSE + ) + + @pytest.mark.parametrize( + "make_options", + [ + pytest.param(lambda: None, id="none_options"), + pytest.param(dict, id="empty_dict_options"), + pytest.param( + client_options_lib.ClientOptions, + id="empty_client_options_obj", + ), + ], + ) + def test_explicit_gdu_parent_overrides_tpc_env_var_in_bqstorage_client( + self, bigquery_storage, monkeypatch, make_options + ): + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", TPC_UNIVERSE) + gdu_creds = make_fake_credentials(DEFAULT_UNIVERSE) + client = bigquery.Client( + project=DEFAULT_PROJECT_ID, + credentials=gdu_creds, + client_options={"universe_domain": DEFAULT_UNIVERSE}, + ) + + bqstorage_client = client._ensure_bqstorage_client( + client_options=make_options() + ) + + assert bqstorage_client is not None + assert bqstorage_client.universe_domain == DEFAULT_UNIVERSE + assert "googleapis.com" in bqstorage_client.api_endpoint + + def test_default_gdu_parent_without_env_var_leaves_child_universe_unset(self): + empty_obj = client_options_lib.ClientOptions() + from_none = _helpers._inherit_universe_in_client_options(DEFAULT_UNIVERSE, None) + from_dict = _helpers._inherit_universe_in_client_options(DEFAULT_UNIVERSE, {}) + from_obj = _helpers._inherit_universe_in_client_options( + DEFAULT_UNIVERSE, empty_obj + ) + + assert from_none is None + assert from_dict is not None + assert from_dict.universe_domain is None + assert from_obj is empty_obj + assert from_obj.universe_domain is None + + def test_default_gdu_parent_normalizes_empty_string_child_universe_without_mutation( + self, + ): + caller_dict: dict[str, Any] = {"universe_domain": ""} + caller_obj = client_options_lib.ClientOptions(universe_domain="") + + from_dict = _helpers._inherit_universe_in_client_options( + DEFAULT_UNIVERSE, caller_dict + ) + from_obj = _helpers._inherit_universe_in_client_options( + DEFAULT_UNIVERSE, caller_obj + ) + + assert from_dict is not None + assert from_dict.universe_domain == DEFAULT_UNIVERSE + assert from_obj is not None + assert from_obj is not caller_obj + assert from_obj.universe_domain == DEFAULT_UNIVERSE + assert caller_dict == {"universe_domain": ""} + assert caller_obj.universe_domain == "" + + @pytest.mark.parametrize( + "child_options", + [ + pytest.param( + client_options_lib.ClientOptions(universe_domain=OTHER_TPC_UNIVERSE), + id="client_options_obj", + ), + pytest.param( + {"universe_domain": OTHER_TPC_UNIVERSE}, + id="client_options_dict", + ), + ], + ) + def test_explicit_child_universe_domain_is_preserved_with_anon_creds( + self, bigquery_storage, assert_no_googleapis_calls, child_options + ): + anon = auth_credentials.AnonymousCredentials() + client = bigquery.Client( + project=DEFAULT_PROJECT_ID, + credentials=anon, + client_options={"universe_domain": TPC_UNIVERSE}, + ) + + bqstorage_client = client._ensure_bqstorage_client(client_options=child_options) + + assert bqstorage_client is not None + assert bqstorage_client.universe_domain == OTHER_TPC_UNIVERSE + assert OTHER_TPC_UNIVERSE in bqstorage_client.api_endpoint + + def test_conflicting_child_universe_domain_fails_closed( + self, assert_no_googleapis_calls, tpc_client + ): + with pytest.raises( + UniverseMismatchError, + match=rf"\({OTHER_TPC_UNIVERSE}\).*\({TPC_UNIVERSE}\)", + ): + tpc_client._ensure_bqstorage_client( + client_options={"universe_domain": OTHER_TPC_UNIVERSE} + ) + + @pytest.mark.parametrize( + "api_endpoint", + [ + pytest.param(TPC_BQ_API_ENDPOINT, id="exact_default_tpc_endpoint"), + pytest.param( + f"{TPC_BQ_API_ENDPOINT}/", + id="trailing_slash_default_tpc_endpoint", + ), + ], + ) + def test_default_universe_api_endpoint_is_not_treated_as_custom( + self, + bigquery_storage, + monkeypatch, + assert_no_googleapis_calls, + recwarn, + api_endpoint, + ): + monkeypatch.setenv("BIGQUERY_EMULATOR_HOST", EMULATOR_HOST) + creds = make_fake_credentials(TPC_UNIVERSE) + client = bigquery.Client( + project=DEFAULT_PROJECT_ID, + credentials=creds, + client_options={ + "universe_domain": TPC_UNIVERSE, + "api_endpoint": api_endpoint, + }, + ) + + bqstorage_client = client._ensure_bqstorage_client() + + assert not recwarn + assert bqstorage_client is not None + assert bqstorage_client.universe_domain == TPC_UNIVERSE + assert TPC_UNIVERSE in bqstorage_client.api_endpoint + + @pytest.mark.parametrize( + "emulator_host", + [ + pytest.param("", id="empty_string"), + pytest.param( + "https://bigquery.googleapis.com/", + id="default_host_with_trailing_slash", + ), + ], + ) + def test_non_custom_emulator_host_env_var_is_not_treated_as_custom( + self, + monkeypatch, + assert_no_googleapis_calls, + recwarn, + tpc_client, + emulator_host, + ): + monkeypatch.setenv("BIGQUERY_EMULATOR_HOST", emulator_host) + + bqstorage_client = tpc_client._ensure_bqstorage_client() + + assert not recwarn + assert bqstorage_client is not None + assert bqstorage_client.universe_domain == TPC_UNIVERSE + + def test_custom_api_endpoint_without_bqstorage_endpoint_warns_via_dbapi( + self, assert_no_googleapis_calls, custom_endpoint_client + ): + with pytest.warns(UserWarning, match=r"custom BigQuery api_endpoint.*REST"): + conn = dbapi.connect(client=custom_endpoint_client) + + assert conn._bqstorage_client is None + + def test_emulator_host_in_tpc_universe_warns_and_falls_back_to_rest( + self, bigquery_storage, monkeypatch, assert_no_googleapis_calls + ): + monkeypatch.setenv("BIGQUERY_EMULATOR_HOST", EMULATOR_HOST) + anon = auth_credentials.AnonymousCredentials() + client = bigquery.Client( + project=DEFAULT_PROJECT_ID, + credentials=anon, + client_options={"universe_domain": TPC_UNIVERSE}, + ) + + assert client._connection.API_BASE_URL == EMULATOR_HOST + with pytest.warns(UserWarning, match=r"BIGQUERY_EMULATOR_HOST.*REST"): + bqstorage_client = client._ensure_bqstorage_client() + + assert bqstorage_client is None + + @pytest.mark.parametrize( + "bqs_options", + [ + pytest.param( + client_options_lib.ClientOptions( + api_endpoint=TPC_BQSTORAGE_API_ENDPOINT + ), + id="client_options_obj", + ), + pytest.param( + {"api_endpoint": TPC_BQSTORAGE_API_ENDPOINT}, + id="client_options_dict", + ), + ], + ) + def test_custom_api_endpoint_allows_explicit_bqstorage_api_endpoint( + self, assert_no_googleapis_calls, custom_endpoint_client, bqs_options + ): + bqstorage_client = custom_endpoint_client._ensure_bqstorage_client( + client_options=bqs_options + ) + + assert bqstorage_client is not None + assert TPC_UNIVERSE in bqstorage_client.api_endpoint + assert "googleapis.com" not in bqstorage_client.api_endpoint + + def test_custom_api_endpoint_preserves_explicit_bqstorage_client_without_warning( + self, + bigquery_storage, + assert_no_googleapis_calls, + recwarn, + custom_endpoint_client, + ): + existing_bqs = mock.create_autospec( + bigquery_storage.BigQueryReadClient, instance=True, spec_set=True + ) + + result = custom_endpoint_client._ensure_bqstorage_client( + bqstorage_client=existing_bqs + ) + + assert not recwarn + assert result is existing_bqs + + def test_to_arrow_falls_back_cleanly_to_rest_on_custom_api_endpoint( + self, assert_no_googleapis_calls, custom_endpoint_client + ): + pytest.importorskip("numpy") + pyarrow = pytest.importorskip("pyarrow") + + fields = [schema.SchemaField("name", "STRING", mode="REQUIRED")] + rows = [{"f": [{"v": "Alice"}]}] + api_request = mock.create_autospec( + custom_endpoint_client._connection.api_request, + spec_set=True, + return_value={"rows": rows}, + ) + + row_iter = bq_table.RowIterator( + custom_endpoint_client, + api_request, + ( + f"/projects/{DEFAULT_PROJECT_ID}" + f"/datasets/{DEFAULT_DATASET_ID}" + f"/tables/{DEFAULT_TABLE_ID}/data" + ), + fields, + table=bq_table.TableReference.from_string( + f"{DEFAULT_PROJECT_ID}.{DEFAULT_DATASET_ID}.{DEFAULT_TABLE_ID}" + ), + total_rows=1, + ) + + with pytest.warns(UserWarning, match=r"custom BigQuery api_endpoint.*REST"): + arrow_tbl = row_iter.to_arrow(create_bqstorage_client=True) + + assert isinstance(arrow_tbl, pyarrow.Table) + assert arrow_tbl.to_pydict() == {"name": ["Alice"]} + + def test_to_arrow_raises_clear_error_on_multi_page_custom_api_endpoint( + self, assert_no_googleapis_calls, custom_endpoint_client + ): + pytest.importorskip("numpy") + pytest.importorskip("pyarrow") + from google.cloud.bigquery import _arrow_query + + fields = [schema.SchemaField("name", "STRING", mode="REQUIRED")] + api_request = mock.create_autospec( + custom_endpoint_client._connection.api_request, + spec_set=True, + ) + + row_iter = bq_table.RowIterator( + custom_endpoint_client, + api_request, + ( + f"/projects/{DEFAULT_PROJECT_ID}" + f"/datasets/{DEFAULT_DATASET_ID}" + f"/tables/{DEFAULT_TABLE_ID}/data" + ), + fields, + table=bq_table.TableReference.from_string( + f"{DEFAULT_PROJECT_ID}.{DEFAULT_DATASET_ID}.{DEFAULT_TABLE_ID}" + ), + first_page_response={"jobComplete": True, "pageToken": "next-page"}, + ) + + with ( + pytest.warns(UserWarning, match=r"custom BigQuery api_endpoint.*REST"), + pytest.raises( + ValueError, + match=r"custom BigQuery api_endpoint or BIGQUERY_EMULATOR_HOST", + ), + ): + list(_arrow_query.download_arrow_from_job(row_iter)) + + +def _make_test_compute_credentials(): + class _TestComputeCredentials(compute_engine.Credentials): + @property + def universe_domain(self) -> str: + if not self._universe_domain_cached: # pragma: NO COVER + raise AssertionError("MDS should not be queried during init") + return self._universe_domain + + return _TestComputeCredentials() + + +def test_validate_universe_skips_uncached_compute_engine_credentials(): + gce_creds = _make_test_compute_credentials() + gce_creds._universe_domain_cached = False + + _helpers._validate_universe(TPC_UNIVERSE, gce_creds) + + +def test_validate_universe_raises_for_cached_mismatched_compute_engine_credentials(): + gce_creds = _make_test_compute_credentials() + gce_creds._universe_domain_cached = True + gce_creds._universe_domain = DEFAULT_UNIVERSE + + with pytest.raises( + UniverseMismatchError, + match=rf"\({TPC_UNIVERSE}\).*\({DEFAULT_UNIVERSE}\)", + ): + _helpers._validate_universe(TPC_UNIVERSE, gce_creds) + + +class _LegacyCredsWithoutUniverse: + pass + + +class _NonStrUniverseCreds: + universe_domain = 123 + + +@pytest.mark.parametrize( + "credentials", + [ + pytest.param(None, id="none_credentials"), + pytest.param(_LegacyCredsWithoutUniverse(), id="missing_universe_domain_attr"), + pytest.param(_NonStrUniverseCreds(), id="non_str_universe_domain_attr"), + ], +) +def test_validate_universe_skips_none_and_legacy_credentials(credentials): + _helpers._validate_universe(TPC_UNIVERSE, credentials) # type: ignore[arg-type] + + +def test_validate_universe_skips_async_anonymous_credentials(): + aio_creds = pytest.importorskip("google.auth.aio.credentials") + _helpers._validate_universe(TPC_UNIVERSE, aio_creds.AnonymousCredentials()) # type: ignore[arg-type]