Test that some modules are imported in a lazy manner. When importing xarray these should not be imported as well. Only when running code for the first time that requires them.
()
| 260 | |
| 261 | |
| 262 | def test_lazy_import() -> None: |
| 263 | """Test that some modules are imported in a lazy manner. |
| 264 | |
| 265 | When importing xarray these should not be imported as well. |
| 266 | Only when running code for the first time that requires them. |
| 267 | """ |
| 268 | deny_list = [ |
| 269 | "cubed", |
| 270 | "cupy", |
| 271 | # "dask", # TODO: backends.locks is not lazy yet :( |
| 272 | "dask.array", |
| 273 | "dask.distributed", |
| 274 | "flox", |
| 275 | "h5netcdf", |
| 276 | "matplotlib", |
| 277 | "nc_time_axis", |
| 278 | "netCDF4", |
| 279 | "numbagg", |
| 280 | "pint", |
| 281 | "pydap", |
| 282 | "scipy", |
| 283 | "sparse", |
| 284 | "zarr", |
| 285 | ] |
| 286 | # ensure that none of the above modules has been imported before |
| 287 | modules_backup = {} |
| 288 | for pkg in list(sys.modules.keys()): |
| 289 | for mod in deny_list + ["xarray"]: |
| 290 | if pkg.startswith(mod): |
| 291 | modules_backup[pkg] = sys.modules[pkg] |
| 292 | del sys.modules[pkg] |
| 293 | break |
| 294 | |
| 295 | try: |
| 296 | import xarray # noqa: F401 |
| 297 | from xarray.backends import list_engines |
| 298 | |
| 299 | list_engines() |
| 300 | |
| 301 | # ensure that none of the modules that are supposed to be |
| 302 | # lazy loaded are loaded when importing xarray |
| 303 | is_imported = set() |
| 304 | for pkg in sys.modules: |
| 305 | for mod in deny_list: |
| 306 | if pkg.startswith(mod): |
| 307 | is_imported.add(mod) |
| 308 | break |
| 309 | assert len(is_imported) == 0, ( |
| 310 | f"{is_imported} have been imported but should be lazy" |
| 311 | ) |
| 312 | |
| 313 | finally: |
| 314 | # restore original |
| 315 | sys.modules.update(modules_backup) |
| 316 | |
| 317 | |
| 318 | def test_list_engines() -> None: |
nothing calls this directly
no test coverage detected
searching dependent graphs…