|
17 | 17 | from __future__ import annotations |
18 | 18 |
|
19 | 19 | import os |
| 20 | +from pathlib import Path |
| 21 | +import subprocess |
| 22 | +import sys |
20 | 23 |
|
21 | 24 | from google.adk.utils import _gcp_metadata |
22 | 25 | from google.adk.utils._gcp_metadata import get_gcp_client_defaults |
@@ -585,3 +588,53 @@ def test_get_gcp_client_defaults_uses_strict_genai_env_parsing( |
585 | 588 | defaults = get_gcp_client_defaults() |
586 | 589 |
|
587 | 590 | assert defaults == expected |
| 591 | + |
| 592 | + |
| 593 | +def test_importing_gcp_metadata_defers_transport_imports( |
| 594 | + tmp_path: Path, |
| 595 | +) -> None: |
| 596 | + """Importing Agent and _gcp_metadata defers metadata transport imports.""" |
| 597 | + src_root = str(Path(_gcp_metadata.__file__).parents[3]) |
| 598 | + existing_pythonpath = os.environ.get('PYTHONPATH') |
| 599 | + env = { |
| 600 | + **os.environ, |
| 601 | + 'PYTHONPATH': ( |
| 602 | + src_root |
| 603 | + if not existing_pythonpath |
| 604 | + else os.pathsep.join((src_root, existing_pythonpath)) |
| 605 | + ), |
| 606 | + } |
| 607 | + result = subprocess.run( |
| 608 | + [ |
| 609 | + sys.executable, |
| 610 | + '-c', |
| 611 | + ( |
| 612 | + 'import sys\n' |
| 613 | + 'from google.adk.agents import Agent\n' |
| 614 | + 'import google.adk.utils._gcp_metadata\n' |
| 615 | + 'forbidden = (\n' |
| 616 | + ' "google.auth.compute_engine",\n' |
| 617 | + ' "google.auth.transport.requests",\n' |
| 618 | + ' "cryptography",\n' |
| 619 | + ' "requests",\n' |
| 620 | + ' "urllib3",\n' |
| 621 | + ' "bcrypt",\n' |
| 622 | + ')\n' |
| 623 | + 'loaded = [\n' |
| 624 | + ' prefix\n' |
| 625 | + ' for prefix in forbidden\n' |
| 626 | + ' if any(\n' |
| 627 | + ' name == prefix or name.startswith(prefix + ".")\n' |
| 628 | + ' for name in sys.modules\n' |
| 629 | + ' )\n' |
| 630 | + ']\n' |
| 631 | + 'assert not loaded, loaded\n' |
| 632 | + ), |
| 633 | + ], |
| 634 | + cwd=tmp_path, |
| 635 | + env=env, |
| 636 | + capture_output=True, |
| 637 | + text=True, |
| 638 | + check=False, |
| 639 | + ) |
| 640 | + assert result.returncode == 0, result.stderr |
0 commit comments