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