diff --git a/.librarian/generator-input/client-post-processing/integrate-isolated-handwritten-code.yaml b/.librarian/generator-input/client-post-processing/integrate-isolated-handwritten-code.yaml index 1c686e8d7269..a709081233d9 100644 --- a/.librarian/generator-input/client-post-processing/integrate-isolated-handwritten-code.yaml +++ b/.librarian/generator-input/client-post-processing/integrate-isolated-handwritten-code.yaml @@ -71,9 +71,20 @@ replacements: # Exclude incompatible versions of `google-auth` # See https://github.com/googleapis/google-cloud-python/issues/12364 "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", - "google-cloud-core >= 2.0.0, <3.0.0", + "google-cloud-core >= 2.9.0, < 3.0.0", "grpcio >= 1.59.0, < 2.0.0", count: 1 + - paths: [ + "packages/google-cloud-translate/testing/constraints-3.10.txt" + ] + before: | + google-auth==2.14.1 + grpcio==1.59.0 + after: | + google-auth==2.14.1 + google-cloud-core==2.9.0 + grpcio==1.59.0 + count: 1 - paths: [ "packages/google-cloud-translate/docs/index.rst", ] diff --git a/packages/google-cloud-translate/google/cloud/translate_v2/_http.py b/packages/google-cloud-translate/google/cloud/translate_v2/_http.py index df26ce0380d1..18d9a968129d 100644 --- a/packages/google-cloud-translate/google/cloud/translate_v2/_http.py +++ b/packages/google-cloud-translate/google/cloud/translate_v2/_http.py @@ -29,10 +29,10 @@ class Connection(_http.JSONConnection): """ DEFAULT_API_ENDPOINT = "https://translation.googleapis.com" + DEFAULT_API_ENDPOINT_TEMPLATE = "https://translation.{universe_domain}" - def __init__(self, client, client_info=None, api_endpoint=DEFAULT_API_ENDPOINT): - super(Connection, self).__init__(client, client_info) - self.API_BASE_URL = api_endpoint + def __init__(self, client, client_info=None, api_endpoint=None): + super(Connection, self).__init__(client, client_info, api_endpoint=api_endpoint) self._client_info.gapic_version = __version__ self._client_info.client_library_version = __version__ diff --git a/packages/google-cloud-translate/google/cloud/translate_v2/client.py b/packages/google-cloud-translate/google/cloud/translate_v2/client.py index 383b983e7f78..b740b4c583b3 100644 --- a/packages/google-cloud-translate/google/cloud/translate_v2/client.py +++ b/packages/google-cloud-translate/google/cloud/translate_v2/client.py @@ -14,7 +14,6 @@ """Client for interacting with the Google Cloud Translation API.""" -import google.api_core.client_options from google.cloud.client import Client as BaseClient from google.cloud.translate_v2._http import Connection @@ -59,8 +58,9 @@ class Client(BaseClient): you only need to set this if you're developing your own library or partner tool. :type client_options: :class:`~google.api_core.client_options.ClientOptions` or :class:`dict` - :param client_options: (Optional) Client options used to set user options on the client. - API Endpoint should be set through client_options. + :param client_options: (Optional) Client options used to set user options + on the client. A non-default universe domain or API endpoint should be + set through client_options. """ SCOPE = ("https://www.googleapis.com/auth/cloud-platform",) @@ -75,19 +75,13 @@ def __init__( client_options=None, ): self.target_language = target_language - super(Client, self).__init__(credentials=credentials, _http=_http) - - kw_args = {"client_info": client_info} - if client_options: - if isinstance(client_options, dict): - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - kw_args["api_endpoint"] = api_endpoint - - self._connection = Connection(self, **kw_args) + super(Client, self).__init__( + credentials=credentials, + client_options=client_options, + _http=_http, + ) + self._validate_universe_domain() + self._connection = Connection(self, client_info=client_info) def get_languages(self, target_language=None): """Get list of supported languages for translation. diff --git a/packages/google-cloud-translate/setup.py b/packages/google-cloud-translate/setup.py index 5280475c6a41..d8ffab673a98 100644 --- a/packages/google-cloud-translate/setup.py +++ b/packages/google-cloud-translate/setup.py @@ -46,7 +46,7 @@ # Exclude incompatible versions of `google-auth` # See https://github.com/googleapis/google-cloud-python/issues/12364 "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", - "google-cloud-core >= 2.0.0, <3.0.0", + "google-cloud-core >= 2.9.0, < 3.0.0", "grpcio >= 1.59.0, < 2.0.0", "grpcio >= 1.75.1, < 2.0.0; python_version >= '3.14'", "proto-plus >= 1.26.1, <2.0.0", diff --git a/packages/google-cloud-translate/testing/constraints-3.10.txt b/packages/google-cloud-translate/testing/constraints-3.10.txt index 9c33fedfb264..a7ddb86c7c91 100644 --- a/packages/google-cloud-translate/testing/constraints-3.10.txt +++ b/packages/google-cloud-translate/testing/constraints-3.10.txt @@ -6,6 +6,7 @@ # then this file should have google-cloud-foo==1.14.0 google-api-core==2.28.0 google-auth==2.14.1 +google-cloud-core==2.9.0 grpcio==1.59.0 proto-plus==1.26.1 protobuf==6.33.5 diff --git a/packages/google-cloud-translate/tests/unit/v2/conftest.py b/packages/google-cloud-translate/tests/unit/v2/conftest.py new file mode 100644 index 000000000000..d32205cfade9 --- /dev/null +++ b/packages/google-cloud-translate/tests/unit/v2/conftest.py @@ -0,0 +1,22 @@ +# 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. + +import pytest + + +@pytest.fixture(autouse=True) +def clean_universe_env(monkeypatch: pytest.MonkeyPatch) -> None: + """Ensure ambient workstation env vars never affect unit tests.""" + monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) + monkeypatch.delenv("GOOGLE_API_USE_MTLS_ENDPOINT", raising=False) diff --git a/packages/google-cloud-translate/tests/unit/v2/test_universe_domain.py b/packages/google-cloud-translate/tests/unit/v2/test_universe_domain.py new file mode 100644 index 000000000000..742489bde8fe --- /dev/null +++ b/packages/google-cloud-translate/tests/unit/v2/test_universe_domain.py @@ -0,0 +1,223 @@ +# 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. + +from __future__ import annotations + +from collections.abc import Iterator +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 EmptyUniverseError, UniverseMismatchError +from google.auth import credentials as auth_credentials +from google.auth.exceptions import MutualTLSChannelError + +from google.cloud import translate_v2 + +DEFAULT_PROJECT_ID = "test-proj" +DEFAULT_UNIVERSE = "googleapis.com" +CUSTOM_UNIVERSE = "apis-tpclp.goog" + + +class FakeScopedQuotaCredentials( + auth_credentials.Scoped, auth_credentials.CredentialsWithQuotaProject +): + """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: Any) -> None: # pragma: NO COVER + self.token = "fake-token" + + def with_scopes( + self, scopes: Any, default_scopes: Any = None + ) -> FakeScopedQuotaCredentials: # 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 + ) -> FakeScopedQuotaCredentials: # pragma: NO COVER + return FakeScopedQuotaCredentials( + universe_domain=self._universe_domain, + quota_project_id=quota_project_id, + scopes=self._scopes, + ) + + +def _is_googleapis_host(url: str) -> bool: + host = urlparse(url).hostname + return bool(host and (host == "googleapis.com" or host.endswith(".googleapis.com"))) + + +@pytest.fixture +def captured_requests(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[str]]: + seen_urls: list[str] = [] + + def _guarded_send(self, request, *args, **kwargs): + if _is_googleapis_host(request.url): # pragma: NO COVER + raise ConnectionRefusedError( + f"Unexpected googleapis.com call: {request.url}" + ) + seen_urls.append(request.url) + resp = requests.Response() + resp.status_code = 200 + resp._content = b'{"data": {"languages": [{"language": "en"}]}}' + resp.headers = {"content-type": "application/json"} + resp.encoding = "utf-8" + return resp + + monkeypatch.setattr(requests.Session, "send", _guarded_send) + yield seen_urls + + +class TestTranslateV2UniverseDomain: + @pytest.mark.parametrize( + "client_options", + [ + {"universe_domain": CUSTOM_UNIVERSE}, + MappingProxyType({"universe_domain": CUSTOM_UNIVERSE}), + client_options_lib.ClientOptions(universe_domain=CUSTOM_UNIVERSE), + ], + ) + def test_custom_universe_routing_and_default_host( + self, captured_requests: list[str], client_options: Any + ) -> None: + creds = FakeScopedQuotaCredentials(CUSTOM_UNIVERSE) + client = translate_v2.Client( + target_language=None, + credentials=creds, + client_options=client_options, + ) + + assert client.universe_domain == CUSTOM_UNIVERSE + assert ( + client._connection.API_BASE_URL == f"https://translation.{CUSTOM_UNIVERSE}" + ) + assert client.get_languages() == [{"language": "en"}] + assert captured_requests == [ + f"https://translation.{CUSTOM_UNIVERSE}/language/translate/v2/languages?prettyPrint=false" + ] + assert client._http._default_host == f"translation.{CUSTOM_UNIVERSE}" + + def test_env_var_universe_with_adc( + self, monkeypatch: pytest.MonkeyPatch, captured_requests: list[str] + ) -> None: + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", CUSTOM_UNIVERSE) + adc_creds = FakeScopedQuotaCredentials(CUSTOM_UNIVERSE) + + with mock.patch.object( + google.auth, + "default", + autospec=True, + return_value=(adc_creds, DEFAULT_PROJECT_ID), + ): + client = translate_v2.Client(target_language=None) + + assert client.universe_domain == CUSTOM_UNIVERSE + assert ( + client._connection.API_BASE_URL == f"https://translation.{CUSTOM_UNIVERSE}" + ) + assert client.get_languages() == [{"language": "en"}] + assert len(captured_requests) == 1 + + def test_universe_validation_and_empty_errors( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + with pytest.raises(UniverseMismatchError): + translate_v2.Client( + credentials=FakeScopedQuotaCredentials(DEFAULT_UNIVERSE), + client_options={"universe_domain": CUSTOM_UNIVERSE}, + ) + + with pytest.raises(UniverseMismatchError): + translate_v2.Client( + credentials=FakeScopedQuotaCredentials(CUSTOM_UNIVERSE), + ) + + with pytest.raises(EmptyUniverseError): + translate_v2.Client( + credentials=auth_credentials.AnonymousCredentials(), + client_options={"universe_domain": ""}, + ) + + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", "") + with pytest.raises(EmptyUniverseError): + translate_v2.Client( + credentials=auth_credentials.AnonymousCredentials(), + ) + + def test_anonymous_credentials_and_api_endpoint_precedence( + self, monkeypatch: pytest.MonkeyPatch, captured_requests: list[str] + ) -> None: + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", "env.goog") + anon_client = translate_v2.Client( + target_language=None, + credentials=auth_credentials.AnonymousCredentials(), + client_options={ + "universe_domain": CUSTOM_UNIVERSE, + "api_endpoint": "https://custom-translation.internal:8443", + }, + ) + assert anon_client.universe_domain == CUSTOM_UNIVERSE + assert ( + anon_client._connection.API_BASE_URL + == "https://custom-translation.internal:8443" + ) + assert anon_client.get_languages() == [{"language": "en"}] + assert captured_requests == [ + "https://custom-translation.internal:8443/language/translate/v2/languages?prettyPrint=false" + ] + + def test_mtls_always_gating(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("GOOGLE_API_USE_MTLS_ENDPOINT", "always") + + tpc_client = translate_v2.Client( + credentials=FakeScopedQuotaCredentials(CUSTOM_UNIVERSE), + client_options={"universe_domain": CUSTOM_UNIVERSE}, + ) + with pytest.raises(MutualTLSChannelError): + tpc_client._connection.get_api_base_url_for_mtls() + + gdu_client = translate_v2.Client( + credentials=FakeScopedQuotaCredentials(DEFAULT_UNIVERSE), + ) + with pytest.raises(ValueError, match="mTLS endpoint is not available"): + gdu_client._connection.get_api_base_url_for_mtls()