test_lazyloading.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import subprocess
  2. import sys
  3. import textwrap
  4. import pytest
  5. from numpy.testing import IS_WASM
  6. @pytest.mark.skipif(IS_WASM, reason="can't start subprocess")
  7. def test_lazy_load():
  8. # gh-22045. lazyload doesn't import submodule names into the namespace
  9. # Test within a new process, to ensure that we do not mess with the
  10. # global state during the test run (could lead to cryptic test failures).
  11. # This is generally unsafe, especially, since we also reload the C-modules.
  12. code = textwrap.dedent(r"""
  13. import sys
  14. from importlib.util import LazyLoader, find_spec, module_from_spec
  15. # create lazy load of numpy as np
  16. spec = find_spec("numpy")
  17. module = module_from_spec(spec)
  18. sys.modules["numpy"] = module
  19. loader = LazyLoader(spec.loader)
  20. loader.exec_module(module)
  21. np = module
  22. # test a subpackage import
  23. from numpy.lib import recfunctions # noqa: F401
  24. # test triggering the import of the package
  25. np.ndarray
  26. """)
  27. p = subprocess.run(
  28. (sys.executable, '-c', code),
  29. stdout=subprocess.PIPE,
  30. stderr=subprocess.STDOUT,
  31. encoding='utf-8',
  32. check=False,
  33. )
  34. assert p.returncode == 0, p.stdout