Skip to content

Commit 87a1989

Browse files
committed
TEST: Test load(..., require=...) keyword arg and have_module() func
1 parent 0644862 commit 87a1989

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

lazy_loader/tests/test_lazy_loader.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,18 @@
11
import sys
22
import types
3+
from unittest import mock
34

45
import pytest
56

67
import lazy_loader as lazy
78

9+
try:
10+
import importlib_metadata # noqa
11+
12+
have_importlib_metadata = True
13+
except ImportError:
14+
have_importlib_metadata = False
15+
816

917
def test_lazy_import_basics():
1018
math = lazy.load("math")
@@ -138,3 +146,32 @@ def test_stub_loading_errors(tmp_path):
138146

139147
with pytest.raises(ValueError, match="Cannot load imports from non-existent stub"):
140148
lazy.attach_stub("name", "not a file")
149+
150+
151+
def test_require_kwarg():
152+
dot = "_" if have_importlib_metadata else "."
153+
# Test with a module that definitely exists, behavior hinges on requirement
154+
with mock.patch(f"importlib{dot}metadata.version") as version:
155+
version.return_value = "1.0.0"
156+
math = lazy.load("math", require="somepkg >= 2.0")
157+
assert isinstance(math, lazy.DelayedImportErrorModule)
158+
159+
math = lazy.load("math", require="somepkg >= 1.0")
160+
assert math.sin(math.pi) == pytest.approx(0, 1e-6)
161+
162+
# We can fail even after a successful import
163+
math = lazy.load("math", require="somepkg >= 2.0")
164+
assert isinstance(math, lazy.DelayedImportErrorModule)
165+
166+
# When a module can be loaded but the version can't be checked,
167+
# raise a ValueError
168+
with pytest.raises(ValueError):
169+
lazy.load("math", require="somepkg >= 1.0")
170+
171+
172+
def test_have_module():
173+
math = lazy.load("math")
174+
anything_not_real = lazy.load("anything_not_real")
175+
176+
assert lazy.have_module(math)
177+
assert not lazy.have_module(anything_not_real)

0 commit comments

Comments
 (0)