test_lazy_imports.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import importlib
  2. import sys
  3. import types
  4. import pytest
  5. import networkx.lazy_imports as lazy
  6. def test_lazy_import_basics():
  7. math = lazy._lazy_import("math")
  8. anything_not_real = lazy._lazy_import("anything_not_real")
  9. # Now test that accessing attributes does what it should
  10. assert math.sin(math.pi) == pytest.approx(0, 1e-6)
  11. # poor-mans pytest.raises for testing errors on attribute access
  12. try:
  13. anything_not_real.pi
  14. assert False # Should not get here
  15. except ModuleNotFoundError:
  16. pass
  17. assert isinstance(anything_not_real, lazy.DelayedImportErrorModule)
  18. # see if it changes for second access
  19. try:
  20. anything_not_real.pi
  21. assert False # Should not get here
  22. except ModuleNotFoundError:
  23. pass
  24. def test_lazy_import_impact_on_sys_modules():
  25. math = lazy._lazy_import("math")
  26. anything_not_real = lazy._lazy_import("anything_not_real")
  27. assert type(math) == types.ModuleType
  28. assert "math" in sys.modules
  29. assert type(anything_not_real) == lazy.DelayedImportErrorModule
  30. assert "anything_not_real" not in sys.modules
  31. # only do this if numpy is installed
  32. np_test = pytest.importorskip("numpy")
  33. np = lazy._lazy_import("numpy")
  34. assert type(np) == types.ModuleType
  35. assert "numpy" in sys.modules
  36. np.pi # trigger load of numpy
  37. assert type(np) == types.ModuleType
  38. assert "numpy" in sys.modules
  39. def test_lazy_import_nonbuiltins():
  40. sp = lazy._lazy_import("scipy")
  41. np = lazy._lazy_import("numpy")
  42. if isinstance(sp, lazy.DelayedImportErrorModule):
  43. try:
  44. sp.pi
  45. assert False
  46. except ModuleNotFoundError:
  47. pass
  48. elif isinstance(np, lazy.DelayedImportErrorModule):
  49. try:
  50. np.sin(np.pi)
  51. assert False
  52. except ModuleNotFoundError:
  53. pass
  54. else:
  55. assert np.sin(sp.pi) == pytest.approx(0, 1e-6)
  56. def test_lazy_attach():
  57. name = "mymod"
  58. submods = ["mysubmodule", "anothersubmodule"]
  59. myall = {"not_real_submod": ["some_var_or_func"]}
  60. locls = {
  61. "attach": lazy.attach,
  62. "name": name,
  63. "submods": submods,
  64. "myall": myall,
  65. }
  66. s = "__getattr__, __lazy_dir__, __all__ = attach(name, submods, myall)"
  67. exec(s, {}, locls)
  68. expected = {
  69. "attach": lazy.attach,
  70. "name": name,
  71. "submods": submods,
  72. "myall": myall,
  73. "__getattr__": None,
  74. "__lazy_dir__": None,
  75. "__all__": None,
  76. }
  77. assert locls.keys() == expected.keys()
  78. for k, v in expected.items():
  79. if v is not None:
  80. assert locls[k] == v