Skip to content

Commit 512d6fc

Browse files
committed
TEST: Test load(..., require=...) keyword arg and have_module() func
1 parent df17386 commit 512d6fc

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,11 +1,19 @@
11
import importlib
22
import sys
33
import types
4+
from unittest import mock
45

56
import pytest
67

78
import lazy_loader as lazy
89

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

1018
def test_lazy_import_basics():
1119
math = lazy.load("math")
@@ -149,3 +157,32 @@ def test_stub_loading_errors(tmp_path):
149157

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

0 commit comments

Comments
 (0)