From b7b376fbf6d01f15d787fb894e92ddea739cea20 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 25 Nov 2026 06:29:17 -0500 Subject: [PATCH 1/7] test(bigquery): add universe domain conformance and bqstorage routing tests --- .../tests/unit/test_tpc_universe.py | 676 ++++++++++++++++++ 1 file changed, 676 insertions(+) create mode 100644 packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py 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..16a55fc4977b --- /dev/null +++ b/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py @@ -0,0 +1,676 @@ +# 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 +from urllib.parse import urlparse + +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 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_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_mock_credentials( + universe_domain: str = DEFAULT_UNIVERSE, +) -> FakeScopedQuotaCredentials: + """Create fake Credentials configured for the given universe_domain.""" + return FakeScopedQuotaCredentials(universe_domain=universe_domain) + + +def _is_googleapis_host(target_or_url: str) -> bool: + if target_or_url.startswith(("http://", "https://")): + host = urlparse(target_or_url).hostname + else: + target = target_or_url.removeprefix("dns:").lstrip("/") + if "/" in target: + target = target.rsplit("/", 1)[-1] + host = urlparse(f"//{target}").hostname + return bool(host and (host == "googleapis.com" or host.endswith(".googleapis.com"))) + + +@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 _is_googleapis_host(target_or_url): # 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 TestGoogleapisHostParser: + @pytest.mark.parametrize( + ("target", "expected"), + [ + pytest.param( + "https://bigquery.googleapis.com/bigquery/v2", + True, + id="https_gdu_url", + ), + pytest.param("https://googleapis.com", True, id="bare_gdu_domain"), + pytest.param( + "bigquerystorage.googleapis.com:443", + True, + id="grpc_host_port", + ), + pytest.param( + "dns:///bigquerystorage.googleapis.com:443", + True, + id="grpc_dns_triple_slash", + ), + pytest.param( + "dns://8.8.8.8/bigquerystorage.googleapis.com:443", + True, + id="grpc_dns_with_authority", + ), + pytest.param( + f"https://bigquery.{TPC_UNIVERSE}/bigquery/v2", + False, + id="https_tpc_url", + ), + pytest.param( + f"dns:///bigquerystorage.{TPC_UNIVERSE}:443", + False, + id="grpc_dns_tpc_target", + ), + pytest.param("http://localhost:9050", False, id="local_emulator"), + ], + ) + def test_is_googleapis_host(self, target: str, expected: bool) -> None: + assert _is_googleapis_host(target) is expected + + +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_mock_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 + 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_mock_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_mock_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 + + 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.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, make_options + ): + pytest.importorskip("google.cloud.bigquery_storage") + creds = make_mock_credentials(TPC_UNIVERSE) + client = bigquery.Client( + project=DEFAULT_PROJECT_ID, + credentials=creds, + client_options={"universe_domain": TPC_UNIVERSE}, + ) + + bqstorage_client = 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 + + def test_preserves_sibling_options_without_mutating_caller_inputs( + self, assert_no_googleapis_calls + ): + pytest.importorskip("google.cloud.bigquery_storage") + creds = make_mock_credentials(TPC_UNIVERSE) + client = bigquery.Client( + project=DEFAULT_PROJECT_ID, + credentials=creds, + client_options={"universe_domain": TPC_UNIVERSE}, + ) + caller_options = client_options_lib.ClientOptions(quota_project_id="qp-1") + caller_dict: dict[str, Any] = {"quota_project_id": "qp-2"} + + propagated_obj = _helpers._inherit_universe_in_client_options( + TPC_UNIVERSE, caller_options + ) + propagated_dict = _helpers._inherit_universe_in_client_options( + TPC_UNIVERSE, caller_dict + ) + bqs_from_obj = client._ensure_bqstorage_client(client_options=caller_options) + bqs_from_dict = client._ensure_bqstorage_client(client_options=caller_dict) + + assert propagated_obj is not None + assert propagated_obj.universe_domain == TPC_UNIVERSE + assert propagated_obj.quota_project_id == "qp-1" + assert propagated_dict is not None + assert propagated_dict.universe_domain == TPC_UNIVERSE + assert propagated_dict.quota_project_id == "qp-2" + assert bqs_from_obj is not None + assert bqs_from_obj.universe_domain == TPC_UNIVERSE + assert bqs_from_dict is not None + assert bqs_from_dict.universe_domain == TPC_UNIVERSE + assert caller_options.universe_domain is None + assert caller_options.quota_project_id == "qp-1" + assert caller_dict == {"quota_project_id": "qp-2"} + + @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, monkeypatch, make_options + ): + pytest.importorskip("google.cloud.bigquery_storage") + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", TPC_UNIVERSE) + gdu_creds = make_mock_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 + + @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, assert_no_googleapis_calls, child_options + ): + pytest.importorskip("google.cloud.bigquery_storage") + 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 + ): + pytest.importorskip("google.cloud.bigquery_storage") + creds = make_mock_credentials(TPC_UNIVERSE) + client = bigquery.Client( + project=DEFAULT_PROJECT_ID, + credentials=creds, + client_options={"universe_domain": TPC_UNIVERSE}, + ) + + with pytest.raises( + UniverseMismatchError, + match=rf"\({OTHER_TPC_UNIVERSE}\).*\({TPC_UNIVERSE}\)", + ): + 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, monkeypatch, assert_no_googleapis_calls, recwarn, api_endpoint + ): + pytest.importorskip("google.cloud.bigquery_storage") + monkeypatch.setenv("BIGQUERY_EMULATOR_HOST", EMULATOR_HOST) + creds = make_mock_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 len(recwarn) == 0 + assert bqstorage_client is not None + assert bqstorage_client.universe_domain == TPC_UNIVERSE + assert TPC_UNIVERSE in bqstorage_client.api_endpoint + + def test_empty_emulator_host_env_var_is_not_treated_as_custom( + self, monkeypatch, assert_no_googleapis_calls, recwarn + ): + pytest.importorskip("google.cloud.bigquery_storage") + monkeypatch.setenv("BIGQUERY_EMULATOR_HOST", "") + creds = make_mock_credentials(TPC_UNIVERSE) + client = bigquery.Client( + project=DEFAULT_PROJECT_ID, + credentials=creds, + client_options={"universe_domain": TPC_UNIVERSE}, + ) + + bqstorage_client = client._ensure_bqstorage_client() + + assert len(recwarn) == 0 + 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 + ): + pytest.importorskip("google.cloud.bigquery_storage") + untagged_creds = make_mock_credentials(DEFAULT_UNIVERSE) + client = bigquery.Client( + project=DEFAULT_PROJECT_ID, + credentials=untagged_creds, + client_options={"api_endpoint": TPC_BQ_API_ENDPOINT}, + ) + + with pytest.warns(UserWarning, match=r"custom BigQuery api_endpoint.*REST"): + conn = dbapi.connect(client=client) + + assert conn._bqstorage_client is None + + def test_emulator_host_in_tpc_universe_warns_and_falls_back_to_rest( + self, monkeypatch, assert_no_googleapis_calls + ): + pytest.importorskip("google.cloud.bigquery_storage") + 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, bqs_options + ): + pytest.importorskip("google.cloud.bigquery_storage") + untagged_creds = make_mock_credentials(DEFAULT_UNIVERSE) + client = bigquery.Client( + project=DEFAULT_PROJECT_ID, + credentials=untagged_creds, + client_options={"api_endpoint": TPC_BQ_API_ENDPOINT}, + ) + + bqstorage_client = 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, assert_no_googleapis_calls, recwarn + ): + bigquery_storage = pytest.importorskip("google.cloud.bigquery_storage") + untagged_creds = make_mock_credentials(DEFAULT_UNIVERSE) + client = bigquery.Client( + project=DEFAULT_PROJECT_ID, + credentials=untagged_creds, + client_options={"api_endpoint": TPC_BQ_API_ENDPOINT}, + ) + existing_bqs = mock.create_autospec( + bigquery_storage.BigQueryReadClient, instance=True, spec_set=True + ) + + result = client._ensure_bqstorage_client(bqstorage_client=existing_bqs) + + assert len(recwarn) == 0 + assert result is existing_bqs + + def test_to_arrow_falls_back_cleanly_to_rest_on_custom_api_endpoint( + self, assert_no_googleapis_calls + ): + pytest.importorskip("numpy") + pyarrow = pytest.importorskip("pyarrow") + pytest.importorskip("google.cloud.bigquery_storage") + + untagged_creds = make_mock_credentials(DEFAULT_UNIVERSE) + client = bigquery.Client( + project=DEFAULT_PROJECT_ID, + credentials=untagged_creds, + client_options={"api_endpoint": TPC_BQ_API_ENDPOINT}, + ) + fields = [schema.SchemaField("name", "STRING", mode="REQUIRED")] + rows = [{"f": [{"v": "Alice"}]}] + api_request = mock.create_autospec( + client._connection.api_request, + spec_set=True, + return_value={"rows": rows}, + ) + + row_iter = bq_table.RowIterator( + client, + api_request, + "/projects/test-proj/datasets/ds/tables/tbl/data", + fields, + table=bq_table.TableReference.from_string("test-proj.ds.tbl"), + 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"]} From cc7977f9de8ae7036af69aac45bd717c4387234f Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Wed, 25 Nov 2026 06:29:20 -0500 Subject: [PATCH 2/7] fix(bigquery): inherit universe_domain and guard custom endpoints in _ensure_bqstorage_client --- .../google/cloud/bigquery/_helpers.py | 95 ++++++++++----- .../google/cloud/bigquery/client.py | 108 ++++++++++++------ 2 files changed, 138 insertions(+), 65 deletions(-) diff --git a/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py b/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py index 00a2ef25605c..ec24548d7c82 100644 --- a/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py +++ b/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py @@ -15,27 +15,32 @@ """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.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 +from google.api_core.universe import UniverseMismatchError +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 TimeoutType = Union[float, None] @@ -77,7 +82,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 +92,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 +109,63 @@ def _get_client_universe( return universe -def _validate_universe(client_universe: str, credentials: ga_credentials.Credentials): +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`` or + ``AnonymousCredentials``. 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, ga_credentials.AnonymousCredentials + ): + return + cred_universe = getattr(credentials, "universe_domain", None) + if isinstance(cred_universe, str) and client_universe != cred_universe: + raise UniverseMismatchError(client_universe, cred_universe) + + +# TODO(universe-domain): Replace with google.api_core.universe.inherit_universe_in_client_options +# once minimum allowed google-api-core version exceeds 2.44.0. +def _inherit_universe_in_client_options( + parent_universe: str, + client_options: 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. + """ + 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 +689,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..e94efb9ad14b 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,10 @@ 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``. """ try: @@ -731,10 +748,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 +789,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: From 9948b6099ff14df29d9635704d7708a3d9be35bb Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Mon, 30 Nov 2026 10:59:07 -0500 Subject: [PATCH 3/7] fix(bigquery): align _validate_universe with shared GCE and async AnonymousCredentials guards --- .../google/cloud/bigquery/_helpers.py | 24 +++++++++++++++---- .../tests/unit/test_tpc_universe.py | 19 +++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py b/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py index ec24548d7c82..4240adebd6ee 100644 --- a/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py +++ b/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py @@ -30,7 +30,18 @@ from dateutil import relativedelta 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 + +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,) from google.cloud._helpers import ( _RFC3339_MICROS, _RFC3339_NO_FRACTION, @@ -109,6 +120,8 @@ def _get_client_universe( return universe +# 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: @@ -117,15 +130,18 @@ def _validate_universe( Args: client_universe (str): The universe domain configured via the client options. credentials (ga_credentials.Credentials | None): The credentials being - used in the client. Validation is skipped when ``None`` or - ``AnonymousCredentials``. + used in the client. Validation is skipped when ``None``, + ``AnonymousCredentials`` (sync or async), or uncached + ``compute_engine.Credentials``. Raises: google.api_core.universe.UniverseMismatchError: (subclass of ``ValueError``) when ``client_universe`` does not match the universe in ``credentials``. """ - if credentials is None or isinstance( - credentials, ga_credentials.AnonymousCredentials + 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) diff --git a/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py b/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py index 16a55fc4977b..c88ce2136fca 100644 --- a/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py +++ b/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py @@ -674,3 +674,22 @@ def test_to_arrow_falls_back_cleanly_to_rest_on_custom_api_endpoint( assert isinstance(arrow_tbl, pyarrow.Table) assert arrow_tbl.to_pydict() == {"name": ["Alice"]} + + +def test_validate_universe_skips_uncached_compute_engine_credentials(): + from google.auth import compute_engine + + gce_creds = compute_engine.Credentials() + gce_creds._universe_domain_cached = False + with mock.patch.object( + compute_engine.Credentials, + "universe_domain", + new_callable=mock.PropertyMock, + side_effect=AssertionError("MDS should not be queried during init"), + ): + _helpers._validate_universe(TPC_UNIVERSE, gce_creds) + + gce_creds._universe_domain_cached = True + gce_creds._universe_domain = DEFAULT_UNIVERSE + with pytest.raises(UniverseMismatchError): + _helpers._validate_universe(TPC_UNIVERSE, gce_creds) From 6d5e0de797c9473b66e66d8894f9e3295b50ea20 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Tue, 1 Dec 2026 09:08:41 -0500 Subject: [PATCH 4/7] test(bigquery): fix compute_engine credentials test on oldest google-auth constraints --- .../google/cloud/bigquery/_helpers.py | 2 -- .../tests/unit/test_tpc_universe.py | 17 +++++++++-------- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py b/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py index 4240adebd6ee..428f4d2b93a9 100644 --- a/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py +++ b/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py @@ -149,8 +149,6 @@ def _validate_universe( raise UniverseMismatchError(client_universe, cred_universe) -# TODO(universe-domain): Replace with google.api_core.universe.inherit_universe_in_client_options -# once minimum allowed google-api-core version exceeds 2.44.0. def _inherit_universe_in_client_options( parent_universe: str, client_options: client_options_lib.ClientOptions | Mapping[str, Any] | None = 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 index c88ce2136fca..b7dfbd914dc0 100644 --- a/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py +++ b/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py @@ -679,15 +679,16 @@ def test_to_arrow_falls_back_cleanly_to_rest_on_custom_api_endpoint( def test_validate_universe_skips_uncached_compute_engine_credentials(): from google.auth import compute_engine - gce_creds = compute_engine.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 + + gce_creds = _TestComputeCredentials() gce_creds._universe_domain_cached = False - with mock.patch.object( - compute_engine.Credentials, - "universe_domain", - new_callable=mock.PropertyMock, - side_effect=AssertionError("MDS should not be queried during init"), - ): - _helpers._validate_universe(TPC_UNIVERSE, gce_creds) + _helpers._validate_universe(TPC_UNIVERSE, gce_creds) gce_creds._universe_domain_cached = True gce_creds._universe_domain = DEFAULT_UNIVERSE From c15255b4dd504cd36f305df78e17382da7b5f709 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Tue, 1 Dec 2026 09:24:17 -0500 Subject: [PATCH 5/7] test(bigquery): drop _is_googleapis_host helper and add _validate_universe edge cases --- .../tests/unit/test_tpc_universe.py | 74 +++++-------------- 1 file changed, 19 insertions(+), 55 deletions(-) diff --git a/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py b/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py index b7dfbd914dc0..8e06893e5fe8 100644 --- a/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py +++ b/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py @@ -17,7 +17,6 @@ from types import MappingProxyType from typing import Any from unittest import mock -from urllib.parse import urlparse import google.auth import pytest @@ -89,17 +88,6 @@ def make_mock_credentials( return FakeScopedQuotaCredentials(universe_domain=universe_domain) -def _is_googleapis_host(target_or_url: str) -> bool: - if target_or_url.startswith(("http://", "https://")): - host = urlparse(target_or_url).hostname - else: - target = target_or_url.removeprefix("dns:").lstrip("/") - if "/" in target: - target = target.rsplit("/", 1)[-1] - host = urlparse(f"//{target}").hostname - return bool(host and (host == "googleapis.com" or host.endswith(".googleapis.com"))) - - @pytest.fixture(autouse=True) def clean_tpc_env(monkeypatch): """Clear ambient universe and endpoint environment variables for each test.""" @@ -117,7 +105,7 @@ def assert_no_googleapis_calls(monkeypatch): unexpected_calls: list[str] = [] def _guard_host(target_or_url: str) -> None: - if _is_googleapis_host(target_or_url): # pragma: NO COVER + 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}" @@ -158,48 +146,6 @@ def _guarded_aio_channel(target, *args, **kwargs): assert unexpected_calls == [] -class TestGoogleapisHostParser: - @pytest.mark.parametrize( - ("target", "expected"), - [ - pytest.param( - "https://bigquery.googleapis.com/bigquery/v2", - True, - id="https_gdu_url", - ), - pytest.param("https://googleapis.com", True, id="bare_gdu_domain"), - pytest.param( - "bigquerystorage.googleapis.com:443", - True, - id="grpc_host_port", - ), - pytest.param( - "dns:///bigquerystorage.googleapis.com:443", - True, - id="grpc_dns_triple_slash", - ), - pytest.param( - "dns://8.8.8.8/bigquerystorage.googleapis.com:443", - True, - id="grpc_dns_with_authority", - ), - pytest.param( - f"https://bigquery.{TPC_UNIVERSE}/bigquery/v2", - False, - id="https_tpc_url", - ), - pytest.param( - f"dns:///bigquerystorage.{TPC_UNIVERSE}:443", - False, - id="grpc_dns_tpc_target", - ), - pytest.param("http://localhost:9050", False, id="local_emulator"), - ], - ) - def test_is_googleapis_host(self, target: str, expected: bool) -> None: - assert _is_googleapis_host(target) is expected - - class TPCClientConformanceMixin: """Reusable baseline conformance suite for client and veneer classes.""" @@ -694,3 +640,21 @@ def universe_domain(self) -> str: gce_creds._universe_domain = DEFAULT_UNIVERSE with pytest.raises(UniverseMismatchError): _helpers._validate_universe(TPC_UNIVERSE, gce_creds) + + +def test_validate_universe_skips_none_and_legacy_credentials(): + _helpers._validate_universe(TPC_UNIVERSE, None) + + class _LegacyCreds: + pass + + class _NonStrUniverseCreds: + universe_domain = 123 + + _helpers._validate_universe(TPC_UNIVERSE, _LegacyCreds()) # type: ignore[arg-type] + _helpers._validate_universe(TPC_UNIVERSE, _NonStrUniverseCreds()) # 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()) From 9d3dda522e797d5252878de490f7c0120f1ece45 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Tue, 1 Dec 2026 13:47:23 -0500 Subject: [PATCH 6/7] fix(bigquery): address code and test review findings for TPC universe support --- .../google/cloud/bigquery/_arrow_query.py | 12 +- .../google/cloud/bigquery/_helpers.py | 31 +- .../google/cloud/bigquery/client.py | 5 + .../tests/unit/test_tpc_universe.py | 394 ++++++++++++------ 4 files changed, 297 insertions(+), 145 deletions(-) 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 428f4d2b93a9..31c7186ae631 100644 --- a/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py +++ b/packages/google-cloud-bigquery/google/cloud/bigquery/_helpers.py @@ -32,16 +32,6 @@ from google.api_core.universe import UniverseMismatchError from google.auth import compute_engine from google.auth import credentials as ga_credentials # type: ignore - -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,) from google.cloud._helpers import ( _RFC3339_MICROS, _RFC3339_NO_FRACTION, @@ -53,6 +43,16 @@ from google.cloud.bigquery import enums +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] _RFC3339_MICROS_NO_ZULU = "%Y-%m-%dT%H:%M:%S.%f" @@ -156,6 +156,17 @@ def _inherit_universe_in_client_options( """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 diff --git a/packages/google-cloud-bigquery/google/cloud/bigquery/client.py b/packages/google-cloud-bigquery/google/cloud/bigquery/client.py index e94efb9ad14b..33ab933260a4 100644 --- a/packages/google-cloud-bigquery/google/cloud/bigquery/client.py +++ b/packages/google-cloud-bigquery/google/cloud/bigquery/client.py @@ -688,6 +688,11 @@ def _ensure_bqstorage_client( ``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: diff --git a/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py b/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py index 8e06893e5fe8..84d97431a5ca 100644 --- a/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py +++ b/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py @@ -23,6 +23,7 @@ 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 @@ -30,6 +31,8 @@ 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" @@ -81,7 +84,7 @@ def with_quota_project(self, quota_project_id: str | None): # pragma: NO COVER ) -def make_mock_credentials( +def make_fake_credentials( universe_domain: str = DEFAULT_UNIVERSE, ) -> FakeScopedQuotaCredentials: """Create fake Credentials configured for the given universe_domain.""" @@ -175,7 +178,7 @@ def _get_effective_endpoint(self, client) -> str: # pragma: NO COVER def test_explicit_tpc_client_options_routes_to_tpc( self, assert_no_googleapis_calls, client_options ): - creds = make_mock_credentials(TPC_UNIVERSE) + creds = make_fake_credentials(TPC_UNIVERSE) client = self._make_client( credentials=creds, @@ -186,6 +189,14 @@ def test_explicit_tpc_client_options_routes_to_tpc( 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) @@ -193,7 +204,7 @@ 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_mock_credentials(TPC_UNIVERSE) + tpc_adc = make_fake_credentials(TPC_UNIVERSE) with mock.patch.object( google.auth, @@ -239,7 +250,7 @@ def test_mismatched_credentials_and_client_universe_fails_closed( client_options, expected_pattern, ): - creds = make_mock_credentials(creds_universe) + creds = make_fake_credentials(creds_universe) with pytest.raises(UniverseMismatchError, match=expected_pattern): self._make_client(credentials=creds, client_options=client_options) @@ -250,6 +261,7 @@ def test_empty_client_options_and_bare_mock_creds_default_to_gdu(self): ) bare_mock.requires_scopes = False bare_mock.with_scopes.return_value = bare_mock + mock.seal(bare_mock) client = self._make_client( credentials=bare_mock, @@ -281,6 +293,26 @@ def _get_effective_endpoint(self, client) -> str: 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", [ @@ -301,17 +333,9 @@ class TestEnsureBqStorageClientTPC: ], ) def test_inherits_parent_tpc_universe_when_child_universe_unset( - self, assert_no_googleapis_calls, make_options + self, assert_no_googleapis_calls, tpc_client, make_options ): - pytest.importorskip("google.cloud.bigquery_storage") - creds = make_mock_credentials(TPC_UNIVERSE) - client = bigquery.Client( - project=DEFAULT_PROJECT_ID, - credentials=creds, - client_options={"universe_domain": TPC_UNIVERSE}, - ) - - bqstorage_client = client._ensure_bqstorage_client( + bqstorage_client = tpc_client._ensure_bqstorage_client( client_options=make_options() ) @@ -320,41 +344,83 @@ def test_inherits_parent_tpc_universe_when_child_universe_unset( assert TPC_UNIVERSE in bqstorage_client.api_endpoint assert "googleapis.com" not in bqstorage_client.api_endpoint - def test_preserves_sibling_options_without_mutating_caller_inputs( - self, assert_no_googleapis_calls + @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 ): - pytest.importorskip("google.cloud.bigquery_storage") - creds = make_mock_credentials(TPC_UNIVERSE) - client = bigquery.Client( - project=DEFAULT_PROJECT_ID, - credentials=creds, - client_options={"universe_domain": TPC_UNIVERSE}, - ) - caller_options = client_options_lib.ClientOptions(quota_project_id="qp-1") - caller_dict: dict[str, Any] = {"quota_project_id": "qp-2"} + caller_options = make_caller_options() - propagated_obj = _helpers._inherit_universe_in_client_options( + propagated = _helpers._inherit_universe_in_client_options( TPC_UNIVERSE, caller_options ) - propagated_dict = _helpers._inherit_universe_in_client_options( - TPC_UNIVERSE, caller_dict + + 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 ) - bqs_from_obj = client._ensure_bqstorage_client(client_options=caller_options) - bqs_from_dict = client._ensure_bqstorage_client(client_options=caller_dict) - - assert propagated_obj is not None - assert propagated_obj.universe_domain == TPC_UNIVERSE - assert propagated_obj.quota_project_id == "qp-1" - assert propagated_dict is not None - assert propagated_dict.universe_domain == TPC_UNIVERSE - assert propagated_dict.quota_project_id == "qp-2" - assert bqs_from_obj is not None - assert bqs_from_obj.universe_domain == TPC_UNIVERSE - assert bqs_from_dict is not None - assert bqs_from_dict.universe_domain == TPC_UNIVERSE - assert caller_options.universe_domain is None - assert caller_options.quota_project_id == "qp-1" - assert caller_dict == {"quota_project_id": "qp-2"} @pytest.mark.parametrize( "make_options", @@ -368,11 +434,10 @@ def test_preserves_sibling_options_without_mutating_caller_inputs( ], ) def test_explicit_gdu_parent_overrides_tpc_env_var_in_bqstorage_client( - self, monkeypatch, make_options + self, bigquery_storage, monkeypatch, make_options ): - pytest.importorskip("google.cloud.bigquery_storage") monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", TPC_UNIVERSE) - gdu_creds = make_mock_credentials(DEFAULT_UNIVERSE) + gdu_creds = make_fake_credentials(DEFAULT_UNIVERSE) client = bigquery.Client( project=DEFAULT_PROJECT_ID, credentials=gdu_creds, @@ -401,6 +466,27 @@ def test_default_gdu_parent_without_env_var_leaves_child_universe_unset(self): 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", [ @@ -415,9 +501,8 @@ def test_default_gdu_parent_without_env_var_leaves_child_universe_unset(self): ], ) def test_explicit_child_universe_domain_is_preserved_with_anon_creds( - self, assert_no_googleapis_calls, child_options + self, bigquery_storage, assert_no_googleapis_calls, child_options ): - pytest.importorskip("google.cloud.bigquery_storage") anon = auth_credentials.AnonymousCredentials() client = bigquery.Client( project=DEFAULT_PROJECT_ID, @@ -432,21 +517,13 @@ def test_explicit_child_universe_domain_is_preserved_with_anon_creds( assert OTHER_TPC_UNIVERSE in bqstorage_client.api_endpoint def test_conflicting_child_universe_domain_fails_closed( - self, assert_no_googleapis_calls + self, assert_no_googleapis_calls, tpc_client ): - pytest.importorskip("google.cloud.bigquery_storage") - creds = make_mock_credentials(TPC_UNIVERSE) - client = bigquery.Client( - project=DEFAULT_PROJECT_ID, - credentials=creds, - client_options={"universe_domain": TPC_UNIVERSE}, - ) - with pytest.raises( UniverseMismatchError, match=rf"\({OTHER_TPC_UNIVERSE}\).*\({TPC_UNIVERSE}\)", ): - client._ensure_bqstorage_client( + tpc_client._ensure_bqstorage_client( client_options={"universe_domain": OTHER_TPC_UNIVERSE} ) @@ -461,11 +538,15 @@ def test_conflicting_child_universe_domain_fails_closed( ], ) def test_default_universe_api_endpoint_is_not_treated_as_custom( - self, monkeypatch, assert_no_googleapis_calls, recwarn, api_endpoint + self, + bigquery_storage, + monkeypatch, + assert_no_googleapis_calls, + recwarn, + api_endpoint, ): - pytest.importorskip("google.cloud.bigquery_storage") monkeypatch.setenv("BIGQUERY_EMULATOR_HOST", EMULATOR_HOST) - creds = make_mock_credentials(TPC_UNIVERSE) + creds = make_fake_credentials(TPC_UNIVERSE) client = bigquery.Client( project=DEFAULT_PROJECT_ID, credentials=creds, @@ -477,49 +558,48 @@ def test_default_universe_api_endpoint_is_not_treated_as_custom( bqstorage_client = client._ensure_bqstorage_client() - assert len(recwarn) == 0 + assert not recwarn assert bqstorage_client is not None assert bqstorage_client.universe_domain == TPC_UNIVERSE assert TPC_UNIVERSE in bqstorage_client.api_endpoint - def test_empty_emulator_host_env_var_is_not_treated_as_custom( - self, monkeypatch, assert_no_googleapis_calls, recwarn + @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, ): - pytest.importorskip("google.cloud.bigquery_storage") - monkeypatch.setenv("BIGQUERY_EMULATOR_HOST", "") - creds = make_mock_credentials(TPC_UNIVERSE) - client = bigquery.Client( - project=DEFAULT_PROJECT_ID, - credentials=creds, - client_options={"universe_domain": TPC_UNIVERSE}, - ) + monkeypatch.setenv("BIGQUERY_EMULATOR_HOST", emulator_host) - bqstorage_client = client._ensure_bqstorage_client() + bqstorage_client = tpc_client._ensure_bqstorage_client() - assert len(recwarn) == 0 + 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 + self, assert_no_googleapis_calls, custom_endpoint_client ): - pytest.importorskip("google.cloud.bigquery_storage") - untagged_creds = make_mock_credentials(DEFAULT_UNIVERSE) - client = bigquery.Client( - project=DEFAULT_PROJECT_ID, - credentials=untagged_creds, - client_options={"api_endpoint": TPC_BQ_API_ENDPOINT}, - ) - with pytest.warns(UserWarning, match=r"custom BigQuery api_endpoint.*REST"): - conn = dbapi.connect(client=client) + 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, monkeypatch, assert_no_googleapis_calls + self, bigquery_storage, monkeypatch, assert_no_googleapis_calls ): - pytest.importorskip("google.cloud.bigquery_storage") monkeypatch.setenv("BIGQUERY_EMULATOR_HOST", EMULATOR_HOST) anon = auth_credentials.AnonymousCredentials() client = bigquery.Client( @@ -550,68 +630,60 @@ def test_emulator_host_in_tpc_universe_warns_and_falls_back_to_rest( ], ) def test_custom_api_endpoint_allows_explicit_bqstorage_api_endpoint( - self, assert_no_googleapis_calls, bqs_options + self, assert_no_googleapis_calls, custom_endpoint_client, bqs_options ): - pytest.importorskip("google.cloud.bigquery_storage") - untagged_creds = make_mock_credentials(DEFAULT_UNIVERSE) - client = bigquery.Client( - project=DEFAULT_PROJECT_ID, - credentials=untagged_creds, - client_options={"api_endpoint": TPC_BQ_API_ENDPOINT}, + bqstorage_client = custom_endpoint_client._ensure_bqstorage_client( + client_options=bqs_options ) - bqstorage_client = 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, assert_no_googleapis_calls, recwarn + self, + bigquery_storage, + assert_no_googleapis_calls, + recwarn, + custom_endpoint_client, ): - bigquery_storage = pytest.importorskip("google.cloud.bigquery_storage") - untagged_creds = make_mock_credentials(DEFAULT_UNIVERSE) - client = bigquery.Client( - project=DEFAULT_PROJECT_ID, - credentials=untagged_creds, - client_options={"api_endpoint": TPC_BQ_API_ENDPOINT}, - ) existing_bqs = mock.create_autospec( bigquery_storage.BigQueryReadClient, instance=True, spec_set=True ) - result = client._ensure_bqstorage_client(bqstorage_client=existing_bqs) + result = custom_endpoint_client._ensure_bqstorage_client( + bqstorage_client=existing_bqs + ) - assert len(recwarn) == 0 + 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 + self, assert_no_googleapis_calls, custom_endpoint_client ): pytest.importorskip("numpy") pyarrow = pytest.importorskip("pyarrow") - pytest.importorskip("google.cloud.bigquery_storage") - untagged_creds = make_mock_credentials(DEFAULT_UNIVERSE) - client = bigquery.Client( - project=DEFAULT_PROJECT_ID, - credentials=untagged_creds, - client_options={"api_endpoint": TPC_BQ_API_ENDPOINT}, - ) fields = [schema.SchemaField("name", "STRING", mode="REQUIRED")] rows = [{"f": [{"v": "Alice"}]}] api_request = mock.create_autospec( - client._connection.api_request, + custom_endpoint_client._connection.api_request, spec_set=True, return_value={"rows": rows}, ) row_iter = bq_table.RowIterator( - client, + custom_endpoint_client, api_request, - "/projects/test-proj/datasets/ds/tables/tbl/data", + ( + f"/projects/{DEFAULT_PROJECT_ID}" + f"/datasets/{DEFAULT_DATASET_ID}" + f"/tables/{DEFAULT_TABLE_ID}/data" + ), fields, - table=bq_table.TableReference.from_string("test-proj.ds.tbl"), + table=bq_table.TableReference.from_string( + f"{DEFAULT_PROJECT_ID}.{DEFAULT_DATASET_ID}.{DEFAULT_TABLE_ID}" + ), total_rows=1, ) @@ -621,10 +693,45 @@ def test_to_arrow_falls_back_cleanly_to_rest_on_custom_api_endpoint( 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 -def test_validate_universe_skips_uncached_compute_engine_credentials(): - from google.auth import compute_engine + 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: @@ -632,29 +739,54 @@ def universe_domain(self) -> str: raise AssertionError("MDS should not be queried during init") return self._universe_domain - gce_creds = _TestComputeCredentials() + 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): + + with pytest.raises( + UniverseMismatchError, + match=rf"\({TPC_UNIVERSE}\).*\({DEFAULT_UNIVERSE}\)", + ): _helpers._validate_universe(TPC_UNIVERSE, gce_creds) -def test_validate_universe_skips_none_and_legacy_credentials(): - _helpers._validate_universe(TPC_UNIVERSE, None) +class _LegacyCredsWithoutUniverse: + pass - class _LegacyCreds: - pass - class _NonStrUniverseCreds: - universe_domain = 123 +class _NonStrUniverseCreds: + universe_domain = 123 + - _helpers._validate_universe(TPC_UNIVERSE, _LegacyCreds()) # type: ignore[arg-type] - _helpers._validate_universe(TPC_UNIVERSE, _NonStrUniverseCreds()) # type: ignore[arg-type] +@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()) + client = bigquery.Client( + project=DEFAULT_PROJECT_ID, + credentials=aio_creds.AnonymousCredentials(), + client_options={"universe_domain": TPC_UNIVERSE}, + ) + + assert client.universe_domain == TPC_UNIVERSE From c894bc0e5b86855ccbc2830ed148e9172ab93f28 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Tue, 1 Dec 2026 15:43:08 -0500 Subject: [PATCH 7/7] test(bigquery): call _validate_universe directly for async AnonymousCredentials --- .../google-cloud-bigquery/tests/unit/test_tpc_universe.py | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py b/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py index 84d97431a5ca..04cc11618cff 100644 --- a/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py +++ b/packages/google-cloud-bigquery/tests/unit/test_tpc_universe.py @@ -783,10 +783,4 @@ def test_validate_universe_skips_none_and_legacy_credentials(credentials): def test_validate_universe_skips_async_anonymous_credentials(): aio_creds = pytest.importorskip("google.auth.aio.credentials") - client = bigquery.Client( - project=DEFAULT_PROJECT_ID, - credentials=aio_creds.AnonymousCredentials(), - client_options={"universe_domain": TPC_UNIVERSE}, - ) - - assert client.universe_domain == TPC_UNIVERSE + _helpers._validate_universe(TPC_UNIVERSE, aio_creds.AnonymousCredentials()) # type: ignore[arg-type]