|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Tests for the lazy package accessors.""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import importlib |
| 20 | +import types |
| 21 | + |
| 22 | +from google.adk.utils import _lazy |
| 23 | +import pytest |
| 24 | + |
| 25 | + |
| 26 | +@pytest.fixture(name='package') |
| 27 | +def _package(tmp_path, monkeypatch) -> types.ModuleType: |
| 28 | + """A package with a plain submodule and one that needs an absent library.""" |
| 29 | + root = tmp_path / 'lazy_fixture_pkg' |
| 30 | + root.mkdir() |
| 31 | + (root / '__init__.py').write_text('') |
| 32 | + (root / 'plain.py').write_text('VALUE = 1\n') |
| 33 | + (root / 'needs_absent.py').write_text('import absent_dependency\n') |
| 34 | + (root / 'exports.py').write_text('Exported = object()\n') |
| 35 | + monkeypatch.syspath_prepend(str(tmp_path)) |
| 36 | + return importlib.import_module('lazy_fixture_pkg') |
| 37 | + |
| 38 | + |
| 39 | +def test_declared_member_resolves_from_its_module(package): |
| 40 | + getattr_, _ = _lazy.accessors(vars(package), {'Exported': '.exports'}) |
| 41 | + |
| 42 | + exports = importlib.import_module('lazy_fixture_pkg.exports') |
| 43 | + assert getattr_('Exported') is exports.Exported |
| 44 | + |
| 45 | + |
| 46 | +def test_submodule_resolves_as_an_attribute(package): |
| 47 | + getattr_, _ = _lazy.accessors(vars(package), {}) |
| 48 | + |
| 49 | + assert getattr_('plain').VALUE == 1 |
| 50 | + |
| 51 | + |
| 52 | +def test_unknown_name_raises_attribute_error(package): |
| 53 | + getattr_, _ = _lazy.accessors(vars(package), {}) |
| 54 | + |
| 55 | + with pytest.raises(AttributeError, match='no attribute'): |
| 56 | + getattr_('not_a_submodule') |
| 57 | + |
| 58 | + |
| 59 | +def test_absent_dependency_keeps_its_own_error(package): |
| 60 | + """A library missing inside a submodule must not read as a typo.""" |
| 61 | + getattr_, _ = _lazy.accessors(vars(package), {}) |
| 62 | + |
| 63 | + with pytest.raises(ModuleNotFoundError) as error: |
| 64 | + getattr_('needs_absent') |
| 65 | + |
| 66 | + assert error.value.name == 'absent_dependency' |
0 commit comments