test_reloading.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from numpy.testing import (
  2. assert_raises,
  3. assert_warns,
  4. assert_,
  5. assert_equal,
  6. IS_WASM,
  7. )
  8. from numpy.compat import pickle
  9. import pytest
  10. import sys
  11. import subprocess
  12. import textwrap
  13. from importlib import reload
  14. def test_numpy_reloading():
  15. # gh-7844. Also check that relevant globals retain their identity.
  16. import numpy as np
  17. import numpy._globals
  18. _NoValue = np._NoValue
  19. VisibleDeprecationWarning = np.VisibleDeprecationWarning
  20. ModuleDeprecationWarning = np.ModuleDeprecationWarning
  21. with assert_warns(UserWarning):
  22. reload(np)
  23. assert_(_NoValue is np._NoValue)
  24. assert_(ModuleDeprecationWarning is np.ModuleDeprecationWarning)
  25. assert_(VisibleDeprecationWarning is np.VisibleDeprecationWarning)
  26. assert_raises(RuntimeError, reload, numpy._globals)
  27. with assert_warns(UserWarning):
  28. reload(np)
  29. assert_(_NoValue is np._NoValue)
  30. assert_(ModuleDeprecationWarning is np.ModuleDeprecationWarning)
  31. assert_(VisibleDeprecationWarning is np.VisibleDeprecationWarning)
  32. def test_novalue():
  33. import numpy as np
  34. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  35. assert_equal(repr(np._NoValue), '<no value>')
  36. assert_(pickle.loads(pickle.dumps(np._NoValue,
  37. protocol=proto)) is np._NoValue)
  38. @pytest.mark.skipif(IS_WASM, reason="can't start subprocess")
  39. def test_full_reimport():
  40. """At the time of writing this, it is *not* truly supported, but
  41. apparently enough users rely on it, for it to be an annoying change
  42. when it started failing previously.
  43. """
  44. # Test within a new process, to ensure that we do not mess with the
  45. # global state during the test run (could lead to cryptic test failures).
  46. # This is generally unsafe, especially, since we also reload the C-modules.
  47. code = textwrap.dedent(r"""
  48. import sys
  49. from pytest import warns
  50. import numpy as np
  51. for k in list(sys.modules.keys()):
  52. if "numpy" in k:
  53. del sys.modules[k]
  54. with warns(UserWarning):
  55. import numpy as np
  56. """)
  57. p = subprocess.run([sys.executable, '-c', code], capture_output=True)
  58. if p.returncode:
  59. raise AssertionError(
  60. f"Non-zero return code: {p.returncode!r}\n\n{p.stderr.decode()}"
  61. )