Debian Codegraph @

hypothesis-python/tests/numpy/test_from_dtype.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 sys
12
13 import numpy as np
14 import pytest
15
16 from hypothesis import assume, given, settings, strategies as st
17 from hypothesis.errors import InvalidArgument
18 from hypothesis.extra import numpy as nps
19 from hypothesis.internal.floats import width_smallest_normals
20 from hypothesis.strategies._internal import SearchStrategy
21
22 from tests.common.debug import assert_no_examples, check_can_generate_examples, find_any
23
24 np_version = tuple(int(x) for x in np.__version__.split(".")[:2])
25
26 STANDARD_TYPES = [
27 np.dtype(t)
28 for t in (
29 "int8",
30 "int16",
31 "int32",
32 "int64",
33 "uint8",
34 "uint16",
35 "uint32",
36 "uint64",
37 "float",
38 "float16",
39 "float32",
40 "float64",
41 "complex64",
42 "complex128",
43 "datetime64",
44 "timedelta64",
45 bool,
46 str,
47 bytes,
48 )
49 ]
50 for nonstandard_typecode in ["g", "G", "S1", "q", "Q"]:
51 try:
52 STANDARD_TYPES.append(np.dtype(nonstandard_typecode))
53 except Exception:
54 pass
55
56
57 @given(nps.nested_dtypes())
58 def test_strategies_for_standard_dtypes_have_reusable_values(dtype):
59 assert nps.from_dtype(dtype).has_reusable_values
60
61
62 @pytest.mark.parametrize("t", STANDARD_TYPES)
63 def test_produces_instances(t):
64 @given(nps.from_dtype(t))
65 def test_is_t(x):
66 assert isinstance(x, t.type)
67 assert x.dtype.kind == t.kind
68
69 test_is_t()
70
71
72 @settings(max_examples=100, deadline=None)
73 @given(nps.nested_dtypes(max_itemsize=400), st.data())
74 def test_infer_strategy_from_dtype(dtype, data):
75 # Given a dtype
76 assert isinstance(dtype, np.dtype)
77 # We can infer a strategy
78 strat = nps.from_dtype(dtype)
79 assert isinstance(strat, SearchStrategy)
80 # And use it to fill an array of that dtype
81 data.draw(nps.arrays(dtype, 10, elements=strat))
82
83
84 @given(st.data())
85 def test_can_cast_for_scalars(data):
86 # Note: this only passes with castable datatypes, certain dtype
87 # combinations will result in an error if numpy is not able to cast them.
88 dt_elements = np.dtype(data.draw(st.sampled_from(["bool", "<i2", ">i2"])))
89 dt_desired = np.dtype(
90 data.draw(st.sampled_from(["<i2", ">i2", "float32", "float64"]))
91 )
92 result = data.draw(
93 nps.arrays(dtype=dt_desired, elements=nps.from_dtype(dt_elements), shape=())
94 )
95 assert isinstance(result, np.ndarray)
96 assert result.dtype == dt_desired
97
98
99 @given(st.data())
100 def test_unicode_string_dtypes_generate_unicode_strings(data):
101 dt = data.draw(nps.unicode_string_dtypes())
102 result = data.draw(nps.from_dtype(dt))
103 assert isinstance(result, str)
104
105
106 @given(nps.arrays(dtype="U99", shape=(10,)))
107 def test_can_unicode_strings_without_decode_error(arr):
108 # See https://github.com/numpy/numpy/issues/15363
109 pass
110
111
112 @pytest.mark.skipif(not nps.NP_FIXED_UNICODE, reason="workaround for old bug")
113 def test_unicode_string_dtypes_need_not_be_utf8():
114 def cannot_encode(string):
115 try:
116 string.encode()
117 return False
118 except UnicodeEncodeError:
119 return True
120
121 find_any(nps.from_dtype(np.dtype("U")), cannot_encode, settings(max_examples=5000))
122
123
124 @given(st.data())
125 def test_byte_string_dtypes_generate_unicode_strings(data):
126 dt = data.draw(nps.byte_string_dtypes())
127 result = data.draw(nps.from_dtype(dt))
128 assert isinstance(result, bytes)
129
130
131 skipif_np2 = pytest.mark.skipif(np_version >= (2, 0), reason="removed in new version")
132
133
134 @pytest.mark.parametrize(
135 "dtype",
136 ["U", "S", pytest.param("a", marks=skipif_np2)],
137 )
138 def test_unsized_strings_length_gt_one(dtype):
139 # See https://github.com/HypothesisWorks/hypothesis/issues/2229
140 find_any(nps.arrays(dtype=dtype, shape=1), lambda arr: len(arr[0]) >= 2)
141
142
143 @given(
144 st.data(),
145 st.builds(
146 "{}[{}]".format,
147 st.sampled_from(("datetime64", "timedelta64")),
148 st.sampled_from(nps.TIME_RESOLUTIONS),
149 ).map(np.dtype),
150 )
151 def test_inferring_from_time_dtypes_gives_same_dtype(data, dtype):
152 ex = data.draw(nps.from_dtype(dtype))
153 assert dtype == ex.dtype
154
155
156 @given(st.data(), nps.byte_string_dtypes() | nps.unicode_string_dtypes())
157 def test_inferred_string_strategies_roundtrip(data, dtype):
158 # Check that we never generate too-long or nul-terminated strings, which
159 # cannot be read back out of an array.
160 arr = np.zeros(shape=1, dtype=dtype)
161 ex = data.draw(nps.from_dtype(arr.dtype))
162 arr[0] = ex
163 assert arr[0] == ex
164
165
166 @given(st.data(), nps.scalar_dtypes())
167 def test_all_inferred_scalar_strategies_roundtrip(data, dtype):
168 # We only check scalars here, because record/compound/nested dtypes always
169 # give an array of np.void objects. We're interested in whether scalar
170 # values are safe, not known type coercion.
171 arr = np.zeros(shape=1, dtype=dtype)
172 ex = data.draw(nps.from_dtype(arr.dtype))
173 assume(ex == ex) # If not, the roundtrip test *should* fail! (eg NaN)
174 arr[0] = ex
175 assert arr[0] == ex
176
177
178 @pytest.mark.parametrize("dtype_str", ["m8", "M8"])
179 @given(data=st.data())
180 def test_from_dtype_works_without_time_unit(data, dtype_str):
181 arr = data.draw(nps.from_dtype(np.dtype(dtype_str)))
182 assert (dtype_str + "[") in arr.dtype.str
183
184
185 @pytest.mark.parametrize("dtype_str", ["m8", "M8"])
186 @given(data=st.data())
187 def test_arrays_selects_consistent_time_unit(data, dtype_str):
188 arr = data.draw(nps.arrays(dtype_str, 10))
189 assert (dtype_str + "[") in arr.dtype.str
190
191
192 @pytest.mark.parametrize("dtype", ["m8", "M8"])
193 def test_from_dtype_can_include_or_exclude_nat(dtype):
194 find_any(nps.from_dtype(np.dtype(dtype), allow_nan=None), np.isnat)
195 find_any(nps.from_dtype(np.dtype(dtype), allow_nan=True), np.isnat)
196 assert_no_examples(nps.from_dtype(np.dtype(dtype), allow_nan=False), np.isnat)
197
198
199 def test_arrays_gives_useful_error_on_inconsistent_time_unit():
200 with pytest.raises(InvalidArgument, match="mismatch of time units in dtypes"):
201 check_can_generate_examples(
202 nps.arrays("m8[Y]", 10, elements=nps.from_dtype(np.dtype("m8[D]")))
203 )
204
205
206 @pytest.mark.parametrize(
207 "dtype, kwargs, pred",
208 [
209 # Floating point: bounds, exclusive bounds, and excluding nonfinites
210 (float, {"min_value": 1, "max_value": 2}, lambda x: 1 <= x <= 2),
211 (
212 float,
213 {"min_value": 1, "max_value": 2, "exclude_min": True, "exclude_max": True},
214 lambda x: 1 < x < 2,
215 ),
216 (float, {"allow_nan": False}, lambda x: not np.isnan(x)),
217 (float, {"allow_infinity": False}, lambda x: not np.isinf(x)),
218 (float, {"allow_nan": False, "allow_infinity": False}, np.isfinite),
219 # Complex numbers: bounds and excluding nonfinites
220 (complex, {"allow_nan": False}, lambda x: not np.isnan(x)),
221 (complex, {"allow_infinity": False}, lambda x: not np.isinf(x)),
222 (complex, {"allow_nan": False, "allow_infinity": False}, np.isfinite),
223 # Note we accept epsilon errors here as internally sqrt is used to draw
224 # complex numbers. sqrt on some platforms gets epsilon errors, which is
225 # too tricky to filter out and so - for now - we just accept them.
226 (
227 complex,
228 {"min_magnitude": 1e3},
229 lambda x: abs(x) >= 1e3 * (1 - sys.float_info.epsilon),
230 ),
231 (
232 complex,
233 {"max_magnitude": 1e2},
234 lambda x: abs(x) <= 1e2 * (1 + sys.float_info.epsilon),
235 ),
236 (
237 complex,
238 {"min_magnitude": 1, "max_magnitude": 1e6},
239 lambda x: (
240 (1 - sys.float_info.epsilon)
241 <= abs(x)
242 <= 1e6 * (1 + sys.float_info.epsilon)
243 ),
244 ),
245 # Integer bounds, limited to the representable range
246 ("int8", {"min_value": -1, "max_value": 1}, lambda x: -1 <= x <= 1),
247 ("uint8", {"min_value": 1, "max_value": 2}, lambda x: 1 <= x <= 2),
248 # String arguments, bounding size and unicode alphabet
249 ("S", {"min_size": 1, "max_size": 2}, lambda x: 1 <= len(x) <= 2),
250 ("S4", {"min_size": 1, "max_size": 2}, lambda x: 1 <= len(x) <= 2),
251 ("U", {"min_size": 1, "max_size": 2}, lambda x: 1 <= len(x) <= 2),
252 ("U4", {"min_size": 1, "max_size": 2}, lambda x: 1 <= len(x) <= 2),
253 ("U", {"alphabet": "abc"}, lambda x: set(x).issubset("abc")),
254 ],
255 )
256 @given(data=st.data())
257 def test_from_dtype_with_kwargs(data, dtype, kwargs, pred):
258 value = data.draw(nps.from_dtype(np.dtype(dtype), **kwargs))
259 assert pred(value)
260
261
262 @given(nps.from_dtype(np.dtype("U20,uint8,float32"), min_size=1, allow_nan=False))
263 def test_customize_structured_dtypes(x):
264 name, age, score = x
265 assert len(name) >= 1
266 assert 0 <= age <= 255
267 assert not np.isnan(score)
268
269
270 @pytest.mark.parametrize("allow_subnormal", [False, True])
271 @pytest.mark.parametrize("width", [32, 64])
272 def test_float_subnormal_generation(allow_subnormal, width):
273 dtype = np.dtype(f"float{width}")
274 strat = nps.from_dtype(dtype, allow_subnormal=allow_subnormal).filter(
275 lambda n: n != 0
276 )
277 smallest_normal = width_smallest_normals[width]
278 if allow_subnormal:
279 find_any(strat, lambda n: -smallest_normal < n < smallest_normal)
280 else:
281 assert_no_examples(strat, lambda n: -smallest_normal < n < smallest_normal)
282
283
284 @pytest.mark.parametrize("allow_subnormal", [False, True])
285 @pytest.mark.parametrize("width", [64, 128])
286 def test_complex_subnormal_generation(allow_subnormal, width):
287 dtype = np.dtype(f"complex{width}")
288 strat = nps.from_dtype(dtype, allow_subnormal=allow_subnormal).filter(
289 lambda n: n.real != 0 and n.imag != 0
290 )
291 smallest_normal = width_smallest_normals[width / 2]
292
293 def condition(n):
294 return (
295 -smallest_normal < n.real < smallest_normal
296 or -smallest_normal < n.imag < smallest_normal
297 )
298
299 if allow_subnormal:
300 find_any(strat, condition)
301 else:
302 assert_no_examples(strat, condition)