Debian Codegraph @

hypothesis-python/tests/numpy/test_from_type.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 import typing
12 import warnings
13
14 import numpy as np
15 import pytest
16
17 from hypothesis import given, strategies as st
18 from hypothesis.errors import SmallSearchSpaceWarning
19 from hypothesis.extra.numpy import ArrayLike, NDArray, _NestedSequence, _SupportsArray
20
21 from .test_from_dtype import STANDARD_TYPES
22 from tests.common.debug import assert_simple_property, find_any
23
24 STANDARD_TYPES_TYPE = [dtype.type for dtype in STANDARD_TYPES]
25
26 needs_np_typing = {"reason": "numpy.typing is not available"}
27 needs_np_private_typing = {"reason": "numpy._typing is not available"}
28
29
30 @given(dtype=st.from_type(np.dtype))
31 def test_resolves_dtype_type(dtype):
32 assert isinstance(dtype, np.dtype)
33
34
35 def test_does_not_resolve_nonscalar_types():
36 # this was previously a parametrized test over np.object_ and np.void which
37 # used the same repr code path for the test. But then numpy changed their types
38 # such that we defer evaluation for st.from_type and are no longer identical
39 # to st.builds, but rather something morally equivalent to it. So we have
40 # these slightly more complicated checks.
41 with warnings.catch_warnings():
42 warnings.simplefilter("ignore", SmallSearchSpaceWarning)
43 assert_simple_property(st.from_type(np.object_), lambda value: value is None)
44
45 with pytest.raises(TypeError):
46 # np.void() requires an argument, and so throws when instantiated
47 assert_simple_property(st.from_type(np.void))
48
49
50 @pytest.mark.parametrize("typ", STANDARD_TYPES_TYPE)
51 def test_resolves_and_varies_numpy_scalar_type(typ):
52 if issubclass(typ, (np.datetime64, np.timedelta64)):
53 # numpy deprecated calling these types with no unit (the "generic" unit),
54 # and cross-unit comparisons can also fail, so use np.isnat instead.
55 x = find_any(st.from_type(typ), lambda x: not np.isnat(x))
56 else:
57 x = find_any(st.from_type(typ), lambda x: x != type(x)())
58 assert isinstance(x, typ)
59
60
61 @pytest.mark.parametrize("atype", [np.ndarray, NDArray])
62 def test_resolves_unspecified_array_type(atype):
63 if atype is not None:
64 assert_simple_property(st.from_type(atype), lambda v: isinstance(v, np.ndarray))
65
66
67 def workaround(dtype):
68 # Total hack to work around https://github.com/numpy/numpy/issues/24043
69 if np.__version__ == "1.25.0" and dtype == np.dtype("bytes").type:
70 return pytest.param(dtype, marks=[pytest.mark.xfail(strict=False)])
71 return dtype
72
73
74 # https://numpy.org/devdocs/release/1.22.0-notes.html#ndarray-dtype-and-number-are-now-runtime-subscriptable
75 @pytest.mark.skipif(
76 tuple(int(x) for x in np.__version__.split(".")[:2]) < (1, 22), reason="see comment"
77 )
78 @pytest.mark.parametrize("typ", [workaround(t) for t in STANDARD_TYPES_TYPE])
79 def test_resolves_specified_ndarray_type(typ):
80 assert_simple_property(
81 st.from_type(np.ndarray[typ]),
82 lambda arr: isinstance(arr, np.ndarray) and arr.dtype.type == typ,
83 )
84
85 assert_simple_property(
86 st.from_type(np.ndarray[typing.Any, typ]),
87 lambda arr: isinstance(arr, np.ndarray) and arr.dtype.type == typ,
88 )
89
90
91 @pytest.mark.skipif(NDArray is None, **needs_np_typing)
92 @pytest.mark.parametrize("typ", [workaround(t) for t in STANDARD_TYPES_TYPE])
93 def test_resolves_specified_NDArray_type(typ):
94 assert_simple_property(
95 st.from_type(NDArray[typ]),
96 lambda arr: isinstance(arr, np.ndarray) and arr.dtype.type == typ,
97 )
98
99
100 @pytest.mark.skipif(NDArray is None, **needs_np_typing)
101 def test_resolves_NDArray_with_dtype_union():
102 strat = st.from_type(NDArray[np.float64 | np.complex128])
103 find_any(strat, lambda arr: arr.dtype == np.dtype("float64"))
104 find_any(strat, lambda arr: arr.dtype == np.dtype("complex128"))
105
106
107 @pytest.mark.skipif(ArrayLike is None, **needs_np_typing)
108 @given(arr_like=st.from_type(ArrayLike))
109 def test_resolves_ArrayLike_type(arr_like):
110 arr = np.array(arr_like)
111 assert isinstance(arr, np.ndarray)
112 # The variation is too large to assert anything else about arr, but the
113 # ArrayLike contract just says that it can be coerced into an array (which
114 # we just did).
115
116
117 @pytest.mark.skipif(_NestedSequence is None, **needs_np_private_typing)
118 def test_resolves_specified_NestedSequence():
119 @given(seq=st.from_type(_NestedSequence[int]))
120 def test(seq):
121 assert hasattr(seq, "__iter__")
122
123 def flatten(lst):
124 for el in lst:
125 try:
126 yield from flatten(el)
127 except TypeError:
128 yield el
129
130 assert all(isinstance(i, int) for i in flatten(seq))
131
132 test()
133
134
135 @pytest.mark.skipif(_NestedSequence is None, **needs_np_private_typing)
136 @given(seq=st.from_type(_NestedSequence))
137 def test_resolves_unspecified_NestedSequence(seq):
138 assert hasattr(seq, "__iter__")
139
140
141 @pytest.mark.skipif(_SupportsArray is None, **needs_np_private_typing)
142 @given(arr=st.from_type(_SupportsArray))
143 def test_resolves_unspecified_SupportsArray(arr):
144 assert hasattr(arr, "__array__")
145
146
147 @pytest.mark.skipif(_SupportsArray is None, **needs_np_private_typing)
148 def test_resolves_SupportsArray():
149 @given(arr=st.from_type(_SupportsArray[int]))
150 def test(arr):
151 assert hasattr(arr, "__array__")
152 assert np.asarray(arr).dtype.kind == "i"
153
154 test()
155
156
157 @pytest.mark.skipif(
158 _NestedSequence is None or _SupportsArray is None, **needs_np_private_typing
159 )
160 def test_resolve_ArrayLike_equivalent():
161 # This is the current (1.24.3) definition of ArrayLike,
162 # with problematic parts commented out.
163 ArrayLike_like = (
164 _SupportsArray
165 # | _NestedSequence[_SupportsArray],
166 | bool
167 | int
168 | float
169 | complex
170 | str
171 | bytes
172 | _NestedSequence[
173 bool | int | float | complex | str,
174 # | bytes,
175 ]
176 )
177
178 @given(arr_like=st.from_type(ArrayLike_like))
179 def test(arr_like):
180 arr = np.array(arr_like)
181 assert isinstance(arr, np.ndarray)
182
183 test()