test__exceptions.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """
  2. Tests of the ._exceptions module. Primarily for exercising the __str__ methods.
  3. """
  4. import pickle
  5. import pytest
  6. import numpy as np
  7. _ArrayMemoryError = np.core._exceptions._ArrayMemoryError
  8. _UFuncNoLoopError = np.core._exceptions._UFuncNoLoopError
  9. class TestArrayMemoryError:
  10. def test_pickling(self):
  11. """ Test that _ArrayMemoryError can be pickled """
  12. error = _ArrayMemoryError((1023,), np.dtype(np.uint8))
  13. res = pickle.loads(pickle.dumps(error))
  14. assert res._total_size == error._total_size
  15. def test_str(self):
  16. e = _ArrayMemoryError((1023,), np.dtype(np.uint8))
  17. str(e) # not crashing is enough
  18. # testing these properties is easier than testing the full string repr
  19. def test__size_to_string(self):
  20. """ Test e._size_to_string """
  21. f = _ArrayMemoryError._size_to_string
  22. Ki = 1024
  23. assert f(0) == '0 bytes'
  24. assert f(1) == '1 bytes'
  25. assert f(1023) == '1023 bytes'
  26. assert f(Ki) == '1.00 KiB'
  27. assert f(Ki+1) == '1.00 KiB'
  28. assert f(10*Ki) == '10.0 KiB'
  29. assert f(int(999.4*Ki)) == '999. KiB'
  30. assert f(int(1023.4*Ki)) == '1023. KiB'
  31. assert f(int(1023.5*Ki)) == '1.00 MiB'
  32. assert f(Ki*Ki) == '1.00 MiB'
  33. # 1023.9999 Mib should round to 1 GiB
  34. assert f(int(Ki*Ki*Ki*0.9999)) == '1.00 GiB'
  35. assert f(Ki*Ki*Ki*Ki*Ki*Ki) == '1.00 EiB'
  36. # larger than sys.maxsize, adding larger prefixes isn't going to help
  37. # anyway.
  38. assert f(Ki*Ki*Ki*Ki*Ki*Ki*123456) == '123456. EiB'
  39. def test__total_size(self):
  40. """ Test e._total_size """
  41. e = _ArrayMemoryError((1,), np.dtype(np.uint8))
  42. assert e._total_size == 1
  43. e = _ArrayMemoryError((2, 4), np.dtype((np.uint64, 16)))
  44. assert e._total_size == 1024
  45. class TestUFuncNoLoopError:
  46. def test_pickling(self):
  47. """ Test that _UFuncNoLoopError can be pickled """
  48. assert isinstance(pickle.dumps(_UFuncNoLoopError), bytes)
  49. @pytest.mark.parametrize("args", [
  50. (2, 1, None),
  51. (2, 1, "test_prefix"),
  52. ("test message",),
  53. ])
  54. class TestAxisError:
  55. def test_attr(self, args):
  56. """Validate attribute types."""
  57. exc = np.AxisError(*args)
  58. if len(args) == 1:
  59. assert exc.axis is None
  60. assert exc.ndim is None
  61. else:
  62. axis, ndim, *_ = args
  63. assert exc.axis == axis
  64. assert exc.ndim == ndim
  65. def test_pickling(self, args):
  66. """Test that `AxisError` can be pickled."""
  67. exc = np.AxisError(*args)
  68. exc2 = pickle.loads(pickle.dumps(exc))
  69. assert type(exc) is type(exc2)
  70. for name in ("axis", "ndim", "args"):
  71. attr1 = getattr(exc, name)
  72. attr2 = getattr(exc2, name)
  73. assert attr1 == attr2, name