test_reloading.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from numpy.testing import assert_raises, assert_warns, 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. with assert_warns(UserWarning):
  15. reload(np)
  16. assert_(_NoValue is np._NoValue)
  17. assert_(ModuleDeprecationWarning is np.ModuleDeprecationWarning)
  18. assert_(VisibleDeprecationWarning is np.VisibleDeprecationWarning)
  19. assert_raises(RuntimeError, reload, numpy._globals)
  20. with assert_warns(UserWarning):
  21. reload(np)
  22. assert_(_NoValue is np._NoValue)
  23. assert_(ModuleDeprecationWarning is np.ModuleDeprecationWarning)
  24. assert_(VisibleDeprecationWarning is np.VisibleDeprecationWarning)
  25. def test_novalue():
  26. import numpy as np
  27. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  28. assert_equal(repr(np._NoValue), '<no value>')
  29. assert_(pickle.loads(pickle.dumps(np._NoValue,
  30. protocol=proto)) is np._NoValue)
  31. def test_full_reimport():
  32. """At the time of writing this, it is *not* truly supported, but
  33. apparently enough users rely on it, for it to be an annoying change
  34. when it started failing previously.
  35. """
  36. # Test within a new process, to ensure that we do not mess with the
  37. # global state during the test run (could lead to cryptic test failures).
  38. # This is generally unsafe, especially, since we also reload the C-modules.
  39. code = textwrap.dedent(r"""
  40. import sys
  41. from pytest import warns
  42. import numpy as np
  43. for k in list(sys.modules.keys()):
  44. if "numpy" in k:
  45. del sys.modules[k]
  46. with warns(UserWarning):
  47. import numpy as np
  48. """)
  49. p = subprocess.run([sys.executable, '-c', code])