test_reloading.py 2.3 KB

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