|
1 | 1 | import sys
|
2 | 2 | import types
|
| 3 | +from unittest import mock |
3 | 4 |
|
4 | 5 | import pytest
|
5 | 6 |
|
6 | 7 | import lazy_loader as lazy
|
7 | 8 |
|
| 9 | +try: |
| 10 | + import importlib_metadata # noqa |
| 11 | + |
| 12 | + have_importlib_metadata = True |
| 13 | +except ImportError: |
| 14 | + have_importlib_metadata = False |
| 15 | + |
8 | 16 |
|
9 | 17 | def test_lazy_import_basics():
|
10 | 18 | math = lazy.load("math")
|
@@ -138,3 +146,32 @@ def test_stub_loading_errors(tmp_path):
|
138 | 146 |
|
139 | 147 | with pytest.raises(ValueError, match="Cannot load imports from non-existent stub"):
|
140 | 148 | 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