|
14 | 14 |
|
15 | 15 | import pytest |
16 | 16 |
|
17 | | -from lumen.util import try_import_xarray |
| 17 | +from lumen.util import try_import, try_import_xarray |
18 | 18 |
|
19 | 19 | # Each entry: (module_path, class_name, guard_package, pip_extra) |
20 | 20 | OPTIONAL_SOURCES = [ |
@@ -88,6 +88,29 @@ def mock_import(name, *args, **kwargs): |
88 | 88 | sys.modules.update(saved) |
89 | 89 |
|
90 | 90 |
|
| 91 | +def test_try_import_returns_module_when_installed(): |
| 92 | + """try_import returns the module object for an importable module.""" |
| 93 | + import pandas |
| 94 | + assert try_import("pandas") is pandas |
| 95 | + |
| 96 | + |
| 97 | +def test_try_import_returns_none_when_missing(): |
| 98 | + """try_import returns None (not raises) for a module that cannot be imported.""" |
| 99 | + assert try_import("a_module_that_does_not_exist_xyz") is None |
| 100 | + |
| 101 | + |
| 102 | +def test_try_import_load_false_returns_already_imported_module(): |
| 103 | + """try_import(load=False) returns a module that is already imported.""" |
| 104 | + import json |
| 105 | + assert try_import("json", load=False) is json |
| 106 | + |
| 107 | + |
| 108 | +def test_try_import_load_false_never_imports(): |
| 109 | + """try_import(load=False) must not trigger an import, only consult sys.modules.""" |
| 110 | + with patch("lumen.util.importlib.import_module", side_effect=AssertionError("imported")): |
| 111 | + assert try_import("a_module_that_does_not_exist_xyz", load=False) is None |
| 112 | + |
| 113 | + |
91 | 114 | def test_try_import_xarray_returns_module_when_installed(): |
92 | 115 | """try_import_xarray returns the xarray module when xarray and xarray-sql are installed.""" |
93 | 116 | xr = pytest.importorskip("xarray") |
|
0 commit comments