blob: 1891c0d1befb30316f5d9df4ebbfc3f42ad865c8 [file] [edit]
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit tests for googleapiclient._universe."""
import importlib.util
import os
import types
import unittest
from unittest import mock
import google.api_core
import google.api_core.client_options
import google.auth.compute_engine
import google.auth.credentials
from parameterized import parameterized
import pytest
from googleapiclient import _universe
try:
from google.api_core import universe
HAS_UNIVERSE = True
except ImportError:
HAS_UNIVERSE = False
def _make_credentials(universe_domain):
credentials = mock.Mock(spec=google.auth.credentials.Credentials)
credentials.universe_domain = universe_domain
return credentials
def _load_universe_module_with_fallbacks():
"""Load an isolated copy of ``_universe`` simulating ``google-api-core < 2.45.0``."""
spec = importlib.util.spec_from_file_location(
"_universe_fallback_test", _universe.__file__
)
module = importlib.util.module_from_spec(spec)
legacy_universe = types.SimpleNamespace(
DEFAULT_UNIVERSE=universe.DEFAULT_UNIVERSE,
determine_domain=universe.determine_domain,
compare_domains=universe.compare_domains,
)
with mock.patch.dict(
"sys.modules", {"google.api_core.universe": legacy_universe}
), mock.patch.object(google.api_core, "universe", legacy_universe, create=True):
spec.loader.exec_module(module)
module.APICoreVersionError = _universe.APICoreVersionError
return module
def _load_universe_module_without_universe():
"""Load an isolated copy of ``_universe`` simulating ``google-api-core < 2.18.0``."""
spec = importlib.util.spec_from_file_location(
"_universe_no_universe_test", _universe.__file__
)
module = importlib.util.module_from_spec(spec)
with mock.patch.dict(
"sys.modules", {"google.api_core.universe": None}
), mock.patch.dict(google.api_core.__dict__):
google.api_core.__dict__.pop("universe", None)
spec.loader.exec_module(module)
module.APICoreVersionError = _universe.APICoreVersionError
return module
@unittest.skipUnless(HAS_UNIVERSE, "google-api-core >= 2.18.0 is required")
class UniverseHelpersTest(unittest.TestCase):
FAKE_UNIVERSE = "foo.com"
@classmethod
def setUpClass(cls):
cls.fallback_universe = _load_universe_module_with_fallbacks()
def setUp(self):
environ_patcher = mock.patch.dict("os.environ")
environ_patcher.start()
self.addCleanup(environ_patcher.stop)
os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None)
os.environ.pop("GOOGLE_API_USE_MTLS_ENDPOINT", None)
def test_prefers_upstream_resolve_client_universe_when_available(self):
if hasattr(universe, "resolve_client_universe"):
self.assertIs(
_universe.resolve_client_universe, universe.resolve_client_universe
)
@parameterized.expand(
[
("defaults_to_default_universe", lambda: None, None, "googleapis.com"),
("env_var_fallback", lambda: None, "foo.com", "foo.com"),
(
"dict_options",
lambda: {"universe_domain": "foo.com"},
None,
"foo.com",
),
(
"mapping_proxy_options",
lambda: types.MappingProxyType({"universe_domain": "foo.com"}),
None,
"foo.com",
),
(
"client_options_instance",
lambda: google.api_core.client_options.ClientOptions(
universe_domain="foo.com"
),
None,
"foo.com",
),
(
"explicit_default_universe_overrides_env",
lambda: {"universe_domain": "googleapis.com"},
"foo.com",
"googleapis.com",
),
(
"empty_client_options_falls_back_to_env",
lambda: google.api_core.client_options.ClientOptions(),
"foo.com",
"foo.com",
),
(
"strips_whitespace_in_dict_universe",
lambda: {"universe_domain": " foo.com "},
None,
"foo.com",
),
(
"strips_whitespace_in_env_universe",
lambda: None,
" foo.com ",
"foo.com",
),
]
)
def test_resolve_client_universe_precedence(
self, _, make_client_options, env_value, expected
):
if env_value is not None:
os.environ["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = env_value
for fn in (
_universe.resolve_client_universe,
self.fallback_universe.resolve_client_universe,
):
self.assertEqual(fn(make_client_options()), expected)
@parameterized.expand(
[
("empty_dict_universe", lambda: {"universe_domain": ""}, None),
(
"empty_client_options_universe",
lambda: google.api_core.client_options.ClientOptions(
universe_domain=""
),
None,
),
("empty_env_universe", lambda: None, ""),
("whitespace_dict_universe", lambda: {"universe_domain": " "}, None),
("whitespace_env_universe", lambda: None, " "),
]
)
def test_resolve_client_universe_empty_raises(
self, _, make_client_options, env_value
):
if env_value is not None:
os.environ["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = env_value
for fn in (
_universe.resolve_client_universe,
self.fallback_universe.resolve_client_universe,
):
with self.assertRaises(universe.EmptyUniverseError):
fn(make_client_options())
def test_resolve_client_universe_invalid_type_raises(self):
for fn in (
_universe.resolve_client_universe,
self.fallback_universe.resolve_client_universe,
):
with self.assertRaises(TypeError):
fn("invalid")
def test_validate_request_credentials_universe_accepts_matching_and_exempt(self):
_universe.validate_request_credentials_universe(self.FAKE_UNIVERSE, None)
_universe.validate_request_credentials_universe(
self.FAKE_UNIVERSE, google.auth.credentials.AnonymousCredentials()
)
_universe.validate_request_credentials_universe(
self.FAKE_UNIVERSE, _make_credentials(self.FAKE_UNIVERSE)
)
def test_validate_request_credentials_universe_exempts_aio_anonymous(self):
aio_credentials = pytest.importorskip("google.auth.aio.credentials")
_universe.validate_request_credentials_universe(
self.FAKE_UNIVERSE, aio_credentials.AnonymousCredentials()
)
def test_validate_request_credentials_universe_mismatch_raises(self):
with self.assertRaises(universe.UniverseMismatchError):
_universe.validate_request_credentials_universe(
self.FAKE_UNIVERSE, _make_credentials("googleapis.com")
)
@unittest.skipUnless(
hasattr(google.auth.compute_engine.Credentials, "universe_domain"),
"google-auth >= 2.28.0 is required",
)
def test_validate_request_credentials_universe_checks_uncached_compute_engine(self):
gce_credentials = google.auth.compute_engine.Credentials()
gce_credentials._universe_domain_cached = False
with mock.patch.object(
google.auth.compute_engine.Credentials,
"universe_domain",
new_callable=mock.PropertyMock,
return_value="googleapis.com",
) as mock_universe_domain:
with self.assertRaises(universe.UniverseMismatchError):
_universe.validate_request_credentials_universe(
self.FAKE_UNIVERSE, gce_credentials
)
mock_universe_domain.assert_called_once_with()
class UniverseHelpersWithoutUniverseSupportTest(unittest.TestCase):
FAKE_UNIVERSE = "foo.com"
@classmethod
def setUpClass(cls):
cls.legacy_universe = _load_universe_module_without_universe()
def setUp(self):
environ_patcher = mock.patch.dict("os.environ")
environ_patcher.start()
self.addCleanup(environ_patcher.stop)
os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None)
os.environ.pop("GOOGLE_API_USE_MTLS_ENDPOINT", None)
def test_has_universe_is_false(self):
self.assertFalse(self.legacy_universe.HAS_UNIVERSE)
def test_resolve_client_universe_defaults_to_none(self):
self.assertIsNone(self.legacy_universe.resolve_client_universe())
self.assertIsNone(self.legacy_universe.resolve_client_universe({}))
self.assertIsNone(
self.legacy_universe.resolve_client_universe(
google.api_core.client_options.ClientOptions()
)
)
with mock.patch.dict(
"os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "googleapis.com"}
):
self.assertIsNone(self.legacy_universe.resolve_client_universe())
with mock.patch.dict(
"os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": " googleapis.com "}
):
self.assertIsNone(self.legacy_universe.resolve_client_universe())
def test_resolve_client_universe_raises_on_configured_universe(self):
with mock.patch.dict(
"os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": self.FAKE_UNIVERSE}
):
with self.assertRaises(_universe.APICoreVersionError):
self.legacy_universe.resolve_client_universe()
with mock.patch.dict("os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": ""}):
with self.assertRaises(_universe.APICoreVersionError):
self.legacy_universe.resolve_client_universe()
with self.assertRaises(_universe.APICoreVersionError):
self.legacy_universe.resolve_client_universe(
{"universe_domain": self.FAKE_UNIVERSE}
)
with self.assertRaises(_universe.APICoreVersionError):
self.legacy_universe.resolve_client_universe({"universe_domain": ""})
if hasattr(google.api_core.client_options.ClientOptions, "universe_domain"):
with self.assertRaises(_universe.APICoreVersionError):
self.legacy_universe.resolve_client_universe(
google.api_core.client_options.ClientOptions(
universe_domain=self.FAKE_UNIVERSE
)
)
with self.assertRaises(_universe.APICoreVersionError):
self.legacy_universe.resolve_client_universe(
google.api_core.client_options.ClientOptions(universe_domain="")
)
def test_check_api_core_compatible_with_credentials_universe(self):
self.legacy_universe.check_api_core_compatible_with_credentials_universe(None)
self.legacy_universe.check_api_core_compatible_with_credentials_universe(
_make_credentials("googleapis.com")
)
with self.assertRaises(_universe.APICoreVersionError):
self.legacy_universe.check_api_core_compatible_with_credentials_universe(
_make_credentials(self.FAKE_UNIVERSE)
)
def test_validate_request_credentials_universe_delegates_without_universe_support(
self,
):
self.legacy_universe.validate_request_credentials_universe(None, None)
self.legacy_universe.validate_request_credentials_universe(
None, _make_credentials("googleapis.com")
)
with self.assertRaises(_universe.APICoreVersionError):
self.legacy_universe.validate_request_credentials_universe(
None, _make_credentials(self.FAKE_UNIVERSE)
)
if __name__ == "__main__":
unittest.main()