test_reloading.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from numpy.testing import assert_raises, assert_, assert_equal
  2. from numpy.compat import pickle
  3. import sys
  4. import subprocess
  5. import textwrap
  6. from importlib import reload
  7. def test_numpy_reloading():
  8. # gh-7844. Also check that relevant globals retain their identity.
  9. import numpy as np
  10. import numpy._globals
  11. _NoValue = np._NoValue
  12. VisibleDeprecationWarning = np.VisibleDeprecationWarning
  13. ModuleDeprecationWarning = np.ModuleDeprecationWarning
  14. reload(np)
  15. assert_(_NoValue is np._NoValue)
  16. assert_(ModuleDeprecationWarning is np.ModuleDeprecationWarning)
  17. assert_(VisibleDeprecationWarning is np.VisibleDeprecationWarning)
  18. assert_raises(RuntimeError, reload, numpy._globals)
  19. reload(np)
  20. assert_(_NoValue is np._NoValue)
  21. assert_(ModuleDeprecationWarning is np.ModuleDeprecationWarning)
  22. assert_(VisibleDeprecationWarning is np.VisibleDeprecationWarning)
  23. def test_novalue():
  24. import numpy as np
  25. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  26. assert_equal(repr(np._NoValue), '<no value>')
  27. assert_(pickle.loads(pickle.dumps(np._NoValue,
  28. protocol=proto)) is np._NoValue)
  29. def test_full_reimport():
  30. """At the time of writing this, it is *not* truly supported, but
  31. apparently enough users rely on it, for it to be an annoying change
  32. when it started failing previously.
  33. """
  34. # Test within a new process, to ensure that we do not mess with the
  35. # global state during the test run (could lead to cryptic test failures).
  36. # This is generally unsafe, especially, since we also reload the C-modules.
  37. code = textwrap.dedent(r"""
  38. import sys
  39. import numpy as np
  40. for k in list(sys.modules.keys()):
  41. if "numpy" in k:
  42. del sys.modules[k]
  43. import numpy as np
  44. """)
  45. p = subprocess.run([sys.executable, '-c', code])
  46. assert p.returncode == 0