From 076c99a15c0b62d984cc55b0b31cce8b96eb9abf Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Tue, 4 Aug 2026 22:15:38 +0000 Subject: [PATCH 1/9] chore(generator): move to --- .../%name_%version/%sub/_compat.py.j2 | 26 +++++++++++++- .../%sub/services/%service/client.py.j2 | 32 ++++------------- .../%name_%version/%sub/test_%service.py.j2 | 12 ------- .../%name_%version/%sub/test_compat.py.j2 | 16 ++++++++- .../asset/google/cloud/asset_v1/_compat.py | 24 ++++++++++++- .../asset_v1/services/asset_service/client.py | 34 ++++--------------- .../unit/gapic/asset_v1/test_asset_service.py | 14 -------- .../tests/unit/gapic/asset_v1/test_compat.py | 16 ++++++++- .../google/iam/credentials_v1/_compat.py | 24 ++++++++++++- .../services/iam_credentials/client.py | 34 ++++--------------- .../unit/gapic/credentials_v1/test_compat.py | 16 ++++++++- .../credentials_v1/test_iam_credentials.py | 14 -------- .../google/cloud/eventarc_v1/_compat.py | 24 ++++++++++++- .../eventarc_v1/services/eventarc/client.py | 34 ++++--------------- .../unit/gapic/eventarc_v1/test_compat.py | 16 ++++++++- .../unit/gapic/eventarc_v1/test_eventarc.py | 14 -------- .../google/cloud/logging_v2/_compat.py | 24 ++++++++++++- .../services/config_service_v2/client.py | 34 ++++--------------- .../services/logging_service_v2/client.py | 34 ++++--------------- .../services/metrics_service_v2/client.py | 34 ++++--------------- .../unit/gapic/logging_v2/test_compat.py | 16 ++++++++- .../logging_v2/test_config_service_v2.py | 14 -------- .../logging_v2/test_logging_service_v2.py | 14 -------- .../logging_v2/test_metrics_service_v2.py | 14 -------- .../google/cloud/logging_v2/_compat.py | 24 ++++++++++++- .../services/config_service_v2/client.py | 34 ++++--------------- .../services/logging_service_v2/client.py | 34 ++++--------------- .../services/metrics_service_v2/client.py | 34 ++++--------------- .../unit/gapic/logging_v2/test_compat.py | 16 ++++++++- .../logging_v2/test_config_service_v2.py | 14 -------- .../logging_v2/test_logging_service_v2.py | 14 -------- .../logging_v2/test_metrics_service_v2.py | 14 -------- .../redis/google/cloud/redis_v1/_compat.py | 24 ++++++++++++- .../redis_v1/services/cloud_redis/client.py | 34 ++++--------------- .../unit/gapic/redis_v1/test_cloud_redis.py | 14 -------- .../tests/unit/gapic/redis_v1/test_compat.py | 16 ++++++++- .../google/cloud/redis_v1/_compat.py | 24 ++++++++++++- .../redis_v1/services/cloud_redis/client.py | 34 ++++--------------- .../unit/gapic/redis_v1/test_cloud_redis.py | 14 -------- .../tests/unit/gapic/redis_v1/test_compat.py | 16 ++++++++- .../storagebatchoperations_v1/_compat.py | 24 ++++++++++++- .../storage_batch_operations/client.py | 34 ++++--------------- .../storagebatchoperations_v1/test_compat.py | 16 ++++++++- .../test_storage_batch_operations.py | 14 -------- 44 files changed, 422 insertions(+), 560 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 index fba8615921af..cbe4a64c4cf9 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 @@ -19,7 +19,7 @@ import json import uuid {% endif %} -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple {% if has_auto_populated_fields %} from typing import Union {% endif %} @@ -34,6 +34,10 @@ from google.auth.exceptions import MutualTLSChannelError from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + +{# TODO: Remove client cert compatibility fallbacks when the minimum supported +version of google-auth is >= 2.43.0 (currently 2.14.1+). #} try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -50,6 +54,26 @@ except ImportError: # pragma: NO COVER ) return use_client_cert == "true" + +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 index 737c5e34e7bb..ad0ee82359d5 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 @@ -30,13 +30,13 @@ from google.api_core import exceptions as core_exceptions from google.api_core import extended_operation {% endif %} from google.api_core import gapic_v1 -from {{package_path}}._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from {{package_path}}._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source {% if has_auto_populated_fields %} from {{package_path}}._compat import setup_request_id {% endif %} from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore + from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -276,12 +276,9 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert: - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() + client_cert_source = get_client_cert_source( + client_options.client_cert_source, use_client_cert + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -314,24 +311,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source def _validate_universe_domain(self): @@ -460,7 +440,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = {{ service.client_name }}._read_environment_variables() - self._client_cert_source = {{ service.client_name }}._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 index 646f3f347837..4b4d6e6d9a2b 100644 --- a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 +++ b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_%service.py.j2 @@ -168,18 +168,6 @@ def set_event_loop(): asyncio.set_event_loop(None) -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert {{ service.client_name }}._get_client_cert_source(None, False) is None - assert {{ service.client_name }}._get_client_cert_source(mock_provided_cert_source, False) is None - assert {{ service.client_name }}._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert {{ service.client_name }}._get_client_cert_source(None, True) is mock_default_cert_source - assert {{ service.client_name }}._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source diff --git a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 index 8a923aeeef83..5e75e945a13f 100644 --- a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 +++ b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 @@ -23,7 +23,7 @@ import google.auth.transport.mtls {% set package_path = api.naming.module_namespace|join('.') + "." + api.naming.versioned_module_name %} from {{package_path}}._compat import transcode_request -from {{package_path}}._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from {{package_path}}._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source {% if has_auto_populated_fields %} from {{package_path}}._compat import setup_request_id {% endif %} @@ -497,4 +497,18 @@ def test_transcode_request_proto_plus_wrapper(): transcoded, _, _ = transcode_request(http_options, mock_proto_plus) assert transcoded["uri"] == "/v1/test/proto-plus-field" + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + {% endblock %} diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py index 3939248a56c6..2a7e1185aee3 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py @@ -18,7 +18,7 @@ import os import json -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple from google.api_core import path_template from google.api_core.universe import EmptyUniverseError @@ -26,6 +26,8 @@ from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -42,6 +44,26 @@ def should_use_client_cert(): ) return use_client_cert == "true" + +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py index 182cfc6017bf..5d51d999e8d7 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py @@ -27,10 +27,10 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.asset_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.asset_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore + from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -331,12 +331,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert: - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() + client_cert_source = get_client_cert_source( + client_options.client_cert_source, use_client_cert + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -369,25 +366,6 @@ def _read_environment_variables(): raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -511,7 +489,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AssetServiceClient._read_environment_variables() - self._client_cert_source = AssetServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py index d11e9ab4594c..ea456b7ea6f4 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_asset_service.py @@ -132,20 +132,6 @@ def set_event_loop(): asyncio.set_event_loop(None) -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert AssetServiceClient._get_client_cert_source(None, False) is None - assert AssetServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AssetServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert AssetServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AssetServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - - @pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ (401, CRED_INFO_JSON, True), (403, CRED_INFO_JSON, True), diff --git a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_compat.py index 8b4a96c2bed3..37795ed23ccd 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_compat.py @@ -24,7 +24,7 @@ import google.auth.transport.mtls from google.cloud.asset_v1._compat import transcode_request -from google.cloud.asset_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.asset_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.auth.exceptions import MutualTLSChannelError from google.api_core.universe import EmptyUniverseError @@ -411,3 +411,17 @@ def test_transcode_request_proto_plus_wrapper(): transcoded, _, _ = transcode_request(http_options, mock_proto_plus) assert transcoded["uri"] == "/v1/test/proto-plus-field" + + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/_compat.py index 3939248a56c6..2a7e1185aee3 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/_compat.py @@ -18,7 +18,7 @@ import os import json -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple from google.api_core import path_template from google.api_core.universe import EmptyUniverseError @@ -26,6 +26,8 @@ from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -42,6 +44,26 @@ def should_use_client_cert(): ) return use_client_cert == "true" + +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py index 4a3cb7bad6c3..9041a0ecf190 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py @@ -27,10 +27,10 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.iam.credentials_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.iam.credentials_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore + from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -268,12 +268,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert: - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() + client_cert_source = get_client_cert_source( + client_options.client_cert_source, use_client_cert + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -306,25 +303,6 @@ def _read_environment_variables(): raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -448,7 +426,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = IAMCredentialsClient._read_environment_variables() - self._client_cert_source = IAMCredentialsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_compat.py index 3f773f27c7a9..c905c95d0800 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_compat.py @@ -24,7 +24,7 @@ import google.auth.transport.mtls from google.iam.credentials_v1._compat import transcode_request -from google.iam.credentials_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.iam.credentials_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.auth.exceptions import MutualTLSChannelError from google.api_core.universe import EmptyUniverseError @@ -411,3 +411,17 @@ def test_transcode_request_proto_plus_wrapper(): transcoded, _, _ = transcode_request(http_options, mock_proto_plus) assert transcoded["uri"] == "/v1/test/proto-plus-field" + + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py index a13fa010afd5..24e22e5a7484 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_iam_credentials.py @@ -123,20 +123,6 @@ def set_event_loop(): asyncio.set_event_loop(None) -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert IAMCredentialsClient._get_client_cert_source(None, False) is None - assert IAMCredentialsClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert IAMCredentialsClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert IAMCredentialsClient._get_client_cert_source(None, True) is mock_default_cert_source - assert IAMCredentialsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - - @pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ (401, CRED_INFO_JSON, True), (403, CRED_INFO_JSON, True), diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/_compat.py index 3939248a56c6..2a7e1185aee3 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/_compat.py @@ -18,7 +18,7 @@ import os import json -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple from google.api_core import path_template from google.api_core.universe import EmptyUniverseError @@ -26,6 +26,8 @@ from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -42,6 +44,26 @@ def should_use_client_cert(): ) return use_client_cert == "true" + +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py index b015982530cc..62607defcd7f 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py @@ -27,10 +27,10 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.eventarc_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.eventarc_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore + from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -451,12 +451,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert: - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() + client_cert_source = get_client_cert_source( + client_options.client_cert_source, use_client_cert + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -489,25 +486,6 @@ def _read_environment_variables(): raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -631,7 +609,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = EventarcClient._read_environment_variables() - self._client_cert_source = EventarcClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_compat.py index 216dbd2a5eac..f01ebcf7d16f 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_compat.py @@ -24,7 +24,7 @@ import google.auth.transport.mtls from google.cloud.eventarc_v1._compat import transcode_request -from google.cloud.eventarc_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.eventarc_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.auth.exceptions import MutualTLSChannelError from google.api_core.universe import EmptyUniverseError @@ -411,3 +411,17 @@ def test_transcode_request_proto_plus_wrapper(): transcoded, _, _ = transcode_request(http_options, mock_proto_plus) assert transcoded["uri"] == "/v1/test/proto-plus-field" + + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py index 7d3e259be19a..fbcef3f9fe03 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_eventarc.py @@ -151,20 +151,6 @@ def set_event_loop(): asyncio.set_event_loop(None) -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert EventarcClient._get_client_cert_source(None, False) is None - assert EventarcClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert EventarcClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert EventarcClient._get_client_cert_source(None, True) is mock_default_cert_source - assert EventarcClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - - @pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ (401, CRED_INFO_JSON, True), (403, CRED_INFO_JSON, True), diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/_compat.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/_compat.py index 3939248a56c6..2a7e1185aee3 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/_compat.py @@ -18,7 +18,7 @@ import os import json -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple from google.api_core import path_template from google.api_core.universe import EmptyUniverseError @@ -26,6 +26,8 @@ from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -42,6 +44,26 @@ def should_use_client_cert(): ) return use_client_cert == "true" + +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py index 36468f3d26c7..a4d5aeb751ed 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py @@ -27,10 +27,10 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore + from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -327,12 +327,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert: - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() + client_cert_source = get_client_cert_source( + client_options.client_cert_source, use_client_cert + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -365,25 +362,6 @@ def _read_environment_variables(): raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -504,7 +482,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ConfigServiceV2Client._read_environment_variables() - self._client_cert_source = ConfigServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py index 6009409d3685..db44bfb75a0a 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -27,10 +27,10 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore + from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -258,12 +258,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert: - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() + client_cert_source = get_client_cert_source( + client_options.client_cert_source, use_client_cert + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -296,25 +293,6 @@ def _read_environment_variables(): raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -435,7 +413,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = LoggingServiceV2Client._read_environment_variables() - self._client_cert_source = LoggingServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py index 1c353672fae1..802269d0e28c 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -27,10 +27,10 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore + from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -259,12 +259,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert: - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() + client_cert_source = get_client_cert_source( + client_options.client_cert_source, use_client_cert + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -297,25 +294,6 @@ def _read_environment_variables(): raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -436,7 +414,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = MetricsServiceV2Client._read_environment_variables() - self._client_cert_source = MetricsServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_compat.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_compat.py index b00995f3ec98..53c3958c271e 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_compat.py @@ -24,7 +24,7 @@ import google.auth.transport.mtls from google.cloud.logging_v2._compat import transcode_request -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.auth.exceptions import MutualTLSChannelError from google.api_core.universe import EmptyUniverseError @@ -411,3 +411,17 @@ def test_transcode_request_proto_plus_wrapper(): transcoded, _, _ = transcode_request(http_options, mock_proto_plus) assert transcoded["uri"] == "/v1/test/proto-plus-field" + + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py index 638aac7a87f8..acb0243b078f 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_config_service_v2.py @@ -124,20 +124,6 @@ def set_event_loop(): asyncio.set_event_loop(None) -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert ConfigServiceV2Client._get_client_cert_source(None, False) is None - assert ConfigServiceV2Client._get_client_cert_source(mock_provided_cert_source, False) is None - assert ConfigServiceV2Client._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert ConfigServiceV2Client._get_client_cert_source(None, True) is mock_default_cert_source - assert ConfigServiceV2Client._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - - @pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ (401, CRED_INFO_JSON, True), (403, CRED_INFO_JSON, True), diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py index 7ae37ba069aa..b6cccccbfa2b 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_logging_service_v2.py @@ -119,20 +119,6 @@ def set_event_loop(): asyncio.set_event_loop(None) -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert LoggingServiceV2Client._get_client_cert_source(None, False) is None - assert LoggingServiceV2Client._get_client_cert_source(mock_provided_cert_source, False) is None - assert LoggingServiceV2Client._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert LoggingServiceV2Client._get_client_cert_source(None, True) is mock_default_cert_source - assert LoggingServiceV2Client._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - - @pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ (401, CRED_INFO_JSON, True), (403, CRED_INFO_JSON, True), diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py index ee3b7e7f1005..a580bf6bc4c0 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_metrics_service_v2.py @@ -120,20 +120,6 @@ def set_event_loop(): asyncio.set_event_loop(None) -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert MetricsServiceV2Client._get_client_cert_source(None, False) is None - assert MetricsServiceV2Client._get_client_cert_source(mock_provided_cert_source, False) is None - assert MetricsServiceV2Client._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert MetricsServiceV2Client._get_client_cert_source(None, True) is mock_default_cert_source - assert MetricsServiceV2Client._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - - @pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ (401, CRED_INFO_JSON, True), (403, CRED_INFO_JSON, True), diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/_compat.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/_compat.py index 3939248a56c6..2a7e1185aee3 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/_compat.py @@ -18,7 +18,7 @@ import os import json -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple from google.api_core import path_template from google.api_core.universe import EmptyUniverseError @@ -26,6 +26,8 @@ from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -42,6 +44,26 @@ def should_use_client_cert(): ) return use_client_cert == "true" + +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py index 0b3b7c49baba..6f355bf3c3c7 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py @@ -27,10 +27,10 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore + from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -327,12 +327,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert: - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() + client_cert_source = get_client_cert_source( + client_options.client_cert_source, use_client_cert + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -365,25 +362,6 @@ def _read_environment_variables(): raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -504,7 +482,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = BaseConfigServiceV2Client._read_environment_variables() - self._client_cert_source = BaseConfigServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py index 6009409d3685..db44bfb75a0a 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -27,10 +27,10 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore + from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -258,12 +258,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert: - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() + client_cert_source = get_client_cert_source( + client_options.client_cert_source, use_client_cert + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -296,25 +293,6 @@ def _read_environment_variables(): raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -435,7 +413,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = LoggingServiceV2Client._read_environment_variables() - self._client_cert_source = LoggingServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py index 7581350f8ec8..60c8f46b8277 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -27,10 +27,10 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore + from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -259,12 +259,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert: - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() + client_cert_source = get_client_cert_source( + client_options.client_cert_source, use_client_cert + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -297,25 +294,6 @@ def _read_environment_variables(): raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -436,7 +414,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = BaseMetricsServiceV2Client._read_environment_variables() - self._client_cert_source = BaseMetricsServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_compat.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_compat.py index b00995f3ec98..53c3958c271e 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_compat.py @@ -24,7 +24,7 @@ import google.auth.transport.mtls from google.cloud.logging_v2._compat import transcode_request -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.auth.exceptions import MutualTLSChannelError from google.api_core.universe import EmptyUniverseError @@ -411,3 +411,17 @@ def test_transcode_request_proto_plus_wrapper(): transcoded, _, _ = transcode_request(http_options, mock_proto_plus) assert transcoded["uri"] == "/v1/test/proto-plus-field" + + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py index c63237e51f6c..1fe9695ee5fd 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_config_service_v2.py @@ -124,20 +124,6 @@ def set_event_loop(): asyncio.set_event_loop(None) -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert BaseConfigServiceV2Client._get_client_cert_source(None, False) is None - assert BaseConfigServiceV2Client._get_client_cert_source(mock_provided_cert_source, False) is None - assert BaseConfigServiceV2Client._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert BaseConfigServiceV2Client._get_client_cert_source(None, True) is mock_default_cert_source - assert BaseConfigServiceV2Client._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - - @pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ (401, CRED_INFO_JSON, True), (403, CRED_INFO_JSON, True), diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py index 7ae37ba069aa..b6cccccbfa2b 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_logging_service_v2.py @@ -119,20 +119,6 @@ def set_event_loop(): asyncio.set_event_loop(None) -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert LoggingServiceV2Client._get_client_cert_source(None, False) is None - assert LoggingServiceV2Client._get_client_cert_source(mock_provided_cert_source, False) is None - assert LoggingServiceV2Client._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert LoggingServiceV2Client._get_client_cert_source(None, True) is mock_default_cert_source - assert LoggingServiceV2Client._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - - @pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ (401, CRED_INFO_JSON, True), (403, CRED_INFO_JSON, True), diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py index 01e7a1f9c9ff..6ef833df9eb9 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_metrics_service_v2.py @@ -120,20 +120,6 @@ def set_event_loop(): asyncio.set_event_loop(None) -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert BaseMetricsServiceV2Client._get_client_cert_source(None, False) is None - assert BaseMetricsServiceV2Client._get_client_cert_source(mock_provided_cert_source, False) is None - assert BaseMetricsServiceV2Client._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert BaseMetricsServiceV2Client._get_client_cert_source(None, True) is mock_default_cert_source - assert BaseMetricsServiceV2Client._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - - @pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ (401, CRED_INFO_JSON, True), (403, CRED_INFO_JSON, True), diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/_compat.py index 3939248a56c6..2a7e1185aee3 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/_compat.py @@ -18,7 +18,7 @@ import os import json -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple from google.api_core import path_template from google.api_core.universe import EmptyUniverseError @@ -26,6 +26,8 @@ from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -42,6 +44,26 @@ def should_use_client_cert(): ) return use_client_cert == "true" + +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py index add3e3f67f59..81ce4197beb9 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py @@ -27,10 +27,10 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore + from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -296,12 +296,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert: - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() + client_cert_source = get_client_cert_source( + client_options.client_cert_source, use_client_cert + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -334,25 +331,6 @@ def _read_environment_variables(): raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -476,7 +454,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = CloudRedisClient._read_environment_variables() - self._client_cert_source = CloudRedisClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py index 4b9551493b1f..87edf53d87ee 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -138,20 +138,6 @@ def set_event_loop(): asyncio.set_event_loop(None) -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert CloudRedisClient._get_client_cert_source(None, False) is None - assert CloudRedisClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert CloudRedisClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert CloudRedisClient._get_client_cert_source(None, True) is mock_default_cert_source - assert CloudRedisClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - - @pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ (401, CRED_INFO_JSON, True), (403, CRED_INFO_JSON, True), diff --git a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_compat.py index afdac041c9e1..74dd950aa484 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_compat.py @@ -24,7 +24,7 @@ import google.auth.transport.mtls from google.cloud.redis_v1._compat import transcode_request -from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.auth.exceptions import MutualTLSChannelError from google.api_core.universe import EmptyUniverseError @@ -411,3 +411,17 @@ def test_transcode_request_proto_plus_wrapper(): transcoded, _, _ = transcode_request(http_options, mock_proto_plus) assert transcoded["uri"] == "/v1/test/proto-plus-field" + + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/_compat.py index 3939248a56c6..2a7e1185aee3 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/_compat.py @@ -18,7 +18,7 @@ import os import json -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple from google.api_core import path_template from google.api_core.universe import EmptyUniverseError @@ -26,6 +26,8 @@ from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -42,6 +44,26 @@ def should_use_client_cert(): ) return use_client_cert == "true" + +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py index 1f6885be1999..92ea6330271a 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py @@ -27,10 +27,10 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore + from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -296,12 +296,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert: - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() + client_cert_source = get_client_cert_source( + client_options.client_cert_source, use_client_cert + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -334,25 +331,6 @@ def _read_environment_variables(): raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -476,7 +454,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = CloudRedisClient._read_environment_variables() - self._client_cert_source = CloudRedisClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py index bebb9731a541..15a7783410db 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_cloud_redis.py @@ -138,20 +138,6 @@ def set_event_loop(): asyncio.set_event_loop(None) -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert CloudRedisClient._get_client_cert_source(None, False) is None - assert CloudRedisClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert CloudRedisClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert CloudRedisClient._get_client_cert_source(None, True) is mock_default_cert_source - assert CloudRedisClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - - @pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ (401, CRED_INFO_JSON, True), (403, CRED_INFO_JSON, True), diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_compat.py index afdac041c9e1..74dd950aa484 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_compat.py @@ -24,7 +24,7 @@ import google.auth.transport.mtls from google.cloud.redis_v1._compat import transcode_request -from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.auth.exceptions import MutualTLSChannelError from google.api_core.universe import EmptyUniverseError @@ -411,3 +411,17 @@ def test_transcode_request_proto_plus_wrapper(): transcoded, _, _ = transcode_request(http_options, mock_proto_plus) assert transcoded["uri"] == "/v1/test/proto-plus-field" + + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/_compat.py index ffa58f4f04eb..59da6ef05f2a 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/_compat.py @@ -19,7 +19,7 @@ import json import uuid -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple from typing import Union import google.protobuf.message @@ -30,6 +30,8 @@ from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -46,6 +48,26 @@ def should_use_client_cert(): ) return use_client_cert == "true" + +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py index d8c6bd9009a7..5714b9de644e 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py @@ -28,11 +28,11 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.storagebatchoperations_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.storagebatchoperations_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.cloud.storagebatchoperations_v1._compat import setup_request_id from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore + from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -292,12 +292,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert: - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() + client_cert_source = get_client_cert_source( + client_options.client_cert_source, use_client_cert + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -330,25 +327,6 @@ def _read_environment_variables(): raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") return use_client_cert, use_mtls_endpoint, universe_domain_env - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -472,7 +450,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = StorageBatchOperationsClient._read_environment_variables() - self._client_cert_source = StorageBatchOperationsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_compat.py index 0fb9cbb72fd5..ae07aa48f967 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_compat.py @@ -25,7 +25,7 @@ import google.auth.transport.mtls from google.cloud.storagebatchoperations_v1._compat import transcode_request -from google.cloud.storagebatchoperations_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert +from google.cloud.storagebatchoperations_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.cloud.storagebatchoperations_v1._compat import setup_request_id from google.auth.exceptions import MutualTLSChannelError @@ -494,3 +494,17 @@ def test_transcode_request_proto_plus_wrapper(): transcoded, _, _ = transcode_request(http_options, mock_proto_plus) assert transcoded["uri"] == "/v1/test/proto-plus-field" + + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py index 8086a2abdf4e..692d98df6158 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_storage_batch_operations.py @@ -132,20 +132,6 @@ def set_event_loop(): asyncio.set_event_loop(None) -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert StorageBatchOperationsClient._get_client_cert_source(None, False) is None - assert StorageBatchOperationsClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert StorageBatchOperationsClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert StorageBatchOperationsClient._get_client_cert_source(None, True) is mock_default_cert_source - assert StorageBatchOperationsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - - @pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ (401, CRED_INFO_JSON, True), (403, CRED_INFO_JSON, True), From fd0d16aa57b7ad6b47076e3b81d1fc8b457bc063 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Tue, 4 Aug 2026 22:21:03 +0000 Subject: [PATCH 2/9] Update goldens --- .../%name_%version/%sub/services/%service/client.py.j2 | 1 - .../asset/google/cloud/asset_v1/services/asset_service/client.py | 1 - .../google/iam/credentials_v1/services/iam_credentials/client.py | 1 - .../google/cloud/eventarc_v1/services/eventarc/client.py | 1 - .../google/cloud/logging_v2/services/config_service_v2/client.py | 1 - .../cloud/logging_v2/services/logging_service_v2/client.py | 1 - .../cloud/logging_v2/services/metrics_service_v2/client.py | 1 - .../google/cloud/logging_v2/services/config_service_v2/client.py | 1 - .../cloud/logging_v2/services/logging_service_v2/client.py | 1 - .../cloud/logging_v2/services/metrics_service_v2/client.py | 1 - .../redis/google/cloud/redis_v1/services/cloud_redis/client.py | 1 - .../google/cloud/redis_v1/services/cloud_redis/client.py | 1 - .../services/storage_batch_operations/client.py | 1 - 13 files changed, 13 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 index ad0ee82359d5..dba97c0d343c 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 @@ -36,7 +36,6 @@ from {{package_path}}._compat import setup_request_id {% endif %} from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore - from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py index 5d51d999e8d7..96051a35baaf 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py @@ -30,7 +30,6 @@ from google.cloud.asset_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore - from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py index 9041a0ecf190..7da380c30cef 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py @@ -30,7 +30,6 @@ from google.iam.credentials_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore - from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py index 62607defcd7f..9c5882bf2226 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py @@ -30,7 +30,6 @@ from google.cloud.eventarc_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore - from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py index a4d5aeb751ed..a0aff2b4d44d 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py @@ -30,7 +30,6 @@ from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore - from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py index db44bfb75a0a..3e21f91ccef6 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -30,7 +30,6 @@ from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore - from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py index 802269d0e28c..fe30c09b7b26 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -30,7 +30,6 @@ from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore - from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py index 6f355bf3c3c7..5dd746319dea 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py @@ -30,7 +30,6 @@ from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore - from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py index db44bfb75a0a..3e21f91ccef6 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -30,7 +30,6 @@ from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore - from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py index 60c8f46b8277..5a6a29272f06 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -30,7 +30,6 @@ from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore - from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py index 81ce4197beb9..0ff116dc7a48 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py @@ -30,7 +30,6 @@ from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore - from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py index 92ea6330271a..6b29e91342f7 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py @@ -30,7 +30,6 @@ from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore - from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py index 5714b9de644e..5682f95ae868 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py @@ -32,7 +32,6 @@ from google.cloud.storagebatchoperations_v1._compat import setup_request_id from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore - from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore From cd4b5c960c8785eebd63a73fb0487b3ac8a7aacc Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Wed, 5 Aug 2026 05:18:36 +0000 Subject: [PATCH 3/9] update goldens --- .../templates/%namespace/%name_%version/%sub/_compat.py.j2 | 2 +- .../integration/goldens/asset/google/cloud/asset_v1/_compat.py | 2 +- .../goldens/credentials/google/iam/credentials_v1/_compat.py | 2 +- .../goldens/eventarc/google/cloud/eventarc_v1/_compat.py | 2 +- .../goldens/logging/google/cloud/logging_v2/_compat.py | 2 +- .../goldens/logging_internal/google/cloud/logging_v2/_compat.py | 2 +- .../integration/goldens/redis/google/cloud/redis_v1/_compat.py | 2 +- .../goldens/redis_selective/google/cloud/redis_v1/_compat.py | 2 +- .../google/cloud/storagebatchoperations_v1/_compat.py | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 index cbe4a64c4cf9..8da6502a9cec 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 @@ -19,7 +19,7 @@ import json import uuid {% endif %} -from typing import Any, Callable, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple {% if has_auto_populated_fields %} from typing import Union {% endif %} diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py index 2a7e1185aee3..825801b77b81 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py @@ -18,7 +18,7 @@ import os import json -from typing import Any, Callable, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple from google.api_core import path_template from google.api_core.universe import EmptyUniverseError diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/_compat.py index 2a7e1185aee3..825801b77b81 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/_compat.py @@ -18,7 +18,7 @@ import os import json -from typing import Any, Callable, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple from google.api_core import path_template from google.api_core.universe import EmptyUniverseError diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/_compat.py index 2a7e1185aee3..825801b77b81 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/_compat.py @@ -18,7 +18,7 @@ import os import json -from typing import Any, Callable, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple from google.api_core import path_template from google.api_core.universe import EmptyUniverseError diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/_compat.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/_compat.py index 2a7e1185aee3..825801b77b81 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/_compat.py @@ -18,7 +18,7 @@ import os import json -from typing import Any, Callable, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple from google.api_core import path_template from google.api_core.universe import EmptyUniverseError diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/_compat.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/_compat.py index 2a7e1185aee3..825801b77b81 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/_compat.py @@ -18,7 +18,7 @@ import os import json -from typing import Any, Callable, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple from google.api_core import path_template from google.api_core.universe import EmptyUniverseError diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/_compat.py index 2a7e1185aee3..825801b77b81 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/_compat.py @@ -18,7 +18,7 @@ import os import json -from typing import Any, Callable, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple from google.api_core import path_template from google.api_core.universe import EmptyUniverseError diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/_compat.py index 2a7e1185aee3..825801b77b81 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/_compat.py @@ -18,7 +18,7 @@ import os import json -from typing import Any, Callable, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple from google.api_core import path_template from google.api_core.universe import EmptyUniverseError diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/_compat.py index 59da6ef05f2a..5a850fc8ef87 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/_compat.py @@ -19,7 +19,7 @@ import json import uuid -from typing import Any, Callable, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple from typing import Union import google.protobuf.message From 5aeaa6070401fec53571f0b48ae5a39b5e4620bf Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Thu, 6 Aug 2026 01:06:35 +0000 Subject: [PATCH 4/9] update goldens --- .../%name_%version/%sub/_compat.py.j2 | 15 +++++-------- .../%sub/services/%service/client.py.j2 | 4 ++-- .../%name_%version/%sub/test_compat.py.j2 | 22 ++++++++++++------- .../asset/google/cloud/asset_v1/_compat.py | 15 +++++-------- .../asset_v1/services/asset_service/client.py | 4 ++-- .../tests/unit/gapic/asset_v1/test_compat.py | 22 ++++++++++++------- .../google/iam/credentials_v1/_compat.py | 15 +++++-------- .../services/iam_credentials/client.py | 4 ++-- .../unit/gapic/credentials_v1/test_compat.py | 22 ++++++++++++------- .../google/cloud/eventarc_v1/_compat.py | 15 +++++-------- .../eventarc_v1/services/eventarc/client.py | 4 ++-- .../unit/gapic/eventarc_v1/test_compat.py | 22 ++++++++++++------- .../google/cloud/logging_v2/_compat.py | 15 +++++-------- .../services/config_service_v2/client.py | 4 ++-- .../services/logging_service_v2/client.py | 4 ++-- .../services/metrics_service_v2/client.py | 4 ++-- .../unit/gapic/logging_v2/test_compat.py | 22 ++++++++++++------- .../google/cloud/logging_v2/_compat.py | 15 +++++-------- .../services/config_service_v2/client.py | 4 ++-- .../services/logging_service_v2/client.py | 4 ++-- .../services/metrics_service_v2/client.py | 4 ++-- .../unit/gapic/logging_v2/test_compat.py | 22 ++++++++++++------- .../redis/google/cloud/redis_v1/_compat.py | 15 +++++-------- .../redis_v1/services/cloud_redis/client.py | 4 ++-- .../tests/unit/gapic/redis_v1/test_compat.py | 22 ++++++++++++------- .../google/cloud/redis_v1/_compat.py | 15 +++++-------- .../redis_v1/services/cloud_redis/client.py | 4 ++-- .../tests/unit/gapic/redis_v1/test_compat.py | 22 ++++++++++++------- .../storagebatchoperations_v1/_compat.py | 15 +++++-------- .../storage_batch_operations/client.py | 4 ++-- .../storagebatchoperations_v1/test_compat.py | 22 ++++++++++++------- 31 files changed, 197 insertions(+), 188 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 index 8da6502a9cec..3fe26116be6c 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 @@ -55,23 +55,18 @@ except ImportError: # pragma: NO COVER return use_client_cert == "true" -def get_client_cert_source(provided_cert_source, use_cert_flag): +def get_client_cert_source(provided_cert_source): """Return the client cert source to be used by the client. Args: provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - Returns: bytes or None: The client cert source to be used by the client. """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source + if should_use_client_cert(): + return provided_cert_source or ( + mtls.default_client_cert_source() if mtls.has_default_client_cert_source() else None + ) DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 index dba97c0d343c..8b555831992a 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 @@ -276,7 +276,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): # Figure out the client cert source to use. client_cert_source = get_client_cert_source( - client_options.client_cert_source, use_client_cert + client_options.client_cert_source ) # Figure out which api endpoint to use. @@ -439,7 +439,7 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = {{ service.client_name }}._read_environment_variables() - self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 index 5e75e945a13f..641596d6ac30 100644 --- a/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 +++ b/packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2 @@ -502,13 +502,19 @@ def test_get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() - assert get_client_cert_source(None, False) is None - assert get_client_cert_source(mock_provided_cert_source, False) is None - assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): - with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): - assert get_client_cert_source(None, True) is mock_default_cert_source - assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert get_client_cert_source(None) is None + assert get_client_cert_source(mock_provided_cert_source) is None + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert get_client_cert_source(mock_provided_cert_source) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source) is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None) is None {% endblock %} diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py index 825801b77b81..ad14d8b88c6f 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py @@ -45,23 +45,18 @@ def should_use_client_cert(): return use_client_cert == "true" -def get_client_cert_source(provided_cert_source, use_cert_flag): +def get_client_cert_source(provided_cert_source): """Return the client cert source to be used by the client. Args: provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - Returns: bytes or None: The client cert source to be used by the client. """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source + if should_use_client_cert(): + return provided_cert_source or ( + mtls.default_client_cert_source() if mtls.has_default_client_cert_source() else None + ) DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py index 96051a35baaf..1aa12c6c4e10 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py @@ -331,7 +331,7 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out the client cert source to use. client_cert_source = get_client_cert_source( - client_options.client_cert_source, use_client_cert + client_options.client_cert_source ) # Figure out which api endpoint to use. @@ -488,7 +488,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AssetServiceClient._read_environment_variables() - self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_compat.py index 37795ed23ccd..55930648e240 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_compat.py @@ -417,11 +417,17 @@ def test_get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() - assert get_client_cert_source(None, False) is None - assert get_client_cert_source(mock_provided_cert_source, False) is None - assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): - with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): - assert get_client_cert_source(None, True) is mock_default_cert_source - assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert get_client_cert_source(None) is None + assert get_client_cert_source(mock_provided_cert_source) is None + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert get_client_cert_source(mock_provided_cert_source) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source) is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None) is None diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/_compat.py index 825801b77b81..ad14d8b88c6f 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/_compat.py @@ -45,23 +45,18 @@ def should_use_client_cert(): return use_client_cert == "true" -def get_client_cert_source(provided_cert_source, use_cert_flag): +def get_client_cert_source(provided_cert_source): """Return the client cert source to be used by the client. Args: provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - Returns: bytes or None: The client cert source to be used by the client. """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source + if should_use_client_cert(): + return provided_cert_source or ( + mtls.default_client_cert_source() if mtls.has_default_client_cert_source() else None + ) DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py index 7da380c30cef..b7c6c906a7b1 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py @@ -268,7 +268,7 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out the client cert source to use. client_cert_source = get_client_cert_source( - client_options.client_cert_source, use_client_cert + client_options.client_cert_source ) # Figure out which api endpoint to use. @@ -425,7 +425,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = IAMCredentialsClient._read_environment_variables() - self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_compat.py index c905c95d0800..760f061fa75b 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_compat.py @@ -417,11 +417,17 @@ def test_get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() - assert get_client_cert_source(None, False) is None - assert get_client_cert_source(mock_provided_cert_source, False) is None - assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): - with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): - assert get_client_cert_source(None, True) is mock_default_cert_source - assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert get_client_cert_source(None) is None + assert get_client_cert_source(mock_provided_cert_source) is None + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert get_client_cert_source(mock_provided_cert_source) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source) is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None) is None diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/_compat.py index 825801b77b81..ad14d8b88c6f 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/_compat.py @@ -45,23 +45,18 @@ def should_use_client_cert(): return use_client_cert == "true" -def get_client_cert_source(provided_cert_source, use_cert_flag): +def get_client_cert_source(provided_cert_source): """Return the client cert source to be used by the client. Args: provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - Returns: bytes or None: The client cert source to be used by the client. """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source + if should_use_client_cert(): + return provided_cert_source or ( + mtls.default_client_cert_source() if mtls.has_default_client_cert_source() else None + ) DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py index 9c5882bf2226..ed2ef3aeb518 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py @@ -451,7 +451,7 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out the client cert source to use. client_cert_source = get_client_cert_source( - client_options.client_cert_source, use_client_cert + client_options.client_cert_source ) # Figure out which api endpoint to use. @@ -608,7 +608,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = EventarcClient._read_environment_variables() - self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_compat.py index f01ebcf7d16f..09ef76eb6fc4 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_compat.py @@ -417,11 +417,17 @@ def test_get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() - assert get_client_cert_source(None, False) is None - assert get_client_cert_source(mock_provided_cert_source, False) is None - assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): - with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): - assert get_client_cert_source(None, True) is mock_default_cert_source - assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert get_client_cert_source(None) is None + assert get_client_cert_source(mock_provided_cert_source) is None + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert get_client_cert_source(mock_provided_cert_source) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source) is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None) is None diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/_compat.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/_compat.py index 825801b77b81..ad14d8b88c6f 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/_compat.py @@ -45,23 +45,18 @@ def should_use_client_cert(): return use_client_cert == "true" -def get_client_cert_source(provided_cert_source, use_cert_flag): +def get_client_cert_source(provided_cert_source): """Return the client cert source to be used by the client. Args: provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - Returns: bytes or None: The client cert source to be used by the client. """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source + if should_use_client_cert(): + return provided_cert_source or ( + mtls.default_client_cert_source() if mtls.has_default_client_cert_source() else None + ) DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py index a0aff2b4d44d..eecba763c838 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py @@ -327,7 +327,7 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out the client cert source to use. client_cert_source = get_client_cert_source( - client_options.client_cert_source, use_client_cert + client_options.client_cert_source ) # Figure out which api endpoint to use. @@ -481,7 +481,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ConfigServiceV2Client._read_environment_variables() - self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py index 3e21f91ccef6..ba931dccdda8 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -258,7 +258,7 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out the client cert source to use. client_cert_source = get_client_cert_source( - client_options.client_cert_source, use_client_cert + client_options.client_cert_source ) # Figure out which api endpoint to use. @@ -412,7 +412,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = LoggingServiceV2Client._read_environment_variables() - self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py index fe30c09b7b26..21f0b6bce7cd 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -259,7 +259,7 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out the client cert source to use. client_cert_source = get_client_cert_source( - client_options.client_cert_source, use_client_cert + client_options.client_cert_source ) # Figure out which api endpoint to use. @@ -413,7 +413,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = MetricsServiceV2Client._read_environment_variables() - self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_compat.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_compat.py index 53c3958c271e..911d5e66debf 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_compat.py @@ -417,11 +417,17 @@ def test_get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() - assert get_client_cert_source(None, False) is None - assert get_client_cert_source(mock_provided_cert_source, False) is None - assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): - with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): - assert get_client_cert_source(None, True) is mock_default_cert_source - assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert get_client_cert_source(None) is None + assert get_client_cert_source(mock_provided_cert_source) is None + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert get_client_cert_source(mock_provided_cert_source) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source) is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None) is None diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/_compat.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/_compat.py index 825801b77b81..ad14d8b88c6f 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/_compat.py @@ -45,23 +45,18 @@ def should_use_client_cert(): return use_client_cert == "true" -def get_client_cert_source(provided_cert_source, use_cert_flag): +def get_client_cert_source(provided_cert_source): """Return the client cert source to be used by the client. Args: provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - Returns: bytes or None: The client cert source to be used by the client. """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source + if should_use_client_cert(): + return provided_cert_source or ( + mtls.default_client_cert_source() if mtls.has_default_client_cert_source() else None + ) DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py index 5dd746319dea..b74710845c13 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py @@ -327,7 +327,7 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out the client cert source to use. client_cert_source = get_client_cert_source( - client_options.client_cert_source, use_client_cert + client_options.client_cert_source ) # Figure out which api endpoint to use. @@ -481,7 +481,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = BaseConfigServiceV2Client._read_environment_variables() - self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py index 3e21f91ccef6..ba931dccdda8 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -258,7 +258,7 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out the client cert source to use. client_cert_source = get_client_cert_source( - client_options.client_cert_source, use_client_cert + client_options.client_cert_source ) # Figure out which api endpoint to use. @@ -412,7 +412,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = LoggingServiceV2Client._read_environment_variables() - self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py index 5a6a29272f06..ba03affb4ebe 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -259,7 +259,7 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out the client cert source to use. client_cert_source = get_client_cert_source( - client_options.client_cert_source, use_client_cert + client_options.client_cert_source ) # Figure out which api endpoint to use. @@ -413,7 +413,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = BaseMetricsServiceV2Client._read_environment_variables() - self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_compat.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_compat.py index 53c3958c271e..911d5e66debf 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_compat.py @@ -417,11 +417,17 @@ def test_get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() - assert get_client_cert_source(None, False) is None - assert get_client_cert_source(mock_provided_cert_source, False) is None - assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): - with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): - assert get_client_cert_source(None, True) is mock_default_cert_source - assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert get_client_cert_source(None) is None + assert get_client_cert_source(mock_provided_cert_source) is None + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert get_client_cert_source(mock_provided_cert_source) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source) is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None) is None diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/_compat.py index 825801b77b81..ad14d8b88c6f 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/_compat.py @@ -45,23 +45,18 @@ def should_use_client_cert(): return use_client_cert == "true" -def get_client_cert_source(provided_cert_source, use_cert_flag): +def get_client_cert_source(provided_cert_source): """Return the client cert source to be used by the client. Args: provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - Returns: bytes or None: The client cert source to be used by the client. """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source + if should_use_client_cert(): + return provided_cert_source or ( + mtls.default_client_cert_source() if mtls.has_default_client_cert_source() else None + ) DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py index 0ff116dc7a48..6a99829d1021 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py @@ -296,7 +296,7 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out the client cert source to use. client_cert_source = get_client_cert_source( - client_options.client_cert_source, use_client_cert + client_options.client_cert_source ) # Figure out which api endpoint to use. @@ -453,7 +453,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = CloudRedisClient._read_environment_variables() - self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_compat.py index 74dd950aa484..223d2b1808f9 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_compat.py @@ -417,11 +417,17 @@ def test_get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() - assert get_client_cert_source(None, False) is None - assert get_client_cert_source(mock_provided_cert_source, False) is None - assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): - with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): - assert get_client_cert_source(None, True) is mock_default_cert_source - assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert get_client_cert_source(None) is None + assert get_client_cert_source(mock_provided_cert_source) is None + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert get_client_cert_source(mock_provided_cert_source) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source) is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None) is None diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/_compat.py index 825801b77b81..ad14d8b88c6f 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/_compat.py @@ -45,23 +45,18 @@ def should_use_client_cert(): return use_client_cert == "true" -def get_client_cert_source(provided_cert_source, use_cert_flag): +def get_client_cert_source(provided_cert_source): """Return the client cert source to be used by the client. Args: provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - Returns: bytes or None: The client cert source to be used by the client. """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source + if should_use_client_cert(): + return provided_cert_source or ( + mtls.default_client_cert_source() if mtls.has_default_client_cert_source() else None + ) DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py index 6b29e91342f7..f3577d01a339 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py @@ -296,7 +296,7 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out the client cert source to use. client_cert_source = get_client_cert_source( - client_options.client_cert_source, use_client_cert + client_options.client_cert_source ) # Figure out which api endpoint to use. @@ -453,7 +453,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = CloudRedisClient._read_environment_variables() - self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_compat.py index 74dd950aa484..223d2b1808f9 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_compat.py @@ -417,11 +417,17 @@ def test_get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() - assert get_client_cert_source(None, False) is None - assert get_client_cert_source(mock_provided_cert_source, False) is None - assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): - with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): - assert get_client_cert_source(None, True) is mock_default_cert_source - assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert get_client_cert_source(None) is None + assert get_client_cert_source(mock_provided_cert_source) is None + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert get_client_cert_source(mock_provided_cert_source) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source) is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None) is None diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/_compat.py index 5a850fc8ef87..e50cf2d1ab99 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/_compat.py @@ -49,23 +49,18 @@ def should_use_client_cert(): return use_client_cert == "true" -def get_client_cert_source(provided_cert_source, use_cert_flag): +def get_client_cert_source(provided_cert_source): """Return the client cert source to be used by the client. Args: provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - Returns: bytes or None: The client cert source to be used by the client. """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source + if should_use_client_cert(): + return provided_cert_source or ( + mtls.default_client_cert_source() if mtls.has_default_client_cert_source() else None + ) DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py index 5682f95ae868..209dc41ba02b 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py @@ -292,7 +292,7 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out the client cert source to use. client_cert_source = get_client_cert_source( - client_options.client_cert_source, use_client_cert + client_options.client_cert_source ) # Figure out which api endpoint to use. @@ -449,7 +449,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = StorageBatchOperationsClient._read_environment_variables() - self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_compat.py index ae07aa48f967..9bc7a00baa12 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_compat.py @@ -500,11 +500,17 @@ def test_get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() - assert get_client_cert_source(None, False) is None - assert get_client_cert_source(mock_provided_cert_source, False) is None - assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): - with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): - assert get_client_cert_source(None, True) is mock_default_cert_source - assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert get_client_cert_source(None) is None + assert get_client_cert_source(mock_provided_cert_source) is None + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert get_client_cert_source(mock_provided_cert_source) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source) is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None) is None From 2bcdeea2ec6d443b7c2abe1118f152b8053d329e Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Thu, 6 Aug 2026 18:26:16 +0000 Subject: [PATCH 5/9] update template --- .../%name_%version/%sub/services/%service/client.py.j2 | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 index 8b555831992a..b493454fcd8e 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/client.py.j2 @@ -36,6 +36,7 @@ from {{package_path}}._compat import setup_request_id {% endif %} from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -275,9 +276,12 @@ class {{ service.client_name }}(metaclass={{ service.client_name }}Meta): raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = get_client_cert_source( - client_options.client_cert_source - ) + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() # Figure out which api endpoint to use. if client_options.api_endpoint is not None: From c39a07a13aa9342f70f4315ef9746bf98f71c93c Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Thu, 6 Aug 2026 19:02:24 +0000 Subject: [PATCH 6/9] update goldens --- .../cloud/asset_v1/services/asset_service/client.py | 10 +++++++--- .../credentials_v1/services/iam_credentials/client.py | 10 +++++++--- .../cloud/eventarc_v1/services/eventarc/client.py | 10 +++++++--- .../logging_v2/services/config_service_v2/client.py | 10 +++++++--- .../logging_v2/services/logging_service_v2/client.py | 10 +++++++--- .../logging_v2/services/metrics_service_v2/client.py | 10 +++++++--- .../logging_v2/services/config_service_v2/client.py | 10 +++++++--- .../logging_v2/services/logging_service_v2/client.py | 10 +++++++--- .../logging_v2/services/metrics_service_v2/client.py | 10 +++++++--- .../cloud/redis_v1/services/cloud_redis/client.py | 10 +++++++--- .../cloud/redis_v1/services/cloud_redis/client.py | 10 +++++++--- .../services/storage_batch_operations/client.py | 10 +++++++--- 12 files changed, 84 insertions(+), 36 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py index 1aa12c6c4e10..1b9a44789de5 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py @@ -30,6 +30,7 @@ from google.cloud.asset_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -330,9 +331,12 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = get_client_cert_source( - client_options.client_cert_source - ) + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() # Figure out which api endpoint to use. if client_options.api_endpoint is not None: diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py index b7c6c906a7b1..65083c3a5314 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py @@ -30,6 +30,7 @@ from google.iam.credentials_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -267,9 +268,12 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = get_client_cert_source( - client_options.client_cert_source - ) + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() # Figure out which api endpoint to use. if client_options.api_endpoint is not None: diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py index ed2ef3aeb518..a8259ef9691a 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py @@ -30,6 +30,7 @@ from google.cloud.eventarc_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -450,9 +451,12 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = get_client_cert_source( - client_options.client_cert_source - ) + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() # Figure out which api endpoint to use. if client_options.api_endpoint is not None: diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py index eecba763c838..6685d2de62f7 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py @@ -30,6 +30,7 @@ from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -326,9 +327,12 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = get_client_cert_source( - client_options.client_cert_source - ) + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() # Figure out which api endpoint to use. if client_options.api_endpoint is not None: diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py index ba931dccdda8..3e470757dde2 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -30,6 +30,7 @@ from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -257,9 +258,12 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = get_client_cert_source( - client_options.client_cert_source - ) + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() # Figure out which api endpoint to use. if client_options.api_endpoint is not None: diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py index 21f0b6bce7cd..09b9f0f02f13 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -30,6 +30,7 @@ from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -258,9 +259,12 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = get_client_cert_source( - client_options.client_cert_source - ) + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() # Figure out which api endpoint to use. if client_options.api_endpoint is not None: diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py index b74710845c13..4d675d4e28a4 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py @@ -30,6 +30,7 @@ from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -326,9 +327,12 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = get_client_cert_source( - client_options.client_cert_source - ) + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() # Figure out which api endpoint to use. if client_options.api_endpoint is not None: diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py index ba931dccdda8..3e470757dde2 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -30,6 +30,7 @@ from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -257,9 +258,12 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = get_client_cert_source( - client_options.client_cert_source - ) + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() # Figure out which api endpoint to use. if client_options.api_endpoint is not None: diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py index ba03affb4ebe..8af10ef2bb3f 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -30,6 +30,7 @@ from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -258,9 +259,12 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = get_client_cert_source( - client_options.client_cert_source - ) + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() # Figure out which api endpoint to use. if client_options.api_endpoint is not None: diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py index 6a99829d1021..09ce2f71bd1c 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py @@ -30,6 +30,7 @@ from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -295,9 +296,12 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = get_client_cert_source( - client_options.client_cert_source - ) + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() # Figure out which api endpoint to use. if client_options.api_endpoint is not None: diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py index f3577d01a339..eff60b126cf1 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py @@ -30,6 +30,7 @@ from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -295,9 +296,12 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = get_client_cert_source( - client_options.client_cert_source - ) + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() # Figure out which api endpoint to use. if client_options.api_endpoint is not None: diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py index 209dc41ba02b..8e832be46e4f 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py @@ -32,6 +32,7 @@ from google.cloud.storagebatchoperations_v1._compat import setup_request_id from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -291,9 +292,12 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") # Figure out the client cert source to use. - client_cert_source = get_client_cert_source( - client_options.client_cert_source - ) + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() # Figure out which api endpoint to use. if client_options.api_endpoint is not None: From 901e554a37b684d736ca3602bbc8a057bf7a6401 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Fri, 7 Aug 2026 00:15:37 +0000 Subject: [PATCH 7/9] update goldens --- .../asset/google/cloud/asset_v1/_compat.py | 21 +++++++++++++++++ .../asset_v1/services/asset_service/client.py | 23 ++----------------- .../tests/unit/gapic/asset_v1/test_compat.py | 19 ++++++++++++++- .../google/iam/credentials_v1/_compat.py | 21 +++++++++++++++++ .../services/iam_credentials/client.py | 23 ++----------------- .../unit/gapic/credentials_v1/test_compat.py | 19 ++++++++++++++- .../google/cloud/eventarc_v1/_compat.py | 21 +++++++++++++++++ .../eventarc_v1/services/eventarc/client.py | 23 ++----------------- .../unit/gapic/eventarc_v1/test_compat.py | 19 ++++++++++++++- .../google/cloud/logging_v2/_compat.py | 21 +++++++++++++++++ .../services/config_service_v2/client.py | 23 ++----------------- .../services/logging_service_v2/client.py | 23 ++----------------- .../services/metrics_service_v2/client.py | 23 ++----------------- .../unit/gapic/logging_v2/test_compat.py | 19 ++++++++++++++- .../google/cloud/logging_v2/_compat.py | 21 +++++++++++++++++ .../services/config_service_v2/client.py | 23 ++----------------- .../services/logging_service_v2/client.py | 23 ++----------------- .../services/metrics_service_v2/client.py | 23 ++----------------- .../unit/gapic/logging_v2/test_compat.py | 19 ++++++++++++++- .../redis/google/cloud/redis_v1/_compat.py | 21 +++++++++++++++++ .../redis_v1/services/cloud_redis/client.py | 23 ++----------------- .../tests/unit/gapic/redis_v1/test_compat.py | 19 ++++++++++++++- .../google/cloud/redis_v1/_compat.py | 21 +++++++++++++++++ .../redis_v1/services/cloud_redis/client.py | 23 ++----------------- .../tests/unit/gapic/redis_v1/test_compat.py | 19 ++++++++++++++- .../storagebatchoperations_v1/_compat.py | 21 +++++++++++++++++ .../storage_batch_operations/client.py | 23 ++----------------- .../storagebatchoperations_v1/test_compat.py | 19 ++++++++++++++- 28 files changed, 336 insertions(+), 260 deletions(-) diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py index cd597b06c87b..11d261cf0954 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/_compat.py @@ -26,6 +26,8 @@ from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -67,6 +69,25 @@ def read_environment_variables(): return use_client_cert, use_mtls_endpoint, universe_domain_env +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py index 1121cb71b64e..0f4f43a520b6 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/google/cloud/asset_v1/services/asset_service/client.py @@ -27,7 +27,7 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.asset_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.asset_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore @@ -348,25 +348,6 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio return api_endpoint, client_cert_source - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -490,7 +471,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = AssetServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_compat.py index df64f9d08916..b195f4284f3f 100755 --- a/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/asset/tests/unit/gapic/asset_v1/test_compat.py @@ -24,7 +24,7 @@ import google.auth.transport.mtls from google.cloud.asset_v1._compat import transcode_request -from google.cloud.asset_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.asset_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.auth.exceptions import MutualTLSChannelError from google.api_core.universe import EmptyUniverseError @@ -423,3 +423,20 @@ def test_read_environment_variables(): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "invalid"}): with pytest.raises(MutualTLSChannelError): read_environment_variables() + + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None, True) is None diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/_compat.py index cd597b06c87b..11d261cf0954 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/_compat.py @@ -26,6 +26,8 @@ from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -67,6 +69,25 @@ def read_environment_variables(): return use_client_cert, use_mtls_endpoint, universe_domain_env +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py index 835c762fe776..9efab07698ca 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/google/iam/credentials_v1/services/iam_credentials/client.py @@ -27,7 +27,7 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.iam.credentials_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.iam.credentials_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore @@ -285,25 +285,6 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio return api_endpoint, client_cert_source - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -427,7 +408,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = IAMCredentialsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_compat.py index 066f4505bdef..8c2675359bc8 100755 --- a/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/credentials/tests/unit/gapic/credentials_v1/test_compat.py @@ -24,7 +24,7 @@ import google.auth.transport.mtls from google.iam.credentials_v1._compat import transcode_request -from google.iam.credentials_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.iam.credentials_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.auth.exceptions import MutualTLSChannelError from google.api_core.universe import EmptyUniverseError @@ -423,3 +423,20 @@ def test_read_environment_variables(): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "invalid"}): with pytest.raises(MutualTLSChannelError): read_environment_variables() + + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None, True) is None diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/_compat.py index cd597b06c87b..11d261cf0954 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/_compat.py @@ -26,6 +26,8 @@ from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -67,6 +69,25 @@ def read_environment_variables(): return use_client_cert, use_mtls_endpoint, universe_domain_env +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py index f7027b05bcbd..60a4541c2f19 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/google/cloud/eventarc_v1/services/eventarc/client.py @@ -27,7 +27,7 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.eventarc_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.eventarc_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore @@ -468,25 +468,6 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio return api_endpoint, client_cert_source - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -610,7 +591,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = EventarcClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_compat.py index c73490e1195a..9299cb301a14 100755 --- a/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/eventarc/tests/unit/gapic/eventarc_v1/test_compat.py @@ -24,7 +24,7 @@ import google.auth.transport.mtls from google.cloud.eventarc_v1._compat import transcode_request -from google.cloud.eventarc_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.eventarc_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.auth.exceptions import MutualTLSChannelError from google.api_core.universe import EmptyUniverseError @@ -423,3 +423,20 @@ def test_read_environment_variables(): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "invalid"}): with pytest.raises(MutualTLSChannelError): read_environment_variables() + + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None, True) is None diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/_compat.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/_compat.py index cd597b06c87b..11d261cf0954 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/_compat.py @@ -26,6 +26,8 @@ from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -67,6 +69,25 @@ def read_environment_variables(): return use_client_cert, use_mtls_endpoint, universe_domain_env +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py index 62ea80691320..2ccce094d9d8 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/config_service_v2/client.py @@ -27,7 +27,7 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore @@ -344,25 +344,6 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio return api_endpoint, client_cert_source - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -483,7 +464,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = ConfigServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py index 2507e84cd049..8d4e110f574a 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -27,7 +27,7 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore @@ -275,25 +275,6 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio return api_endpoint, client_cert_source - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -414,7 +395,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = LoggingServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py index 4c96b9b45d0a..d082d8845cb3 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -27,7 +27,7 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore @@ -276,25 +276,6 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio return api_endpoint, client_cert_source - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -415,7 +396,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = MetricsServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_compat.py b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_compat.py index bce857df2a1d..21ef7116086d 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/logging/tests/unit/gapic/logging_v2/test_compat.py @@ -24,7 +24,7 @@ import google.auth.transport.mtls from google.cloud.logging_v2._compat import transcode_request -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.auth.exceptions import MutualTLSChannelError from google.api_core.universe import EmptyUniverseError @@ -423,3 +423,20 @@ def test_read_environment_variables(): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "invalid"}): with pytest.raises(MutualTLSChannelError): read_environment_variables() + + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None, True) is None diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/_compat.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/_compat.py index cd597b06c87b..11d261cf0954 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/_compat.py @@ -26,6 +26,8 @@ from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -67,6 +69,25 @@ def read_environment_variables(): return use_client_cert, use_mtls_endpoint, universe_domain_env +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py index 52cb67262f88..3deb3bdd4efd 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/config_service_v2/client.py @@ -27,7 +27,7 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore @@ -344,25 +344,6 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio return api_endpoint, client_cert_source - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -483,7 +464,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = BaseConfigServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py index 2507e84cd049..8d4e110f574a 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/logging_service_v2/client.py @@ -27,7 +27,7 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore @@ -275,25 +275,6 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio return api_endpoint, client_cert_source - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -414,7 +395,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = LoggingServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py index 6e6fe990f6a2..7e60628cc2fd 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/google/cloud/logging_v2/services/metrics_service_v2/client.py @@ -27,7 +27,7 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore @@ -276,25 +276,6 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio return api_endpoint, client_cert_source - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -415,7 +396,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = BaseMetricsServiceV2Client._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_compat.py b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_compat.py index bce857df2a1d..21ef7116086d 100755 --- a/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/logging_internal/tests/unit/gapic/logging_v2/test_compat.py @@ -24,7 +24,7 @@ import google.auth.transport.mtls from google.cloud.logging_v2._compat import transcode_request -from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.logging_v2._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.auth.exceptions import MutualTLSChannelError from google.api_core.universe import EmptyUniverseError @@ -423,3 +423,20 @@ def test_read_environment_variables(): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "invalid"}): with pytest.raises(MutualTLSChannelError): read_environment_variables() + + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None, True) is None diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/_compat.py index cd597b06c87b..11d261cf0954 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/_compat.py @@ -26,6 +26,8 @@ from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -67,6 +69,25 @@ def read_environment_variables(): return use_client_cert, use_mtls_endpoint, universe_domain_env +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py index dd14380a6c91..707ae16295a8 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/google/cloud/redis_v1/services/cloud_redis/client.py @@ -27,7 +27,7 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore @@ -313,25 +313,6 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio return api_endpoint, client_cert_source - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -455,7 +436,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = CloudRedisClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_compat.py index f7fe8e355981..bbaa06d25845 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/redis/tests/unit/gapic/redis_v1/test_compat.py @@ -24,7 +24,7 @@ import google.auth.transport.mtls from google.cloud.redis_v1._compat import transcode_request -from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.auth.exceptions import MutualTLSChannelError from google.api_core.universe import EmptyUniverseError @@ -423,3 +423,20 @@ def test_read_environment_variables(): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "invalid"}): with pytest.raises(MutualTLSChannelError): read_environment_variables() + + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None, True) is None diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/_compat.py index cd597b06c87b..11d261cf0954 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/_compat.py @@ -26,6 +26,8 @@ from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -67,6 +69,25 @@ def read_environment_variables(): return use_client_cert, use_mtls_endpoint, universe_domain_env +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py index 1c2a3de6f32d..f8b8264e2f26 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/google/cloud/redis_v1/services/cloud_redis/client.py @@ -27,7 +27,7 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore @@ -313,25 +313,6 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio return api_endpoint, client_cert_source - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -455,7 +436,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = CloudRedisClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_compat.py index f7fe8e355981..bbaa06d25845 100755 --- a/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/redis_selective/tests/unit/gapic/redis_v1/test_compat.py @@ -24,7 +24,7 @@ import google.auth.transport.mtls from google.cloud.redis_v1._compat import transcode_request -from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.redis_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.auth.exceptions import MutualTLSChannelError from google.api_core.universe import EmptyUniverseError @@ -423,3 +423,20 @@ def test_read_environment_variables(): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "invalid"}): with pytest.raises(MutualTLSChannelError): read_environment_variables() + + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None, True) is None diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/_compat.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/_compat.py index 87e049d32472..41ae87418cb8 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/_compat.py @@ -32,6 +32,8 @@ from google.protobuf import json_format from urllib.parse import urlparse, urlunparse +from google.auth.transport import mtls # type: ignore + try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once @@ -73,6 +75,25 @@ def read_environment_variables(): return use_client_cert, use_mtls_endpoint, universe_domain_env +def get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + DEFAULT_UNIVERSE = "googleapis.com" diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py index c066f52b0b1c..7ed4f90f4684 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/google/cloud/storagebatchoperations_v1/services/storage_batch_operations/client.py @@ -28,7 +28,7 @@ from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 -from google.cloud.storagebatchoperations_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.storagebatchoperations_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.cloud.storagebatchoperations_v1._compat import setup_request_id from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore @@ -309,25 +309,6 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio return api_endpoint, client_cert_source - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - def _validate_universe_domain(self): """Validates client's and credentials' universe domains are consistent. @@ -451,7 +432,7 @@ def __init__(self, *, universe_domain_opt = getattr(self._client_options, 'universe_domain', None) self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = read_environment_variables() - self._client_cert_source = StorageBatchOperationsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._client_cert_source = get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) self._universe_domain = get_universe_domain(universe_domain_opt, self._universe_domain_env) self._api_endpoint: str = "" # updated below, depending on `transport` diff --git a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_compat.py b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_compat.py index 94e6e93cf443..cb3cdbdc6b56 100755 --- a/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_compat.py +++ b/packages/gapic-generator/tests/integration/goldens/storagebatchoperations/tests/unit/gapic/storagebatchoperations_v1/test_compat.py @@ -25,7 +25,7 @@ import google.auth.transport.mtls from google.cloud.storagebatchoperations_v1._compat import transcode_request -from google.cloud.storagebatchoperations_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables +from google.cloud.storagebatchoperations_v1._compat import get_universe_domain, get_api_endpoint, get_default_mtls_endpoint, should_use_client_cert, read_environment_variables, get_client_cert_source from google.cloud.storagebatchoperations_v1._compat import setup_request_id from google.auth.exceptions import MutualTLSChannelError @@ -528,3 +528,20 @@ def test_read_environment_variables(): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "invalid"}): with pytest.raises(MutualTLSChannelError): read_environment_variables() + + +def test_get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert get_client_cert_source(None, False) is None + assert get_client_cert_source(mock_provided_cert_source, False) is None + assert get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=True): + with mock.patch("google.auth.transport.mtls.default_client_cert_source", return_value=mock_default_cert_source): + assert get_client_cert_source(None, True) is mock_default_cert_source + assert get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + assert get_client_cert_source(None, True) is None From 4dcd98de058e9b4d23263d176c6115c5ce93295d Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Fri, 7 Aug 2026 18:40:38 +0000 Subject: [PATCH 8/9] clean up comment --- .../templates/%namespace/%name_%version/%sub/_compat.py.j2 | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 index a6a11425e9a3..d1cc2c5ed6df 100644 --- a/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 +++ b/packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2 @@ -36,14 +36,13 @@ from urllib.parse import urlparse, urlunparse from google.auth.transport import mtls # type: ignore -{# TODO: Remove client cert compatibility fallbacks when the minimum supported -version of google-auth is >= 2.43.0 (currently 2.14.1+). #} try: # note: `#type: ignore` is added because the return type for `should_use_client_cert` # is different than that of the fallback implementation below. This will be removed once # we bump the minimum supported version of google-auth. from google.auth.transport.mtls import should_use_client_cert # type: ignore except ImportError: # pragma: NO COVER + {# TODO: Remove client cert compatibility fallbacks when the minimum supported version of google-auth is >= 2.43.0 (currently 2.14.1+). #} def should_use_client_cert(): """Returns whether client certificate should be used for mTLS.""" use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() From 1ac01bf16e6345484bbb37ed7dfcf08abf698922 Mon Sep 17 00:00:00 2001 From: Heba Alazzeh Date: Mon, 10 Aug 2026 20:04:55 +0000 Subject: [PATCH 9/9] feat(core): implement PEP 0810 explicit lazy imports in google-cloud-core This PR implements PEP 0810 explicit lazy imports in google-cloud-core. On Python 3.15+, this defers loading of heavy inner modules and third-party dependencies (grpcio, cryptography, requests, and protobuf descriptor pools) to reduce serverless cold starts and memory footprints. On Python 3.14 and below, this falls back safely to eager execution with zero backwards-compatibility risk. ### Related Links - GAPIC Implementation PR: #17591 - google-api-core gapic_v1 PR: #17673 - google-api-core operations_v1 PR: #17724 - google-auth transport PR: #17679 --- .../google/cloud/_helpers/__init__.py | 47 +++++++++++--- .../google/cloud/_http/__init__.py | 20 ++++-- .../google/cloud/client/__init__.py | 64 +++++++++++++------ .../google/cloud/exceptions/__init__.py | 29 +++++++-- .../google/cloud/operation/__init__.py | 21 ++++-- 5 files changed, 141 insertions(+), 40 deletions(-) diff --git a/packages/google-cloud-core/google/cloud/_helpers/__init__.py b/packages/google-cloud-core/google/cloud/_helpers/__init__.py index 7a198cc9d683..fd60ee00d5ad 100644 --- a/packages/google-cloud-core/google/cloud/_helpers/__init__.py +++ b/packages/google-cloud-core/google/cloud/_helpers/__init__.py @@ -22,20 +22,47 @@ import calendar import datetime import http.client +import importlib.util import os import re from threading import local as Local -from typing import Union - -import google.auth -import google.auth.transport.requests -from google.protobuf import duration_pb2 -from google.protobuf import timestamp_pb2 +from typing import Set, Union + +_has_grpc = importlib.util.find_spec("grpc") is not None + +# PEP 0810: Explicit Lazy Imports +# Python 3.15+ natively intercepts and defers these imports. +# Developers can disable this behavior and force eager imports. +# For more information, see: +# https://docs.python.org/3.15/library/sys.html#sys.set_lazy_imports_filter +# Older Python versions safely ignore this variable. +__lazy_modules__: Set[str] = { + "google.auth", + "google.auth.transport.requests", + "google.protobuf.duration_pb2", + "google.protobuf.timestamp_pb2", +} + +if _has_grpc: + __lazy_modules__.update( + { + "grpc", + "google.auth.transport.grpc", + } + ) -try: - import grpc - import google.auth.transport.grpc -except ImportError: # pragma: NO COVER +import google.auth # noqa: E402 +import google.auth.transport.requests # noqa: E402 +from google.protobuf import duration_pb2 # noqa: E402 +from google.protobuf import timestamp_pb2 # noqa: E402 + +if _has_grpc: + try: + import grpc # noqa: E402 + import google.auth.transport.grpc # noqa: E402 + except ImportError: # pragma: NO COVER + grpc = None +else: grpc = None # `google.cloud._helpers._NOW` is deprecated diff --git a/packages/google-cloud-core/google/cloud/_http/__init__.py b/packages/google-cloud-core/google/cloud/_http/__init__.py index af25e650db6e..96c673f6f701 100644 --- a/packages/google-cloud-core/google/cloud/_http/__init__.py +++ b/packages/google-cloud-core/google/cloud/_http/__init__.py @@ -19,13 +19,25 @@ import json import os import platform -from typing import Optional +from typing import Optional, Set from urllib.parse import urlencode import warnings -from google.api_core.client_info import ClientInfo -from google.cloud import exceptions -from google.cloud import version +# PEP 0810: Explicit Lazy Imports +# Python 3.15+ natively intercepts and defers these imports. +# Developers can disable this behavior and force eager imports. +# For more information, see: +# https://docs.python.org/3.15/library/sys.html#sys.set_lazy_imports_filter +# Older Python versions safely ignore this variable. +__lazy_modules__: Set[str] = { + "google.api_core.client_info", + "google.cloud.exceptions", + "google.cloud.version", +} + +from google.api_core.client_info import ClientInfo # noqa: E402 +from google.cloud import exceptions # noqa: E402 +from google.cloud import version # noqa: E402 API_BASE_URL = "https://www.googleapis.com" diff --git a/packages/google-cloud-core/google/cloud/client/__init__.py b/packages/google-cloud-core/google/cloud/client/__init__.py index 27d1a4c3dbae..1b88b28aa6d2 100644 --- a/packages/google-cloud-core/google/cloud/client/__init__.py +++ b/packages/google-cloud-core/google/cloud/client/__init__.py @@ -14,28 +14,56 @@ """Base classes for client used to interact with Google Cloud APIs.""" +import importlib.util import io import json import os from pickle import PicklingError -from typing import Tuple -from typing import Union - -import google.api_core.client_options -import google.api_core.exceptions -import google.auth -from google.auth import environment_vars -import google.auth.credentials -import google.auth.transport.requests -from google.cloud._helpers import _determine_default_project -from google.oauth2 import service_account - -try: - import google.auth.api_key - - HAS_GOOGLE_AUTH_API_KEY = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_API_KEY = False # pragma: NO COVER +from typing import Set, Tuple, Union + +_has_google_auth_api_key = ( + importlib.util.find_spec("google.auth.api_key") is not None +) + +# PEP 0810: Explicit Lazy Imports +# Python 3.15+ natively intercepts and defers these imports. +# Developers can disable this behavior and force eager imports. +# For more information, see: +# https://docs.python.org/3.15/library/sys.html#sys.set_lazy_imports_filter +# Older Python versions safely ignore this variable. +__lazy_modules__: Set[str] = { + "google.api_core.client_options", + "google.api_core.exceptions", + "google.auth", + "google.auth.environment_vars", + "google.auth.credentials", + "google.auth.transport.requests", + "google.cloud._helpers", + "google.oauth2", + "google.oauth2.service_account", +} + +if _has_google_auth_api_key: + __lazy_modules__.add("google.auth.api_key") + +import google.api_core.client_options # noqa: E402 +import google.api_core.exceptions # noqa: E402 +import google.auth # noqa: E402 +from google.auth import environment_vars # noqa: E402 +import google.auth.credentials # noqa: E402 +import google.auth.transport.requests # noqa: E402 +from google.cloud._helpers import _determine_default_project # noqa: E402 +from google.oauth2 import service_account # noqa: E402 + +if _has_google_auth_api_key: + try: + import google.auth.api_key # noqa: E402 + + HAS_GOOGLE_AUTH_API_KEY = True + except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_API_KEY = False # pragma: NO COVER +else: + HAS_GOOGLE_AUTH_API_KEY = False # TODO: Investigate adding a test for google.auth.api_key ImportError (https://github.com/googleapis/python-cloud-core/issues/334) diff --git a/packages/google-cloud-core/google/cloud/exceptions/__init__.py b/packages/google-cloud-core/google/cloud/exceptions/__init__.py index 36ee6d14fcab..a92712c96843 100644 --- a/packages/google-cloud-core/google/cloud/exceptions/__init__.py +++ b/packages/google-cloud-core/google/cloud/exceptions/__init__.py @@ -21,11 +21,32 @@ # Avoid the grpc and google.cloud.grpc collision. from __future__ import absolute_import -from google.api_core import exceptions +import importlib.util +from typing import Set -try: - from grpc._channel import _Rendezvous -except ImportError: # pragma: NO COVER +_has_grpc = importlib.util.find_spec("grpc") is not None + +# PEP 0810: Explicit Lazy Imports +# Python 3.15+ natively intercepts and defers these imports. +# Developers can disable this behavior and force eager imports. +# For more information, see: +# https://docs.python.org/3.15/library/sys.html#sys.set_lazy_imports_filter +# Older Python versions safely ignore this variable. +__lazy_modules__: Set[str] = { + "google.api_core.exceptions", +} + +if _has_grpc: + __lazy_modules__.update({"grpc", "grpc._channel"}) + +from google.api_core import exceptions # noqa: E402 + +if _has_grpc: + try: + from grpc._channel import _Rendezvous # noqa: E402 + except ImportError: # pragma: NO COVER + _Rendezvous = None +else: _Rendezvous = None GrpcRendezvous = _Rendezvous diff --git a/packages/google-cloud-core/google/cloud/operation/__init__.py b/packages/google-cloud-core/google/cloud/operation/__init__.py index 4fd1f271a1d4..126025b7b830 100644 --- a/packages/google-cloud-core/google/cloud/operation/__init__.py +++ b/packages/google-cloud-core/google/cloud/operation/__init__.py @@ -14,10 +14,23 @@ """Wrap long-running operations returned from Google Cloud APIs.""" -from typing import Dict - -from google.longrunning import operations_pb2 -from google.protobuf import json_format +from typing import Dict, Set + +# PEP 0810: Explicit Lazy Imports +# Python 3.15+ natively intercepts and defers these imports. +# Developers can disable this behavior and force eager imports. +# For more information, see: +# https://docs.python.org/3.15/library/sys.html#sys.set_lazy_imports_filter +# Older Python versions safely ignore this variable. +__lazy_modules__: Set[str] = { + "google.longrunning", + "google.longrunning.operations_pb2", + "google.protobuf", + "google.protobuf.json_format", +} + +from google.longrunning import operations_pb2 # noqa: E402 +from google.protobuf import json_format # noqa: E402 _GOOGLE_APIS_PREFIX = "type.googleapis.com"