Debian Codegraph @

hypothesis-python/tests/numpy/test_gen_data.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 from functools import reduce
13 from itertools import zip_longest
14
15 import numpy as np
16 import pytest
17
18 from hypothesis import (
19 HealthCheck,
20 Phase,
21 assume,
22 given,
23 note,
24 settings,
25 strategies as st,
26 target,
27 )
28 from hypothesis.errors import InvalidArgument, UnsatisfiedAssumption
29 from hypothesis.extra import numpy as nps
30 from hypothesis.strategies._internal.lazy import unwrap_strategies
31
32 from tests.common.debug import (
33 assert_all_examples,
34 check_can_generate_examples,
35 find_any,
36 minimal,
37 )
38 from tests.common.utils import fails_with, flaky
39
40 ANY_SHAPE = nps.array_shapes(min_dims=0, max_dims=32, min_side=0, max_side=32)
41 ANY_NONZERO_SHAPE = nps.array_shapes(min_dims=0, max_dims=32, min_side=1, max_side=32)
42
43
44 @given(nps.arrays(float, ()))
45 def test_empty_dimensions_are_arrays(x):
46 assert isinstance(x, np.ndarray)
47 assert x.dtype.kind == "f"
48
49
50 @given(nps.arrays(float, (1, 0, 1)))
51 def test_can_handle_zero_dimensions(x):
52 assert x.shape == (1, 0, 1)
53
54
55 @given(nps.arrays("uint32", (5, 5)))
56 def test_generates_unsigned_ints(x):
57 assert (x >= 0).all()
58
59
60 @given(nps.arrays(int, (1,)))
61 def test_assert_fits_in_machine_size(x):
62 pass
63
64
65 def test_generates_and_minimizes():
66 assert (minimal(nps.arrays(float, (2, 2))) == np.zeros(shape=(2, 2))).all()
67
68
69 def test_can_minimize_large_arrays():
70 x = minimal(nps.arrays("uint32", 100), lambda x: np.any(x) and not np.all(x))
71 assert np.logical_or(x == 0, x == 1).all()
72 assert np.count_nonzero(x) in (1, len(x) - 1)
73
74
75 @flaky(max_runs=50, min_passes=1)
76 def test_can_minimize_float_arrays():
77 with np.errstate(over="ignore", invalid="ignore"):
78 x = minimal(nps.arrays(float, 50), lambda t: np.nansum(t) >= 1.0)
79 assert x.sum() in (1, 50)
80
81
82 class Foo:
83 pass
84
85
86 foos = st.tuples().map(lambda _: Foo())
87
88
89 def test_can_create_arrays_of_composite_types():
90 arr = minimal(nps.arrays(object, 100, elements=foos))
91 for x in arr:
92 assert isinstance(x, Foo)
93
94
95 @given(st.lists(st.integers()), st.data())
96 def test_can_create_zero_dim_arrays_of_lists(x, data):
97 arr = data.draw(nps.arrays(object, (), elements=st.just(x)))
98 assert arr.shape == ()
99 assert arr.dtype == np.dtype(object)
100 assert arr.item() == x
101
102
103 def test_can_create_arrays_of_tuples():
104 arr = minimal(
105 nps.arrays(object, 10, elements=st.tuples(st.integers(), st.integers())),
106 lambda x: all(t0 != t1 for t0, t1 in x),
107 )
108 assert all(a in ((1, 0), (0, 1)) for a in arr)
109
110
111 @given(nps.arrays(object, (2, 2), elements=st.tuples(st.integers())))
112 def test_does_not_flatten_arrays_of_tuples(arr):
113 assert isinstance(arr[0][0], tuple)
114
115
116 @given(
117 nps.arrays(object, (2, 2), elements=st.lists(st.integers(), min_size=1, max_size=1))
118 )
119 def test_does_not_flatten_arrays_of_lists(arr):
120 assert isinstance(arr[0][0], list)
121
122
123 @given(nps.array_shapes())
124 def test_can_generate_array_shapes(shape):
125 assert isinstance(shape, tuple)
126 assert all(isinstance(i, int) for i in shape)
127
128
129 @settings(
130 deadline=None, max_examples=10, suppress_health_check=[HealthCheck.nested_given]
131 )
132 @given(st.integers(0, 10), st.integers(0, 9), st.integers(0), st.integers(0))
133 def test_minimise_array_shapes(min_dims, dim_range, min_side, side_range):
134 smallest = minimal(
135 nps.array_shapes(
136 min_dims=min_dims,
137 max_dims=min_dims + dim_range,
138 min_side=min_side,
139 max_side=min_side + side_range,
140 )
141 )
142 assert len(smallest) == min_dims
143 assert all(k == min_side for k in smallest)
144
145
146 @pytest.mark.parametrize(
147 "kwargs", [{"min_side": 100}, {"min_dims": 15}, {"min_dims": 32}]
148 )
149 def test_interesting_array_shapes_argument(kwargs):
150 check_can_generate_examples(nps.array_shapes(**kwargs))
151
152
153 @given(nps.scalar_dtypes())
154 def test_can_generate_scalar_dtypes(dtype):
155 assert isinstance(dtype, np.dtype)
156
157
158 @settings(max_examples=100)
159 @given(
160 nps.nested_dtypes(
161 subtype_strategy=st.one_of(
162 nps.scalar_dtypes(), nps.byte_string_dtypes(), nps.unicode_string_dtypes()
163 )
164 )
165 )
166 def test_can_generate_compound_dtypes(dtype):
167 assert isinstance(dtype, np.dtype)
168
169
170 @settings(max_examples=100)
171 @given(
172 nps.nested_dtypes(
173 subtype_strategy=st.one_of(
174 nps.scalar_dtypes(), nps.byte_string_dtypes(), nps.unicode_string_dtypes()
175 )
176 ).flatmap(lambda dt: nps.arrays(dtype=dt, shape=1))
177 )
178 def test_can_generate_data_compound_dtypes(arr):
179 # This is meant to catch the class of errors which prompted PR #2085
180 assert isinstance(arr, np.ndarray)
181
182
183 @given(nps.nested_dtypes())
184 def test_np_dtype_is_idempotent(dtype):
185 assert dtype == np.dtype(dtype)
186
187
188 def test_minimise_scalar_dtypes():
189 assert minimal(nps.scalar_dtypes()) == np.dtype("bool")
190
191
192 def test_minimise_nested_types():
193 assert minimal(nps.nested_dtypes()) == np.dtype("bool")
194
195
196 def test_minimise_array_strategy():
197 smallest = minimal(
198 nps.arrays(
199 nps.nested_dtypes(max_itemsize=200),
200 nps.array_shapes(max_dims=3, max_side=3),
201 )
202 )
203 assert smallest.dtype == np.dtype("bool")
204 assert not smallest.any()
205
206
207 @given(nps.array_dtypes(allow_subarrays=False))
208 def test_can_turn_off_subarrays(dt):
209 for name in dt.names:
210 assert dt.fields[name][0].shape == ()
211
212
213 def test_array_dtypes_may_have_field_titles():
214 find_any(nps.array_dtypes(), lambda dt: len(dt.fields) > len(dt.names))
215
216
217 @pytest.mark.parametrize("byteorder", ["<", ">"])
218 @given(data=st.data())
219 def test_can_restrict_endianness(data, byteorder):
220 dtype = data.draw(nps.integer_dtypes(endianness=byteorder, sizes=(16, 32, 64)))
221 if byteorder == ("<" if sys.byteorder == "little" else ">"):
222 assert dtype.byteorder == "="
223 else:
224 assert dtype.byteorder == byteorder
225
226
227 @given(nps.integer_dtypes(sizes=8))
228 def test_can_specify_size_as_an_int(dt):
229 assert dt.itemsize == 1
230
231
232 @given(st.data())
233 def test_can_draw_arrays_from_scalars(data):
234 dt = data.draw(nps.scalar_dtypes())
235 result = data.draw(nps.arrays(dtype=dt, shape=()))
236 assert isinstance(result, np.ndarray)
237 assert result.dtype == dt
238
239
240 @given(st.data())
241 def test_can_cast_for_arrays(data):
242 # Note: this only passes with castable datatypes, certain dtype
243 # combinations will result in an error if numpy is not able to cast them.
244 dt_elements = np.dtype(data.draw(st.sampled_from(["bool", "<i2", ">i2"])))
245 dt_desired = np.dtype(
246 data.draw(st.sampled_from(["<i2", ">i2", "float32", "float64"]))
247 )
248 result = data.draw(
249 nps.arrays(
250 dtype=dt_desired, elements=nps.from_dtype(dt_elements), shape=(1, 2, 3)
251 )
252 )
253 assert isinstance(result, np.ndarray)
254 assert result.dtype == dt_desired
255
256
257 @given(nps.arrays(dtype="int8", shape=st.integers(0, 20), unique=True))
258 def test_array_values_are_unique(arr):
259 assert len(set(arr)) == len(arr)
260
261
262 def test_cannot_generate_unique_array_of_too_many_elements():
263 strat = nps.arrays(dtype=int, elements=st.integers(0, 5), shape=10, unique=True)
264 with pytest.raises(InvalidArgument):
265 check_can_generate_examples(strat)
266
267
268 @given(
269 nps.arrays(
270 elements=st.just(0.0),
271 dtype=float,
272 fill=st.just(np.nan),
273 shape=st.integers(0, 20),
274 unique=True,
275 )
276 )
277 def test_array_values_are_unique_high_collision(arr):
278 assert (arr == 0.0).sum() <= 1
279
280
281 @given(nps.arrays(dtype="int8", shape=(4,), elements=st.integers(0, 3), unique=True))
282 def test_generates_all_values_for_unique_array(arr):
283 # Ensures that the "reject already-seen element" branch is covered
284 assert len(set(arr)) == len(arr)
285
286
287 @given(nps.arrays(dtype="int8", shape=255, unique=True))
288 def test_efficiently_generates_all_unique_array(arr):
289 # Avoids the birthday paradox with UniqueSampledListStrategy
290 assert len(set(arr)) == len(arr)
291
292
293 @given(st.data(), st.integers(-100, 100), st.integers(1, 100))
294 def test_array_element_rewriting(data, start, size):
295 arr = nps.arrays(
296 dtype=np.dtype("int64"),
297 shape=size,
298 elements=st.integers(start, start + size - 1),
299 unique=True,
300 )
301 assert set(data.draw(arr)) == set(range(start, start + size))
302
303
304 def test_may_fill_with_nan_when_unique_is_set():
305 find_any(
306 nps.arrays(
307 dtype=float,
308 elements=st.floats(allow_nan=False),
309 shape=10,
310 unique=True,
311 fill=st.just(np.nan),
312 ),
313 lambda x: np.isnan(x).any(),
314 )
315
316
317 @given(
318 nps.arrays(
319 dtype=float,
320 elements=st.floats(allow_nan=False),
321 shape=10,
322 unique=True,
323 fill=st.just(np.nan),
324 )
325 )
326 def test_is_still_unique_with_nan_fill(xs):
327 assert len(set(xs)) == len(xs)
328
329
330 @fails_with(InvalidArgument)
331 @given(
332 nps.arrays(
333 dtype=float,
334 elements=st.floats(allow_nan=False),
335 shape=10,
336 unique=True,
337 fill=st.just(0.0),
338 )
339 )
340 def test_may_not_fill_with_non_nan_when_unique_is_set(arr):
341 pass
342
343
344 @fails_with(InvalidArgument)
345 @given(nps.arrays(dtype="U", shape=10, unique=True, fill=st.just("")))
346 def test_may_not_fill_with_non_nan_when_unique_is_set_and_type_is_not_number(arr):
347 pass
348
349
350 np_version = tuple(int(x) for x in np.__version__.split(".")[:2])
351
352
353 @pytest.mark.parametrize("fill", [False, True])
354 # Overflowing elements deprecated upstream in Numpy 1.24 :-)
355 @fails_with(
356 InvalidArgument
357 if np_version < (1, 24)
358 else (DeprecationWarning if np_version < (2, 0) else OverflowError)
359 )
360 @given(st.data())
361 def test_overflowing_integers_are_deprecated(fill, data):
362 kw = {"elements": st.just(300)}
363 if fill:
364 kw = {"elements": st.nothing(), "fill": kw["elements"]}
365 arr = data.draw(nps.arrays(dtype="int8", shape=(1,), **kw))
366 assert arr[0] == (300 % 256)
367
368
369 @pytest.mark.parametrize("fill", [False, True])
370 @pytest.mark.parametrize(
371 "dtype,strat",
372 [
373 ("float16", st.floats(min_value=65520, allow_infinity=False)),
374 ("float32", st.floats(min_value=10**40, allow_infinity=False)),
375 (
376 "complex64",
377 st.complex_numbers(min_magnitude=10**300, allow_infinity=False),
378 ),
379 ("U1", st.text(min_size=2, max_size=2)),
380 ("S1", st.binary(min_size=2, max_size=2)),
381 ],
382 )
383 @fails_with(InvalidArgument)
384 @given(data=st.data())
385 def test_unrepresentable_elements_are_deprecated(fill, dtype, strat, data):
386 if fill:
387 kw = {"elements": st.nothing(), "fill": strat}
388 else:
389 kw = {"elements": strat}
390 try:
391 arr = data.draw(nps.arrays(dtype=dtype, shape=(1,), **kw))
392 except RuntimeWarning:
393 assert np_version >= (1, 24), "New overflow-on-cast detection"
394 raise InvalidArgument("so the test passes") from None
395
396 try:
397 # This is a float or complex number, and has overflowed to infinity,
398 # triggering our deprecation for overflow.
399 assert np.isinf(arr[0])
400 except TypeError:
401 # We tried to call isinf on a string. The string was generated at
402 # length two, then truncated by the dtype of size 1 - deprecation
403 # again. If the first character was \0 it is now the empty string.
404 assert len(arr[0]) <= 1
405
406
407 @given(nps.arrays(dtype="float16", shape=(1,)))
408 def test_inferred_floats_do_not_overflow(arr):
409 pass
410
411
412 @given(nps.arrays(dtype="float16", shape=10, elements={"min_value": 0, "max_value": 1}))
413 def test_inferred_floats_can_be_constrained_at_low_width(arr):
414 assert (arr >= 0).all()
415 assert (arr <= 1).all()
416
417
418 @given(
419 nps.arrays(
420 dtype="float16",
421 shape=10,
422 elements={
423 "min_value": 0,
424 "max_value": 1,
425 "exclude_min": True,
426 "exclude_max": True,
427 },
428 )
429 )
430 def test_inferred_floats_can_be_constrained_at_low_width_excluding_endpoints(arr):
431 assert (arr > 0).all()
432 assert (arr < 1).all()
433
434
435 @given(
436 nps.arrays(
437 dtype="float16",
438 shape=10,
439 unique=True,
440 elements=st.integers(1, 9),
441 fill=st.just(np.nan),
442 )
443 )
444 def test_unique_array_with_fill_can_use_all_elements(arr):
445 assume(len(set(arr)) == arr.size)
446
447
448 @given(nps.arrays(dtype="uint8", shape=25, unique=True, fill=st.nothing()))
449 def test_unique_array_without_fill(arr):
450 # This test covers the collision-related branches for fully dense unique arrays.
451 # Choosing 25 of 256 possible elements means we're almost certain to see collisions
452 # thanks to the 'birthday paradox', but finding unique elemennts is still easy.
453 assume(len(set(arr)) == arr.size)
454
455
456 @given(ndim=st.integers(0, 5), data=st.data())
457 def test_mapped_positive_axes_are_unique(ndim, data):
458 min_size = data.draw(st.integers(0, ndim), label="min_size")
459 max_size = data.draw(st.integers(min_size, ndim), label="max_size")
460 axes = data.draw(
461 nps.valid_tuple_axes(ndim, min_size=min_size, max_size=max_size), label="axes"
462 )
463 assert len(set(axes)) == len({i if 0 < i else ndim + i for i in axes})
464
465
466 @given(ndim=st.integers(0, 5), data=st.data())
467 def test_length_bounds_are_satisfied(ndim, data):
468 min_size = data.draw(st.integers(0, ndim), label="min_size")
469 max_size = data.draw(st.integers(min_size, ndim), label="max_size")
470 axes = data.draw(
471 nps.valid_tuple_axes(ndim, min_size=min_size, max_size=max_size), label="axes"
472 )
473 assert min_size <= len(axes) <= max_size
474
475
476 @given(shape=nps.array_shapes(), data=st.data())
477 def test_axes_are_valid_inputs_to_sum(shape, data):
478 x = np.zeros(shape, dtype="uint8")
479 axes = data.draw(nps.valid_tuple_axes(ndim=len(shape)), label="axes")
480 np.sum(x, axes)
481
482
483 @settings(
484 deadline=None, max_examples=10, suppress_health_check=[HealthCheck.nested_given]
485 )
486 @given(ndim=st.integers(0, 3), data=st.data())
487 def test_minimize_tuple_axes(ndim, data):
488 min_size = data.draw(st.integers(0, ndim), label="min_size")
489 max_size = data.draw(st.integers(min_size, ndim), label="max_size")
490 smallest = minimal(nps.valid_tuple_axes(ndim, min_size=min_size, max_size=max_size))
491 assert len(smallest) == min_size
492 assert all(k > -1 for k in smallest)
493
494
495 @settings(
496 deadline=None, max_examples=10, suppress_health_check=[HealthCheck.nested_given]
497 )
498 @given(ndim=st.integers(0, 3), data=st.data())
499 def test_minimize_negative_tuple_axes(ndim, data):
500 min_size = data.draw(st.integers(0, ndim), label="min_size")
501 max_size = data.draw(st.integers(min_size, ndim), label="max_size")
502 smallest = minimal(
503 nps.valid_tuple_axes(ndim, min_size=min_size, max_size=max_size),
504 lambda x: all(i < 0 for i in x),
505 )
506 assert len(smallest) == min_size
507
508
509 @given(nps.broadcastable_shapes((), min_side=0, max_side=0, min_dims=0, max_dims=0))
510 def test_broadcastable_empty_shape(shape):
511 assert shape == ()
512
513
514 @settings(deadline=None, suppress_health_check=[HealthCheck.too_slow])
515 @given(shape=ANY_SHAPE, data=st.data())
516 def test_broadcastable_shape_bounds_are_satisfied(shape, data):
517 min_dims = data.draw(st.integers(0, 32), label="min_dims")
518 max_dims = data.draw(st.none() | st.integers(min_dims, 32), label="max_dims")
519 min_side = data.draw(st.integers(0, 3), label="min_side")
520 max_side = data.draw(st.none() | st.integers(min_side, 6), label="max_side")
521 try:
522 bshape = data.draw(
523 nps.broadcastable_shapes(
524 shape,
525 min_side=min_side,
526 max_side=max_side,
527 min_dims=min_dims,
528 max_dims=max_dims,
529 ),
530 label="bshape",
531 )
532 except InvalidArgument:
533 raise UnsatisfiedAssumption from None
534
535 if max_dims is None:
536 max_dims = max(len(shape), min_dims) + 2
537
538 if max_side is None:
539 max_side = max((*shape[::-1][:max_dims], min_side)) + 2
540
541 assert isinstance(bshape, tuple)
542 assert all(isinstance(s, int) for s in bshape)
543 assert min_dims <= len(bshape) <= max_dims
544 assert all(min_side <= s <= max_side for s in bshape)
545
546
547 @settings(deadline=None)
548 @given(num_shapes=st.integers(1, 4), base_shape=ANY_SHAPE, data=st.data())
549 def test_mutually_broadcastable_shape_bounds_are_satisfied(
550 num_shapes, base_shape, data
551 ):
552 min_dims = data.draw(st.integers(0, 32), label="min_dims")
553 max_dims = data.draw(
554 st.one_of(st.none(), st.integers(min_dims, 32)), label="max_dims"
555 )
556 min_side = data.draw(st.integers(0, 3), label="min_side")
557 max_side = data.draw(
558 st.one_of(st.none(), st.integers(min_side, 6)), label="max_side"
559 )
560 try:
561 shapes, result = data.draw(
562 nps.mutually_broadcastable_shapes(
563 num_shapes=num_shapes,
564 base_shape=base_shape,
565 min_side=min_side,
566 max_side=max_side,
567 min_dims=min_dims,
568 max_dims=max_dims,
569 ),
570 label="shapes, result",
571 )
572 except InvalidArgument:
573 raise UnsatisfiedAssumption from None
574
575 if max_dims is None:
576 max_dims = max(len(base_shape), min_dims) + 2
577
578 if max_side is None:
579 max_side = max((*base_shape[::-1][:max_dims], min_side)) + 2
580
581 assert isinstance(shapes, tuple)
582 assert isinstance(result, tuple)
583 assert all(isinstance(s, int) for s in result)
584
585 for bshape in shapes:
586 assert isinstance(bshape, tuple)
587 assert all(isinstance(s, int) for s in bshape)
588 assert min_dims <= len(bshape) <= max_dims
589 assert all(min_side <= s <= max_side for s in bshape)
590
591
592 def _draw_valid_bounds(data, shape, max_dims, *, permit_none=True):
593 if max_dims == 0 or not shape:
594 return 0, None
595
596 smallest_side = min(shape[::-1][:max_dims])
597 min_strat = (
598 st.sampled_from([1, smallest_side])
599 if smallest_side > 1
600 else st.just(smallest_side)
601 )
602 min_side = data.draw(min_strat, label="min_side")
603 largest_side = max(max(shape[::-1][:max_dims]), min_side)
604 if permit_none:
605 max_strat = st.one_of(st.none(), st.integers(largest_side, largest_side + 2))
606 else:
607 max_strat = st.integers(largest_side, largest_side + 2)
608 max_side = data.draw(max_strat, label="max_side")
609 return min_side, max_side
610
611
612 def _broadcast_two_shapes(shape_a: nps.Shape, shape_b: nps.Shape) -> nps.Shape:
613 result = []
614 for a, b in zip_longest(reversed(shape_a), reversed(shape_b), fillvalue=1):
615 if a != b and (a != 1) and (b != 1):
616 raise ValueError(
617 f"shapes {shape_a!r} and {shape_b!r} are not broadcast-compatible"
618 )
619 result.append(a if a != 1 else b)
620 return tuple(reversed(result))
621
622
623 def _broadcast_shapes(*shapes):
624 """Returns the shape resulting from broadcasting the
625 input shapes together.
626
627 Raises ValueError if the shapes are not broadcast-compatible"""
628 assert shapes, "Must pass >=1 shapes to broadcast"
629 return reduce(_broadcast_two_shapes, shapes, ())
630
631
632 @settings(deadline=None, max_examples=500)
633 @given(
634 shapes=st.lists(
635 nps.array_shapes(min_dims=0, min_side=0, max_dims=4, max_side=4), min_size=1
636 )
637 )
638 def test_broadcastable_shape_util(shapes):
639 """Ensures that `_broadcast_shapes` raises when fed incompatible shapes,
640 and ensures that it produces the true broadcasted shape"""
641 if len(shapes) == 1:
642 assert _broadcast_shapes(*shapes) == shapes[0]
643 return
644
645 arrs = [np.zeros(s, dtype=np.uint8) for s in shapes]
646
647 try:
648 broadcast_out = np.broadcast_arrays(*arrs)
649 except ValueError:
650 with pytest.raises(ValueError):
651 _broadcast_shapes(*shapes)
652 return
653 broadcasted_shape = _broadcast_shapes(*shapes)
654
655 assert broadcast_out[0].shape == broadcasted_shape
656
657
658 @settings(deadline=None, max_examples=200)
659 @given(shape=ANY_NONZERO_SHAPE, data=st.data())
660 def test_broadcastable_shape_has_good_default_values(shape, data):
661 # This test ensures that default parameters can always produce broadcast-compatible shapes
662 broadcastable_shape = data.draw(
663 nps.broadcastable_shapes(shape), label="broadcastable_shapes"
664 )
665 # error if drawn shape for b is not broadcast-compatible
666 _broadcast_shapes(shape, broadcastable_shape)
667
668
669 @settings(deadline=None, max_examples=200)
670 @given(base_shape=ANY_SHAPE, num_shapes=st.integers(1, 10), data=st.data())
671 def test_mutually_broadcastableshapes_has_good_default_values(
672 num_shapes, base_shape, data
673 ):
674 # This test ensures that default parameters can always produce broadcast-compatible shapes
675 shapes, result = data.draw(
676 nps.mutually_broadcastable_shapes(num_shapes=num_shapes, base_shape=base_shape),
677 label="shapes, result",
678 )
679 assert len(shapes) == num_shapes
680 # raises if shapes are not mutually-compatible
681 assert result == _broadcast_shapes(base_shape, *shapes)
682
683
684 @settings(deadline=None)
685 @given(min_dims=st.integers(0, 32), shape=ANY_SHAPE, data=st.data())
686 def test_broadcastable_shape_can_broadcast(min_dims, shape, data):
687 max_dims = data.draw(st.none() | st.integers(min_dims, 32), label="max_dims")
688 min_side, max_side = _draw_valid_bounds(data, shape, max_dims)
689 broadcastable_shape = data.draw(
690 nps.broadcastable_shapes(
691 shape,
692 min_side=min_side,
693 max_side=max_side,
694 min_dims=min_dims,
695 max_dims=max_dims,
696 ),
697 label="broadcastable_shapes",
698 )
699 # error if drawn shape for b is not broadcast-compatible
700 _broadcast_shapes(shape, broadcastable_shape)
701
702
703 @settings(deadline=None)
704 @given(
705 num_shapes=st.integers(1, 10),
706 min_dims=st.integers(0, 32),
707 base_shape=ANY_SHAPE,
708 data=st.data(),
709 )
710 def test_mutually_broadcastable_shape_can_broadcast(
711 num_shapes, min_dims, base_shape, data
712 ):
713 max_dims = data.draw(st.none() | st.integers(min_dims, 32), label="max_dims")
714 min_side, max_side = _draw_valid_bounds(data, base_shape, max_dims)
715 shapes, result = data.draw(
716 nps.mutually_broadcastable_shapes(
717 num_shapes=num_shapes,
718 base_shape=base_shape,
719 min_side=min_side,
720 max_side=max_side,
721 min_dims=min_dims,
722 max_dims=max_dims,
723 ),
724 label="shapes, result",
725 )
726
727 # error if drawn shapes are not mutually broadcast-compatible
728 assert result == _broadcast_shapes(base_shape, *shapes)
729
730
731 @settings(
732 deadline=None, max_examples=50, suppress_health_check=[HealthCheck.nested_given]
733 )
734 @given(
735 num_shapes=st.integers(1, 3),
736 min_dims=st.integers(0, 5),
737 base_shape=nps.array_shapes(min_dims=0, max_dims=3, min_side=0, max_side=5),
738 data=st.data(),
739 )
740 def test_minimize_mutually_broadcastable_shape(num_shapes, min_dims, base_shape, data):
741 # Ensure aligned dimensions of broadcastable shape minimizes to `(1,) * min_dims`
742 max_dims = data.draw(st.none() | st.integers(min_dims, 5), label="max_dims")
743 min_side, max_side = _draw_valid_bounds(
744 data, base_shape, max_dims, permit_none=False
745 )
746
747 if num_shapes > 1:
748 # shrinking gets a little bit hairy when we have empty axes
749 # and multiple num_shapes
750 assume(min_side > 0)
751
752 smallest_shapes, result = minimal(
753 nps.mutually_broadcastable_shapes(
754 num_shapes=num_shapes,
755 base_shape=base_shape,
756 min_side=min_side,
757 max_side=max_side,
758 min_dims=min_dims,
759 max_dims=max_dims,
760 )
761 )
762 note(f"smallest_shapes: {smallest_shapes}")
763 note(f"result: {result}")
764 assert len(smallest_shapes) == num_shapes
765 assert result == _broadcast_shapes(base_shape, *smallest_shapes)
766 for smallest in smallest_shapes:
767 n_leading = max(len(smallest) - len(base_shape), 0)
768 n_aligned = max(len(smallest) - n_leading, 0)
769 note(f"n_leading: {n_leading}")
770 note(f"n_aligned: {n_aligned} {base_shape[-n_aligned:]}")
771 expected = [min_side] * n_leading + [
772 (min(1, i) if i != 1 else min_side) if min_side <= 1 <= max_side else i
773 for i in (base_shape[-n_aligned:] if n_aligned else ())
774 ]
775 assert tuple(expected) == smallest
776
777
778 @settings(deadline=None)
779 @given(max_dims=st.integers(4, 6), data=st.data())
780 def test_broadcastable_shape_adjusts_max_dim_with_explicit_bounds(max_dims, data):
781 # Ensures that `broadcastable_shapes` limits itself to satisfiable dimensions
782 # Broadcastable values can only be drawn for dims 0-3 for these shapes
783 shape = data.draw(st.sampled_from([(5, 3, 2, 1), (0, 3, 2, 1)]), label="shape")
784 broadcastable_shape = data.draw(
785 nps.broadcastable_shapes(
786 shape, min_side=2, max_side=3, min_dims=3, max_dims=max_dims
787 ),
788 label="broadcastable_shapes",
789 )
790 assert len(broadcastable_shape) == 3
791 # error if drawn shape for b is not broadcast-compatible
792 _broadcast_shapes(shape, broadcastable_shape)
793
794
795 @settings(deadline=None)
796 @given(
797 max_side=st.sampled_from([3, None]),
798 min_dims=st.integers(0, 4),
799 num_shapes=st.integers(1, 3),
800 data=st.data(),
801 )
802 def test_mutually_broadcastable_shape_adjusts_max_dim_with_default_bounds(
803 max_side, min_dims, num_shapes, data
804 ):
805 # Ensures that `mutually_broadcastable_shapes` limits itself to satisfiable dimensions
806 # when a default `max_dims` is derived.
807 base_shape = data.draw(
808 st.sampled_from([(5, 3, 2, 1), (0, 3, 2, 1)]), label="base_shape"
809 )
810
811 try:
812 shapes, result = data.draw(
813 nps.mutually_broadcastable_shapes(
814 num_shapes=num_shapes,
815 base_shape=base_shape,
816 min_side=2,
817 max_side=max_side,
818 min_dims=min_dims,
819 ),
820 label="shapes, result",
821 )
822 except InvalidArgument:
823 # There is no satisfiable `max_dims` for us to tune
824 assert min_dims == 4
825 assert max_side == 3 or base_shape[0] == 0
826 return
827
828 if max_side == 3 or base_shape[0] == 0:
829 assert all(len(s) <= 3 for s in shapes)
830 elif min_dims == 4:
831 assert all(4 <= len(s) for s in shapes)
832
833 # error if drawn shape for b is not broadcast-compatible
834 assert len(shapes) == num_shapes
835 assert result == _broadcast_shapes(base_shape, *shapes)
836
837
838 @settings(
839 deadline=None, max_examples=10, suppress_health_check=[HealthCheck.nested_given]
840 )
841 @given(min_dims=st.integers(0, 32), min_side=st.integers(2, 3), data=st.data())
842 def test_broadcastable_shape_shrinking_with_singleton_out_of_bounds(
843 min_dims, min_side, data
844 ):
845 max_dims = data.draw(st.none() | st.integers(min_dims, 32), label="max_dims")
846 max_side = data.draw(st.none() | st.integers(min_side, 6), label="max_side")
847 shape = data.draw(st.integers(1, 4).map(lambda n: n * (1,)), label="shape")
848 smallest = minimal(
849 nps.broadcastable_shapes(
850 shape,
851 min_side=min_side,
852 max_side=max_side,
853 min_dims=min_dims,
854 max_dims=max_dims,
855 )
856 )
857 assert smallest == (min_side,) * min_dims
858
859
860 @settings(
861 deadline=None, max_examples=50, suppress_health_check=[HealthCheck.nested_given]
862 )
863 @given(
864 num_shapes=st.integers(1, 4),
865 min_dims=st.integers(0, 4),
866 min_side=st.integers(2, 3),
867 data=st.data(),
868 )
869 def test_mutually_broadcastable_shapes_shrinking_with_singleton_out_of_bounds(
870 num_shapes, min_dims, min_side, data
871 ):
872 """Ensures that shapes minimize to `(min_side,) * min_dims` when singleton dimensions
873 are disallowed."""
874 max_dims = data.draw(st.none() | st.integers(min_dims, 4), label="max_dims")
875 max_side = data.draw(
876 st.one_of(st.none(), st.integers(min_side, 6)), label="max_side"
877 )
878 ndims = data.draw(st.integers(1, 4), label="ndim")
879 base_shape = (1,) * ndims
880 smallest_shapes, result = minimal(
881 nps.mutually_broadcastable_shapes(
882 num_shapes=num_shapes,
883 base_shape=base_shape,
884 min_side=min_side,
885 max_side=max_side,
886 min_dims=min_dims,
887 max_dims=max_dims,
888 )
889 )
890 note(f"(smallest_shapes, result): {(smallest_shapes, result)}")
891 assert len(smallest_shapes) == num_shapes
892 assert result == _broadcast_shapes(base_shape, *smallest_shapes)
893 for smallest in smallest_shapes:
894 assert smallest == (min_side,) * min_dims
895
896
897 @settings(suppress_health_check=[HealthCheck.too_slow])
898 @given(
899 num_shapes=st.integers(1, 4),
900 min_dims=st.integers(1, 32),
901 max_side=st.integers(1, 6),
902 data=st.data(),
903 )
904 def test_mutually_broadcastable_shapes_only_singleton_is_valid(
905 num_shapes, min_dims, max_side, data
906 ):
907 """Ensures that, when all aligned base-shape dim sizes are larger
908 than ``max_side``, only singletons can be drawn"""
909 max_dims = data.draw(st.integers(min_dims, 32), label="max_dims")
910 base_shape = data.draw(
911 nps.array_shapes(min_side=max_side + 1, min_dims=1), label="base_shape"
912 )
913 input_shapes, result = data.draw(
914 nps.mutually_broadcastable_shapes(
915 num_shapes=num_shapes,
916 base_shape=base_shape,
917 min_side=1,
918 max_side=max_side,
919 min_dims=min_dims,
920 max_dims=max_dims,
921 ),
922 label="input_shapes, result",
923 )
924
925 assert len(input_shapes) == num_shapes
926 assert result == _broadcast_shapes(base_shape, *input_shapes)
927 for shape in input_shapes:
928 assert all(i == 1 for i in shape[-len(base_shape) :])
929
930
931 @settings(deadline=None, suppress_health_check=[HealthCheck.too_slow])
932 @given(
933 shape=nps.array_shapes(min_dims=0, max_dims=3, min_side=0, max_side=5),
934 max_dims=st.integers(0, 6),
935 data=st.data(),
936 )
937 def test_broadcastable_shape_can_generate_arbitrary_ndims(shape, max_dims, data):
938 # ensures that generates shapes can possess any length in [min_dims, max_dims]
939 desired_ndim = data.draw(st.integers(0, max_dims), label="desired_ndim")
940 min_dims = data.draw(
941 st.one_of(st.none(), st.integers(0, desired_ndim)), label="min_dims"
942 )
943 # check default arg behavior too
944 kwargs = {"min_dims": min_dims} if min_dims is not None else {}
945 find_any(
946 nps.broadcastable_shapes(shape, min_side=0, max_dims=max_dims, **kwargs),
947 lambda x: len(x) == desired_ndim,
948 settings(max_examples=10**6),
949 )
950
951
952 @settings(deadline=None)
953 @given(
954 num_shapes=st.integers(1, 3),
955 base_shape=nps.array_shapes(min_dims=0, max_dims=3, min_side=0, max_side=5),
956 max_dims=st.integers(0, 4),
957 data=st.data(),
958 )
959 def test_mutually_broadcastable_shapes_can_generate_arbitrary_ndims(
960 num_shapes, base_shape, max_dims, data
961 ):
962 # ensures that each generated shape can possess any length in [min_dims, max_dims]
963 desired_ndims = data.draw(
964 st.lists(st.integers(0, max_dims), min_size=num_shapes, max_size=num_shapes),
965 label="desired_ndims",
966 )
967 min_dims = data.draw(
968 st.one_of(st.none(), st.integers(0, min(desired_ndims))), label="min_dims"
969 )
970 # check default arg behavior too
971 kwargs = {"min_dims": min_dims} if min_dims is not None else {}
972 find_any(
973 nps.mutually_broadcastable_shapes(
974 num_shapes=num_shapes,
975 base_shape=base_shape,
976 min_side=0,
977 max_dims=max_dims,
978 **kwargs,
979 ),
980 lambda x: {len(s) for s in x.input_shapes} == set(desired_ndims),
981 settings(max_examples=10**6),
982 )
983
984
985 @settings(deadline=None, suppress_health_check=list(HealthCheck))
986 @given(
987 base_shape=nps.array_shapes(min_dims=0, max_dims=3, min_side=0, max_side=2),
988 max_dims=st.integers(1, 4),
989 )
990 def test_mutually_broadcastable_shapes_can_generate_interesting_singletons(
991 base_shape, max_dims
992 ):
993 find_any(
994 nps.mutually_broadcastable_shapes(
995 num_shapes=2,
996 base_shape=base_shape,
997 min_side=0,
998 max_dims=max_dims,
999 ),
1000 lambda x: any(a != b for a, b in zip(*(s[::-1] for s in x.input_shapes), strict=False)), # type: ignore
1001 )
1002
1003
1004 @pytest.mark.parametrize("base_shape", [(), (0,), (1,), (2,), (1, 2), (2, 1), (2, 2)])
1005 def test_mutually_broadcastable_shapes_can_generate_mirrored_singletons(base_shape):
1006 def f(shapes: nps.BroadcastableShapes):
1007 x, y = shapes.input_shapes
1008 return x.count(1) == 1 and y.count(1) == 1 and x[::-1] == y
1009
1010 find_any(
1011 nps.mutually_broadcastable_shapes(
1012 num_shapes=2,
1013 base_shape=base_shape,
1014 min_side=0,
1015 max_side=3,
1016 min_dims=2,
1017 max_dims=2,
1018 ),
1019 f,
1020 )
1021
1022
1023 @settings(deadline=None)
1024 @given(
1025 shape=nps.array_shapes(min_dims=1, min_side=1),
1026 dtype=st.one_of(nps.unsigned_integer_dtypes(), nps.integer_dtypes()),
1027 data=st.data(),
1028 )
1029 def test_advanced_integer_index_is_valid_with_default_result_shape(shape, dtype, data):
1030 index = data.draw(nps.integer_array_indices(shape, dtype=dtype))
1031 x = np.zeros(shape)
1032 out = x[index] # raises if the index is invalid
1033 assert not np.shares_memory(x, out) # advanced indexing should not return a view
1034 assert all(dtype == x.dtype for x in index)
1035
1036
1037 @settings(deadline=None)
1038 @given(
1039 shape=nps.array_shapes(min_dims=1, min_side=1),
1040 min_dims=st.integers(0, 3),
1041 min_side=st.integers(0, 3),
1042 dtype=st.one_of(nps.unsigned_integer_dtypes(), nps.integer_dtypes()),
1043 data=st.data(),
1044 )
1045 def test_advanced_integer_index_is_valid_and_satisfies_bounds(
1046 shape, min_dims, min_side, dtype, data
1047 ):
1048 max_side = data.draw(st.integers(min_side, min_side + 2), label="max_side")
1049 max_dims = data.draw(st.integers(min_dims, min_dims + 2), label="max_dims")
1050 index = data.draw(
1051 nps.integer_array_indices(
1052 shape,
1053 result_shape=nps.array_shapes(
1054 min_dims=min_dims,
1055 max_dims=max_dims,
1056 min_side=min_side,
1057 max_side=max_side,
1058 ),
1059 dtype=dtype,
1060 )
1061 )
1062 x = np.zeros(shape)
1063 out = x[index] # raises if the index is invalid
1064 assert all(min_side <= s <= max_side for s in out.shape)
1065 assert min_dims <= out.ndim <= max_dims
1066 assert not np.shares_memory(x, out) # advanced indexing should not return a view
1067 assert all(dtype == x.dtype for x in index)
1068
1069
1070 @settings(deadline=None, suppress_health_check=[HealthCheck.nested_given])
1071 @given(
1072 shape=nps.array_shapes(min_dims=1, min_side=1),
1073 min_dims=st.integers(0, 3),
1074 min_side=st.integers(0, 3),
1075 dtype=st.sampled_from(["uint8", "int8"]),
1076 data=st.data(),
1077 )
1078 def test_advanced_integer_index_minimizes_as_documented(
1079 shape, min_dims, min_side, dtype, data
1080 ):
1081 max_side = data.draw(st.integers(min_side, min_side + 2), label="max_side")
1082 max_dims = data.draw(st.integers(min_dims, min_dims + 2), label="max_dims")
1083 result_shape = nps.array_shapes(
1084 min_dims=min_dims, max_dims=max_dims, min_side=min_side, max_side=max_side
1085 )
1086 smallest = minimal(
1087 nps.integer_array_indices(shape, result_shape=result_shape, dtype=dtype)
1088 )
1089 desired = len(shape) * (np.zeros(min_dims * [min_side]),)
1090 assert len(smallest) == len(desired)
1091 for s, d in zip(smallest, desired, strict=True):
1092 np.testing.assert_array_equal(s, d)
1093
1094
1095 @settings(
1096 deadline=None, max_examples=10, suppress_health_check=[HealthCheck.nested_given]
1097 )
1098 @given(
1099 shape=nps.array_shapes(min_dims=1, max_dims=2, min_side=1, max_side=3),
1100 data=st.data(),
1101 )
1102 def test_advanced_integer_index_can_generate_any_pattern(shape, data):
1103 # ensures that generated index-arrays can be used to yield any pattern of elements from an array
1104 x = np.arange(np.prod(shape)).reshape(shape)
1105
1106 target_array = data.draw(
1107 nps.arrays(
1108 shape=nps.array_shapes(min_dims=1, max_dims=2, min_side=1, max_side=2),
1109 elements=st.sampled_from(x.flatten()),
1110 dtype=x.dtype,
1111 ),
1112 label="target",
1113 )
1114
1115 def index_selects_values_in_order(index):
1116 selected = x[index]
1117 target(len(set(selected.flatten())), label="unique indices")
1118 target(float(np.sum(target_array == selected)), label="elements correct")
1119 return np.all(target_array == selected)
1120
1121 minimal(
1122 nps.integer_array_indices(shape, result_shape=st.just(target_array.shape)),
1123 index_selects_values_in_order,
1124 settings(max_examples=10**6, phases=[Phase.generate, Phase.target]),
1125 )
1126
1127
1128 @pytest.mark.parametrize(
1129 "condition",
1130 [
1131 lambda ix: isinstance(ix, tuple) and Ellipsis in ix,
1132 lambda ix: isinstance(ix, tuple) and Ellipsis not in ix,
1133 lambda ix: isinstance(ix, tuple) and np.newaxis in ix,
1134 lambda ix: isinstance(ix, tuple) and np.newaxis not in ix,
1135 lambda ix: ix is Ellipsis,
1136 lambda ix: ix == np.newaxis,
1137 ],
1138 )
1139 def test_basic_indices_options(condition):
1140 indexers = nps.array_shapes(min_dims=0, max_dims=32).flatmap(
1141 lambda shape: nps.basic_indices(shape, allow_newaxis=True)
1142 )
1143 find_any(indexers, condition)
1144
1145
1146 def test_basic_indices_can_generate_empty_tuple():
1147 find_any(nps.basic_indices(shape=(0, 0), allow_ellipsis=True), lambda ix: ix == ())
1148
1149
1150 def test_basic_indices_can_generate_non_tuples():
1151 find_any(
1152 nps.basic_indices(shape=(0, 0), allow_ellipsis=True),
1153 lambda ix: not isinstance(ix, tuple),
1154 )
1155
1156
1157 def test_basic_indices_can_generate_long_ellipsis():
1158 # Runs of slice(None) - such as [0,:,:,:,0] - can be replaced by e.g. [0,...,0]
1159 find_any(
1160 nps.basic_indices(shape=(1, 0, 0, 0, 1), allow_ellipsis=True),
1161 lambda ix: len(ix) == 3 and ix[1] == Ellipsis,
1162 )
1163
1164
1165 @given(
1166 nps.basic_indices(shape=(0, 0, 0, 0, 0)).filter(
1167 lambda idx: isinstance(idx, tuple) and Ellipsis in idx
1168 )
1169 )
1170 def test_basic_indices_replaces_whole_axis_slices_with_ellipsis(idx):
1171 # `slice(None)` (aka `:`) is the only valid index for an axis of size
1172 # zero, so if all dimensions are 0 then a `...` will replace all the
1173 # slices because we generate `...` for entire contiguous runs of `:`
1174 assert slice(None) not in idx
1175
1176
1177 def test_basic_indices_can_generate_indices_not_covering_all_dims():
1178 # These "flat indices" are skippable in the underlying BasicIndexStrategy,
1179 # so we ensure we're definitely generating them for nps.basic_indices().
1180 find_any(
1181 nps.basic_indices(shape=(3, 3, 3)),
1182 lambda ix: (
1183 (not isinstance(ix, tuple) and ix != Ellipsis)
1184 or (isinstance(ix, tuple) and Ellipsis not in ix and len(ix) < 3)
1185 ),
1186 settings=settings(max_examples=5_000),
1187 )
1188
1189
1190 @given(
1191 shape=nps.array_shapes(min_dims=0, max_side=4)
1192 | nps.array_shapes(min_dims=0, min_side=0, max_side=10),
1193 allow_newaxis=st.booleans(),
1194 allow_ellipsis=st.booleans(),
1195 data=st.data(),
1196 )
1197 def test_basic_indices_generate_valid_indexers(
1198 shape, allow_newaxis, allow_ellipsis, data
1199 ):
1200 min_dims = data.draw(
1201 st.integers(0, 5 if allow_newaxis else len(shape)), label="min_dims"
1202 )
1203 max_dims = data.draw(
1204 st.none() | st.integers(min_dims, 32 if allow_newaxis else len(shape)),
1205 label="max_dims",
1206 )
1207 indexer = data.draw(
1208 nps.basic_indices(
1209 shape,
1210 min_dims=min_dims,
1211 max_dims=max_dims,
1212 allow_ellipsis=allow_ellipsis,
1213 allow_newaxis=allow_newaxis,
1214 ),
1215 label="indexer",
1216 )
1217
1218 # Check that disallowed things are indeed absent
1219 if not allow_newaxis:
1220 if isinstance(indexer, tuple):
1221 assert 0 <= len(indexer) <= len(shape) + int(allow_ellipsis)
1222 else:
1223 assert 1 <= len(shape) + int(allow_ellipsis)
1224 assert np.newaxis not in shape
1225 if not allow_ellipsis:
1226 assert Ellipsis not in shape
1227
1228 if 0 in shape:
1229 # If there's a zero in the shape, the array will have no elements.
1230 array = np.zeros(shape)
1231 assert array.size == 0
1232 elif np.prod(shape) <= 10**5:
1233 # If it's small enough to instantiate, do so with distinct elements.
1234 array = np.arange(np.prod(shape)).reshape(shape)
1235 else:
1236 # We can't cheat on this one, so just try another.
1237 assume(False)
1238 view = array[indexer]
1239 if not np.isscalar(view):
1240 assert min_dims <= view.ndim <= (32 if max_dims is None else max_dims)
1241 if view.size:
1242 assert np.shares_memory(view, array)
1243
1244
1245 # addresses https://github.com/HypothesisWorks/hypothesis/issues/2582
1246 @given(
1247 nps.arrays(
1248 shape=nps.array_shapes(min_dims=0, min_side=0), dtype=nps.floating_dtypes()
1249 )
1250 )
1251 def test_array_owns_memory(x: np.ndarray):
1252 assert x.base is None
1253 assert x[...].base is x
1254
1255
1256 @given(st.data())
1257 def test_no_recursion_in_multi_line_reprs_issue_3560(data):
1258 data.draw(nps.arrays(shape=(2,), dtype=float).map(lambda x: x))
1259 data.draw(
1260 nps.arrays(
1261 shape=(2,),
1262 dtype=float,
1263 ).map(lambda x: x)
1264 )
1265
1266
1267 def test_infers_elements_and_fill():
1268 # Regression test for https://github.com/HypothesisWorks/hypothesis/issues/3900
1269 # We only infer a fill strategy if the elements_strategy has reusable values,
1270 # and the interaction of two performance fixes broke this. Oops...
1271 s = unwrap_strategies(nps.arrays(dtype=np.uint32, shape=1))
1272 assert isinstance(s, nps.ArrayStrategy)
1273 assert repr(s.element_strategy) == f"integers(0, {2**32-1})"
1274 assert repr(s.fill) == f"integers(0, {2**32-1})"
1275
1276 # But we _don't_ infer a fill if the elements strategy is non-reusable
1277 elems = st.builds(lambda x: x * 2, st.integers(1, 10)).map(np.uint32)
1278 assert not elems.has_reusable_values
1279 s = unwrap_strategies(nps.arrays(dtype=np.uint32, shape=1, elements=elems))
1280 assert s.fill.is_empty
1281
1282
1283 @given(nps.arrays(np.dtype("O"), shape=nps.array_shapes()))
1284 def test_object_arrays_are_of_type_object(obj_array):
1285 assert obj_array.dtype == np.dtype("O")
1286
1287
1288 def test_class_instances_not_allowed_in_scalar_array():
1289 class A:
1290 pass
1291
1292 s = nps.arrays(
1293 nps.scalar_dtypes(),
1294 shape=nps.array_shapes(),
1295 elements=st.just(A()),
1296 )
1297
1298 # can raise ValueError during generation. For example if scalar_dtype is
1299 # corresponds to a datetime, numpy will raise "cannot convert A to a datetime".
1300 with pytest.raises((InvalidArgument, ValueError)):
1301 check_can_generate_examples(s)
1302
1303
1304 def test_object_arrays_with_mixed_elements_has_object_dtype():
1305 class A:
1306 pass
1307
1308 s = nps.arrays(
1309 np.dtype("O"),
1310 shape=nps.array_shapes(),
1311 elements=st.just(A()) | st.integers(),
1312 )
1313
1314 assert_all_examples(s, lambda arr: arr.dtype == np.dtype("O"))
1315 find_any(s, lambda arr: len({type(x) for x in arr.ravel()}) > 1)
1316
1317
1318 @given(st.data())
1319 def test_object_array_can_hold_arbitrary_class_instances(data):
1320 instance = data.draw(st.from_type(type).flatmap(st.from_type))
1321 s = nps.arrays(np.dtype("O"), nps.array_shapes(), elements=st.just(instance))
1322 arr = data.draw(s)
1323
1324 assert all(v is instance for v in arr.ravel())
1325
1326
1327 def test_object_array_can_hold_incomparable_elements():
1328 class Incomparable:
1329 def __eq__(self, other):
1330 raise TypeError
1331
1332 check_can_generate_examples(
1333 nps.arrays(
1334 np.dtype("O"),
1335 nps.array_shapes(),
1336 elements=st.just(Incomparable()),
1337 )
1338 )
1339
1340
1341 def test_can_generate_nested_object_arrays():
1342 int_arrays = nps.arrays(np.dtype("int"), nps.array_shapes())
1343 s = nps.arrays(np.dtype("O"), nps.array_shapes(), elements=int_arrays)
1344 check_can_generate_examples(s)