|
| 1 | +import importlib |
| 2 | +import sys |
| 3 | +import types |
| 4 | + |
| 5 | +import lazy_loader as lazy |
| 6 | +import pytest |
| 7 | + |
| 8 | + |
| 9 | +def test_lazy_import_basics(): |
| 10 | + with lazy.lazy_imports(): |
| 11 | + import math |
| 12 | + |
| 13 | + with pytest.raises(ImportError): |
| 14 | + with lazy.lazy_imports(): |
| 15 | + import anything_not_real |
| 16 | + |
| 17 | + # Now test that accessing attributes does what it should |
| 18 | + assert math.sin(math.pi) == pytest.approx(0, 1e-6) |
| 19 | + |
| 20 | + |
| 21 | +def test_lazy_import_subpackages(): |
| 22 | + with lazy.lazy_imports(): |
| 23 | + import html.parser as hp |
| 24 | + assert "html" in sys.modules |
| 25 | + assert type(sys.modules["html"]) == type(pytest) |
| 26 | + assert isinstance(hp, importlib.util._LazyModule) |
| 27 | + assert "html.parser" in sys.modules |
| 28 | + assert sys.modules["html.parser"] == hp |
| 29 | + |
| 30 | + |
| 31 | +def test_lazy_import_impact_on_sys_modules(): |
| 32 | + with lazy.lazy_imports(): |
| 33 | + import math |
| 34 | + |
| 35 | + with pytest.raises(ImportError): |
| 36 | + with lazy.lazy_imports(): |
| 37 | + import anything_not_real |
| 38 | + |
| 39 | + assert isinstance(math, types.ModuleType) |
| 40 | + assert "math" in sys.modules |
| 41 | + assert "anything_not_real" not in sys.modules |
| 42 | + |
| 43 | + # only do this if numpy is installed |
| 44 | + pytest.importorskip("numpy") |
| 45 | + with lazy.lazy_imports(): |
| 46 | + import numpy as np |
| 47 | + assert isinstance(np, types.ModuleType) |
| 48 | + assert "numpy" in sys.modules |
| 49 | + |
| 50 | + np.pi # trigger load of numpy |
| 51 | + |
| 52 | + assert isinstance(np, types.ModuleType) |
| 53 | + assert "numpy" in sys.modules |
| 54 | + |
| 55 | + |
| 56 | +def test_lazy_import_nonbuiltins(): |
| 57 | + with lazy.lazy_imports(): |
| 58 | + import numpy as np |
| 59 | + import scipy as sp |
| 60 | + |
| 61 | + assert np.sin(np.pi) == pytest.approx(0, 1e-6) |
| 62 | + |
| 63 | + |
| 64 | +def test_attach_same_module_and_attr_name(): |
| 65 | + from lazy_loader.tests import fake_pkg_magic |
| 66 | + |
| 67 | + # Grab attribute twice, to ensure that importing it does not |
| 68 | + # override function by module |
| 69 | + assert isinstance(fake_pkg_magic.some_func, types.FunctionType) |
| 70 | + assert isinstance(fake_pkg_magic.some_func, types.FunctionType) |
| 71 | + |
| 72 | + # Ensure imports from submodule still work |
| 73 | + from lazy_loader.tests.fake_pkg_magic.some_func import some_func |
| 74 | + |
| 75 | + assert isinstance(some_func, types.FunctionType) |
0 commit comments