Skip to content

Commit 8ad1f91

Browse files
committed
test: add lazy imports fallback and tests for PEP 810
1 parent 66b9fe5 commit 8ad1f91

2 files changed

Lines changed: 58 additions & 0 deletions

File tree

packages/google-auth/google/auth/transport/__init__.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,12 @@
2424
for the return value of :class:`Request`.
2525
"""
2626

27+
# PEP 0810: Explicit Lazy Imports
28+
# Python 3.15+ natively intercepts and defers these imports.
29+
# Developers can disable this behavior and force eager imports.
30+
# For more information, see:
31+
# https://docs.python.org/3.15/library/sys.html#sys.set_lazy_imports_filter
32+
# Older Python versions safely ignore this variable.
2733
__lazy_modules__ = {
2834
"google.auth.transport.aiohttp_requests",
2935
"google.auth.transport._custom_tls_signer",
@@ -114,3 +120,12 @@ def __call__(
114120
# pylint: disable=redundant-returns-doc, missing-raises-doc
115121
# (pylint doesn't play well with abstract docstrings.)
116122
raise NotImplementedError("__call__ must be implemented.")
123+
124+
import sys
125+
if sys.version_info < (3, 15):
126+
import importlib
127+
for _lazy_mod in __lazy_modules__:
128+
try:
129+
importlib.import_module(_lazy_mod)
130+
except ImportError:
131+
pass
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import sys
2+
import pytest
3+
4+
# List of modules we expect to be lazy
5+
LAZY_MODULES = [
6+
"google.auth.transport.requests",
7+
"google.auth.transport.urllib3",
8+
"google.auth.transport.grpc",
9+
]
10+
11+
def clean_sys_modules():
12+
"""Helper to ensure we start with a clean slate for import testing."""
13+
for mod in LAZY_MODULES:
14+
sys.modules.pop(mod, None)
15+
16+
@pytest.mark.skipif(sys.version_info < (3, 15), reason="PEP 810 requires Python 3.15+")
17+
def test_lazy_imports_on_python_315():
18+
clean_sys_modules()
19+
20+
# 1. Import the transport package
21+
import google.auth.transport
22+
23+
# 2. Assert that none of the lazy modules have been eagerly loaded into sys.modules
24+
for mod in LAZY_MODULES:
25+
assert mod not in sys.modules
26+
27+
# 3. Access an attribute to trigger reification
28+
from google.auth.transport import requests
29+
_ = requests.__name__ # Trigger first-use reification
30+
31+
# 4. Assert that the module has now been reified and loaded
32+
assert "google.auth.transport.requests" in sys.modules
33+
34+
35+
@pytest.mark.skipif(sys.version_info >= (3, 15), reason="Testing fallback behavior on < 3.15")
36+
def test_fallback_eager_imports_pre_315():
37+
clean_sys_modules()
38+
39+
# On older Python, __lazy_modules__ is safely ignored, meaning they should eager-load
40+
import google.auth.transport
41+
42+
for mod in LAZY_MODULES:
43+
assert mod in sys.modules

0 commit comments

Comments
 (0)