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