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
11import codecs
12import enum
13import math
14import operator
15import random
16import re
17import string
18import sys
19import typing
20import warnings
21from collections.abc import Collection, Hashable, Iterable, Sequence
22from contextvars import ContextVar
23from decimal import Context, Decimal, localcontext
24from fractions import Fraction
25from functools import reduce
26from inspect import Parameter, Signature, isabstract, isclass
27from re import Pattern
28from types import FunctionType, GenericAlias
29from typing import (
30 Annotated,
31 Any,
32 AnyStr,
33 Callable,
34 Literal,
35 NoReturn,
36 Optional,
37 Protocol,
38 TypeVar,
39 Union,
40 cast,
41 get_args,
42 get_origin,
43 overload,
44)
45from uuid import UUID
46
47import attr
48
49from hypothesis._settings import note_deprecation
50from hypothesis.control import (
51 cleanup,
52 current_build_context,
53 deprecate_random_in_strategy,
54 note,
55 should_note,
56)
57from hypothesis.errors import (
58 HypothesisSideeffectWarning,
59 HypothesisWarning,
60 InvalidArgument,
61 ResolutionFailed,
62 RewindRecursive,
63 SmallSearchSpaceWarning,
64)
65from hypothesis.internal.cathetus import cathetus
66from hypothesis.internal.charmap import (
67 Categories,
68 CategoryName,
69 as_general_categories,
70 categories as all_categories,
71)
72from hypothesis.internal.compat import (
73 Concatenate,
74 EllipsisType,
75 ParamSpec,
76 bit_count,
77 ceil,
78 floor,
79 get_type_hints,
80 is_typed_named_tuple,
81)
82from hypothesis.internal.conjecture.data import ConjectureData
83from hypothesis.internal.conjecture.utils import (
84 calc_label_from_cls,
85 check_sample,
86 identity,
87)
88from hypothesis.internal.entropy import get_seeder_and_restorer
89from hypothesis.internal.floats import float_of
90from hypothesis.internal.reflection import (
91 define_function_signature,
92 get_pretty_function_description,
93 get_signature,
94 is_first_param_referenced_in_function,
95 nicerepr,
96 repr_call,
97 required_args,
98)
99from hypothesis.internal.validation import (
100 check_type,
101 check_valid_integer,
102 check_valid_interval,
103 check_valid_magnitude,
104 check_valid_size,
105 check_valid_sizes,
106 try_convert,
107)
108from hypothesis.strategies._internal import SearchStrategy, check_strategy
109from hypothesis.strategies._internal.collections import (
110 FixedDictStrategy,
111 ListStrategy,
112 TupleStrategy,
113 UniqueListStrategy,
114 UniqueSampledListStrategy,
115 tuples,
116)
117from hypothesis.strategies._internal.deferred import DeferredStrategy
118from hypothesis.strategies._internal.functions import FunctionStrategy
119from hypothesis.strategies._internal.lazy import LazyStrategy, unwrap_strategies
120from hypothesis.strategies._internal.misc import BooleansStrategy, just, none, nothing
121from hypothesis.strategies._internal.numbers import (
122 IntegersStrategy,
123 Real,
124 floats,
125 integers,
126)
127from hypothesis.strategies._internal.recursive import RecursiveStrategy
128from hypothesis.strategies._internal.shared import SharedStrategy
129from hypothesis.strategies._internal.strategies import (
130 Ex,
131 SampledFromStrategy,
132 T,
133 one_of,
134)
135from hypothesis.strategies._internal.strings import (
136 BytesStrategy,
137 OneCharStringStrategy,
138 TextStrategy,
139 _check_is_single_character,
140)
141from hypothesis.strategies._internal.utils import cacheable, defines_strategy
142from hypothesis.utils.conventions import not_set
143from hypothesis.vendor.pretty import RepresentationPrinter
144
145
146@cacheable
147@defines_strategy(force_reusable_values=True)
148def booleans() -> SearchStrategy[bool]:
149 """Returns a strategy which generates instances of :class:`python:bool`.
150
151 Examples from this strategy will shrink towards ``False`` (i.e.
152 shrinking will replace ``True`` with ``False`` where possible).
153 """
154 return BooleansStrategy()
155
156
157@overload
158def sampled_from(elements: Sequence[T]) -> SearchStrategy[T]: # pragma: no cover
159 ...
160
161
162@overload
163def sampled_from(elements: type[enum.Enum]) -> SearchStrategy[Any]: # pragma: no cover
164 # `SearchStrategy[Enum]` is unreliable due to metaclass issues.
165 ...
166
167
168@overload
169def sampled_from(
170 elements: Union[type[enum.Enum], Sequence[Any]],
171) -> SearchStrategy[Any]: # pragma: no cover
172 ...
173
174
175@defines_strategy(try_non_lazy=True)
176def sampled_from(
177 elements: Union[type[enum.Enum], Sequence[Any]],
178) -> SearchStrategy[Any]:
179 """Returns a strategy which generates any value present in ``elements``.
180
181 Note that as with :func:`~hypothesis.strategies.just`, values will not be
182 copied and thus you should be careful of using mutable data.
183
184 ``sampled_from`` supports ordered collections, as well as
185 :class:`~python:enum.Enum` objects. :class:`~python:enum.Flag` objects
186 may also generate any combination of their members.
187
188 Examples from this strategy shrink by replacing them with values earlier in
189 the list. So e.g. ``sampled_from([10, 1])`` will shrink by trying to replace
190 1 values with 10, and ``sampled_from([1, 10])`` will shrink by trying to
191 replace 10 values with 1.
192
193 It is an error to sample from an empty sequence, because returning :func:`nothing`
194 makes it too easy to silently drop parts of compound strategies. If you need
195 that behaviour, use ``sampled_from(seq) if seq else nothing()``.
196 """
197 values = check_sample(elements, "sampled_from")
198 force_repr = None
199 # check_sample converts to tuple unconditionally, but we want to preserve
200 # square braces for list reprs.
201 # This will not cover custom sequence implementations which return different
202 # braces (or other, more unusual things) for their reprs, but this is a tradeoff
203 # between repr accuracy and greedily-evaluating all sequence reprs (at great
204 # cost for large sequences).
205 force_repr_braces = ("[", "]") if isinstance(elements, list) else None
206 if isinstance(elements, type) and issubclass(elements, enum.Enum):
207 force_repr = f"sampled_from({elements.__module__}.{elements.__name__})"
208
209 if isclass(elements) and issubclass(elements, enum.Flag):
210 # Combinations of enum.Flag members (including empty) are also members. We generate these
211 # dynamically, because static allocation takes O(2^n) memory. LazyStrategy is used for the
212 # ease of force_repr.
213 # Add all named values, both flag bits (== list(elements)) and aliases. The aliases are
214 # necessary for full coverage for flags that would fail enum.NAMED_FLAGS check, and they
215 # are also nice values to shrink to.
216 flags = sorted(
217 set(elements.__members__.values()),
218 key=lambda v: (bit_count(v.value), v.value),
219 )
220 # Finally, try to construct the empty state if it is not named. It's placed at the
221 # end so that we shrink to named values.
222 flags_with_empty = flags
223 if not flags or flags[0].value != 0:
224 try:
225 flags_with_empty = [*flags, elements(0)]
226 except TypeError: # pragma: no cover
227 # Happens on some python versions (at least 3.12) when there are no named values
228 pass
229 inner = [
230 # Consider one or no named flags set, with shrink-to-named-flag behaviour.
231 # Special cases (length zero or one) are handled by the inner sampled_from.
232 sampled_from(flags_with_empty),
233 ]
234 if len(flags) > 1:
235 inner += [
236 # Uniform distribution over number of named flags or combinations set. The overlap
237 # at r=1 is intentional, it may lead to oversampling but gives consistent shrinking
238 # behaviour.
239 integers(min_value=1, max_value=len(flags))
240 .flatmap(lambda r: sets(sampled_from(flags), min_size=r, max_size=r))
241 .map(lambda s: elements(reduce(operator.or_, s))),
242 ]
243 return LazyStrategy(one_of, args=inner, kwargs={}, force_repr=force_repr)
244 if not values:
245 if (
246 isinstance(elements, type)
247 and issubclass(elements, enum.Enum)
248 and vars(elements).get("__annotations__")
249 ):
250 # See https://github.com/HypothesisWorks/hypothesis/issues/2923
251 raise InvalidArgument(
252 f"Cannot sample from {elements.__module__}.{elements.__name__} "
253 "because it contains no elements. It does however have annotations, "
254 "so maybe you tried to write an enum as if it was a dataclass?"
255 )
256 raise InvalidArgument("Cannot sample from a length-zero sequence.")
257 if len(values) == 1:
258 return just(values[0])
259 return SampledFromStrategy(
260 values, force_repr=force_repr, force_repr_braces=force_repr_braces
261 )
262
263
264@cacheable
265@defines_strategy()
266def lists(
267 elements: SearchStrategy[Ex],
268 *,
269 min_size: int = 0,
270 max_size: Optional[int] = None,
271 unique_by: Union[
272 None,
273 Callable[[Ex], Hashable],
274 tuple[Callable[[Ex], Hashable], ...],
275 ] = None,
276 unique: bool = False,
277) -> SearchStrategy[list[Ex]]:
278 """Returns a list containing values drawn from elements with length in the
279 interval [min_size, max_size] (no bounds in that direction if these are
280 None). If max_size is 0, only the empty list will be drawn.
281
282 If ``unique`` is True (or something that evaluates to True), we compare direct
283 object equality, as if unique_by was ``lambda x: x``. This comparison only
284 works for hashable types.
285
286 If ``unique_by`` is not None it must be a callable or tuple of callables
287 returning a hashable type when given a value drawn from elements. The
288 resulting list will satisfy the condition that for ``i`` != ``j``,
289 ``unique_by(result[i])`` != ``unique_by(result[j])``.
290
291 If ``unique_by`` is a tuple of callables the uniqueness will be respective
292 to each callable.
293
294 For example, the following will produce two columns of integers with both
295 columns being unique respectively.
296
297 .. code-block:: pycon
298
299 >>> twoints = st.tuples(st.integers(), st.integers())
300 >>> st.lists(twoints, unique_by=(lambda x: x[0], lambda x: x[1]))
301
302 Examples from this strategy shrink by trying to remove elements from the
303 list, and by shrinking each individual element of the list.
304 """
305 check_valid_sizes(min_size, max_size)
306 check_strategy(elements, "elements")
307 if unique:
308 if unique_by is not None:
309 raise InvalidArgument(
310 "cannot specify both unique and unique_by "
311 "(you probably only want to set unique_by)"
312 )
313 else:
314 unique_by = identity
315
316 if max_size == 0:
317 return builds(list)
318 if unique_by is not None:
319 if not (callable(unique_by) or isinstance(unique_by, tuple)):
320 raise InvalidArgument(
321 f"{unique_by=} is not a callable or tuple of callables"
322 )
323 if callable(unique_by):
324 unique_by = (unique_by,)
325 if len(unique_by) == 0:
326 raise InvalidArgument("unique_by is empty")
327 for i, f in enumerate(unique_by):
328 if not callable(f):
329 raise InvalidArgument(f"unique_by[{i}]={f!r} is not a callable")
330 # Note that lazy strategies automatically unwrap when passed to a defines_strategy
331 # function.
332 tuple_suffixes = None
333 if (
334 # We're generating a list of tuples unique by the first element, perhaps
335 # via st.dictionaries(), and this will be more efficient if we rearrange
336 # our strategy somewhat to draw the first element then draw add the rest.
337 isinstance(elements, TupleStrategy)
338 and len(elements.element_strategies) >= 1
339 and len(unique_by) == 1
340 and (
341 # Introspection for either `itemgetter(0)`, or `lambda x: x[0]`
342 (
343 isinstance(unique_by[0], operator.itemgetter)
344 and repr(unique_by[0]) == "operator.itemgetter(0)"
345 )
346 or (
347 isinstance(unique_by[0], FunctionType)
348 and re.fullmatch(
349 get_pretty_function_description(unique_by[0]),
350 r"lambda ([a-z]+): \1\[0\]",
351 )
352 )
353 )
354 ):
355 unique_by = (identity,)
356 tuple_suffixes = TupleStrategy(elements.element_strategies[1:])
357 elements = elements.element_strategies[0]
358
359 # UniqueSampledListStrategy offers a substantial performance improvement for
360 # unique arrays with few possible elements, e.g. of eight-bit integer types.
361 if (
362 isinstance(elements, IntegersStrategy)
363 and elements.start is not None
364 and elements.end is not None
365 and (elements.end - elements.start) <= 255
366 ):
367 elements = SampledFromStrategy(
368 sorted(range(elements.start, elements.end + 1), key=abs) # type: ignore
369 if elements.end < 0 or elements.start > 0
370 else (
371 list(range(elements.end + 1))
372 + list(range(-1, elements.start - 1, -1))
373 )
374 )
375
376 if isinstance(elements, SampledFromStrategy):
377 element_count = len(elements.elements)
378 if min_size > element_count:
379 raise InvalidArgument(
380 f"Cannot create a collection of {min_size=} unique "
381 f"elements with values drawn from only {element_count} distinct "
382 "elements"
383 )
384
385 if max_size is not None:
386 max_size = min(max_size, element_count)
387 else:
388 max_size = element_count
389
390 return UniqueSampledListStrategy(
391 elements=elements,
392 max_size=max_size,
393 min_size=min_size,
394 keys=unique_by,
395 tuple_suffixes=tuple_suffixes,
396 )
397
398 return UniqueListStrategy(
399 elements=elements,
400 max_size=max_size,
401 min_size=min_size,
402 keys=unique_by,
403 tuple_suffixes=tuple_suffixes,
404 )
405 return ListStrategy(elements, min_size=min_size, max_size=max_size)
406
407
408@cacheable
409@defines_strategy()
410def sets(
411 elements: SearchStrategy[Ex],
412 *,
413 min_size: int = 0,
414 max_size: Optional[int] = None,
415) -> SearchStrategy[set[Ex]]:
416 """This has the same behaviour as lists, but returns sets instead.
417
418 Note that Hypothesis cannot tell if values are drawn from elements
419 are hashable until running the test, so you can define a strategy
420 for sets of an unhashable type but it will fail at test time.
421
422 Examples from this strategy shrink by trying to remove elements from the
423 set, and by shrinking each individual element of the set.
424 """
425 return lists(
426 elements=elements, min_size=min_size, max_size=max_size, unique=True
427 ).map(set)
428
429
430@cacheable
431@defines_strategy()
432def frozensets(
433 elements: SearchStrategy[Ex],
434 *,
435 min_size: int = 0,
436 max_size: Optional[int] = None,
437) -> SearchStrategy[frozenset[Ex]]:
438 """This is identical to the sets function but instead returns
439 frozensets."""
440 return lists(
441 elements=elements, min_size=min_size, max_size=max_size, unique=True
442 ).map(frozenset)
443
444
445class PrettyIter:
446 def __init__(self, values):
447 self._values = values
448 self._iter = iter(self._values)
449
450 def __iter__(self):
451 return self._iter
452
453 def __next__(self):
454 return next(self._iter)
455
456 def __repr__(self) -> str:
457 return f"iter({self._values!r})"
458
459
460@defines_strategy()
461def iterables(
462 elements: SearchStrategy[Ex],
463 *,
464 min_size: int = 0,
465 max_size: Optional[int] = None,
466 unique_by: Union[
467 None,
468 Callable[[Ex], Hashable],
469 tuple[Callable[[Ex], Hashable], ...],
470 ] = None,
471 unique: bool = False,
472) -> SearchStrategy[Iterable[Ex]]:
473 """This has the same behaviour as lists, but returns iterables instead.
474
475 Some iterables cannot be indexed (e.g. sets) and some do not have a
476 fixed length (e.g. generators). This strategy produces iterators,
477 which cannot be indexed and do not have a fixed length. This ensures
478 that you do not accidentally depend on sequence behaviour.
479 """
480 return lists(
481 elements=elements,
482 min_size=min_size,
483 max_size=max_size,
484 unique_by=unique_by,
485 unique=unique,
486 ).map(PrettyIter)
487
488
489# this type definition is imprecise, in multiple ways:
490# * mapping and optional can be of different types:
491# s: dict[str | int, int] = st.fixed_dictionaries(
492# {"a": st.integers()}, optional={1: st.integers()}
493# )
494# * the values in either mapping or optional need not all be of the same type:
495# s: dict[str, int | bool] = st.fixed_dictionaries(
496# {"a": st.integers(), "b": st.booleans()}
497# )
498# * the arguments may be of any dict-compatible type, in which case the return
499# value will be of that type instead of dit
500#
501# Overloads may help here, but I doubt we'll be able to satisfy all these
502# constraints.
503#
504# Here's some platonic ideal test cases for revealed_types.py, with the understanding
505# that some may not be achievable:
506#
507# ("fixed_dictionaries({'a': booleans()})", "dict[str, bool]"),
508# ("fixed_dictionaries({'a': booleans(), 'b': integers()})", "dict[str, bool | int]"),
509# ("fixed_dictionaries({}, optional={'a': booleans()})", "dict[str, bool]"),
510# (
511# "fixed_dictionaries({'a': booleans()}, optional={1: booleans()})",
512# "dict[str | int, bool]",
513# ),
514# (
515# "fixed_dictionaries({'a': booleans()}, optional={1: integers()})",
516# "dict[str | int, bool | int]",
517# ),
518
519
520@defines_strategy()
521def fixed_dictionaries(
522 mapping: dict[T, SearchStrategy[Ex]],
523 *,
524 optional: Optional[dict[T, SearchStrategy[Ex]]] = None,
525) -> SearchStrategy[dict[T, Ex]]:
526 """Generates a dictionary of the same type as mapping with a fixed set of
527 keys mapping to strategies. ``mapping`` must be a dict subclass.
528
529 Generated values have all keys present in mapping, in iteration order,
530 with the corresponding values drawn from mapping[key].
531
532 If ``optional`` is passed, the generated value *may or may not* contain each
533 key from ``optional`` and a value drawn from the corresponding strategy.
534 Generated values may contain optional keys in an arbitrary order.
535
536 Examples from this strategy shrink by shrinking each individual value in
537 the generated dictionary, and omitting optional key-value pairs.
538 """
539 check_type(dict, mapping, "mapping")
540 for k, v in mapping.items():
541 check_strategy(v, f"mapping[{k!r}]")
542
543 if optional is not None:
544 check_type(dict, optional, "optional")
545 for k, v in optional.items():
546 check_strategy(v, f"optional[{k!r}]")
547 if type(mapping) != type(optional):
548 raise InvalidArgument(
549 f"Got arguments of different types: "
550 f"mapping={nicerepr(type(mapping))}, "
551 f"optional={nicerepr(type(optional))}"
552 )
553 if set(mapping) & set(optional):
554 raise InvalidArgument(
555 "The following keys were in both mapping and optional, "
556 f"which is invalid: {set(mapping) & set(optional)!r}"
557 )
558
559 return FixedDictStrategy(mapping, optional=optional)
560
561
562@cacheable
563@defines_strategy()
564def dictionaries(
565 keys: SearchStrategy[Ex],
566 values: SearchStrategy[T],
567 *,
568 dict_class: type = dict,
569 min_size: int = 0,
570 max_size: Optional[int] = None,
571) -> SearchStrategy[dict[Ex, T]]:
572 # Describing the exact dict_class to Mypy drops the key and value types,
573 # so we report Dict[K, V] instead of Mapping[Any, Any] for now. Sorry!
574 """Generates dictionaries of type ``dict_class`` with keys drawn from the ``keys``
575 argument and values drawn from the ``values`` argument.
576
577 The size parameters have the same interpretation as for
578 :func:`~hypothesis.strategies.lists`.
579
580 Examples from this strategy shrink by trying to remove keys from the
581 generated dictionary, and by shrinking each generated key and value.
582 """
583 check_valid_sizes(min_size, max_size)
584 if max_size == 0:
585 return fixed_dictionaries(dict_class())
586 check_strategy(keys, "keys")
587 check_strategy(values, "values")
588
589 return lists(
590 tuples(keys, values),
591 min_size=min_size,
592 max_size=max_size,
593 unique_by=operator.itemgetter(0),
594 ).map(dict_class)
595
596
597@cacheable
598@defines_strategy(force_reusable_values=True)
599def characters(
600 *,
601 codec: Optional[str] = None,
602 min_codepoint: Optional[int] = None,
603 max_codepoint: Optional[int] = None,
604 categories: Optional[Collection[CategoryName]] = None,
605 exclude_categories: Optional[Collection[CategoryName]] = None,
606 exclude_characters: Optional[Collection[str]] = None,
607 include_characters: Optional[Collection[str]] = None,
608 # Note: these arguments are deprecated aliases for backwards compatibility
609 blacklist_categories: Optional[Collection[CategoryName]] = None,
610 whitelist_categories: Optional[Collection[CategoryName]] = None,
611 blacklist_characters: Optional[Collection[str]] = None,
612 whitelist_characters: Optional[Collection[str]] = None,
613) -> SearchStrategy[str]:
614 r"""Generates characters, length-one :class:`python:str`\ ings,
615 following specified filtering rules.
616
617 - When no filtering rules are specified, any character can be produced.
618 - If ``min_codepoint`` or ``max_codepoint`` is specified, then only
619 characters having a codepoint in that range will be produced.
620 - If ``categories`` is specified, then only characters from those
621 Unicode categories will be produced. This is a further restriction,
622 characters must also satisfy ``min_codepoint`` and ``max_codepoint``.
623 - If ``exclude_categories`` is specified, then any character from those
624 categories will not be produced. You must not pass both ``categories``
625 and ``exclude_categories``; these arguments are alternative ways to
626 specify exactly the same thing.
627 - If ``include_characters`` is specified, then any additional characters
628 in that list will also be produced.
629 - If ``exclude_characters`` is specified, then any characters in
630 that list will be not be produced. Any overlap between
631 ``include_characters`` and ``exclude_characters`` will raise an
632 exception.
633 - If ``codec`` is specified, only characters in the specified `codec encodings`_
634 will be produced.
635
636 The ``_codepoint`` arguments must be integers between zero and
637 :obj:`python:sys.maxunicode`. The ``_characters`` arguments must be
638 collections of length-one unicode strings, such as a unicode string.
639
640 The ``_categories`` arguments must be used to specify either the
641 one-letter Unicode major category or the two-letter Unicode
642 `general category`_. For example, ``('Nd', 'Lu')`` signifies "Number,
643 decimal digit" and "Letter, uppercase". A single letter ('major category')
644 can be given to match all corresponding categories, for example ``'P'``
645 for characters in any punctuation category.
646
647 We allow codecs from the :mod:`codecs` module and their aliases, platform
648 specific and user-registered codecs if they are available, and
649 `python-specific text encodings`_ (but not text or binary transforms).
650 ``include_characters`` which cannot be encoded using this codec will
651 raise an exception. If non-encodable codepoints or categories are
652 explicitly allowed, the ``codec`` argument will exclude them without
653 raising an exception.
654
655 .. _general category: https://en.wikipedia.org/wiki/Unicode_character_property
656 .. _codec encodings: https://docs.python.org/3/library/codecs.html#encodings-and-unicode
657 .. _python-specific text encodings: https://docs.python.org/3/library/codecs.html#python-specific-encodings
658
659 Examples from this strategy shrink towards the codepoint for ``'0'``,
660 or the first allowable codepoint after it if ``'0'`` is excluded.
661 """
662 check_valid_size(min_codepoint, "min_codepoint")
663 check_valid_size(max_codepoint, "max_codepoint")
664 check_valid_interval(min_codepoint, max_codepoint, "min_codepoint", "max_codepoint")
665 categories = cast(Optional[Categories], categories)
666 if categories is not None and exclude_categories is not None:
667 raise InvalidArgument(
668 f"Pass at most one of {categories=} and {exclude_categories=} - "
669 "these arguments both specify which categories are allowed, so it "
670 "doesn't make sense to use both in a single call."
671 )
672
673 # Handle deprecation of whitelist/blacklist arguments
674 has_old_arg = any(v is not None for k, v in locals().items() if "list" in k)
675 has_new_arg = any(v is not None for k, v in locals().items() if "lude" in k)
676 if has_old_arg and has_new_arg:
677 raise InvalidArgument(
678 "The deprecated blacklist/whitelist arguments cannot be used in "
679 "the same call as their replacement include/exclude arguments."
680 )
681 if blacklist_categories is not None:
682 exclude_categories = blacklist_categories
683 if whitelist_categories is not None:
684 categories = whitelist_categories
685 if blacklist_characters is not None:
686 exclude_characters = blacklist_characters
687 if whitelist_characters is not None:
688 include_characters = whitelist_characters
689
690 if (
691 min_codepoint is None
692 and max_codepoint is None
693 and categories is None
694 and exclude_categories is None
695 and include_characters is not None
696 and codec is None
697 ):
698 raise InvalidArgument(
699 "Nothing is excluded by other arguments, so passing only "
700 f"{include_characters=} would have no effect. "
701 "Also pass categories=(), or use "
702 f"sampled_from({include_characters!r}) instead."
703 )
704 exclude_characters = exclude_characters or ""
705 include_characters = include_characters or ""
706 overlap = set(exclude_characters).intersection(include_characters)
707 if overlap:
708 raise InvalidArgument(
709 f"Characters {sorted(overlap)!r} are present in both "
710 f"{include_characters=} and {exclude_characters=}"
711 )
712 if categories is not None:
713 categories = as_general_categories(categories, "categories")
714 if exclude_categories is not None:
715 exclude_categories = as_general_categories(
716 exclude_categories, "exclude_categories"
717 )
718 if categories is not None and not categories and not include_characters:
719 raise InvalidArgument(
720 "When `categories` is an empty collection and there are "
721 "no characters specified in include_characters, nothing can "
722 "be generated by the characters() strategy."
723 )
724 both_cats = set(exclude_categories or ()).intersection(categories or ())
725 if both_cats:
726 # Note: we check that exactly one of `categories` or `exclude_categories` is
727 # passed above, but retain this older check for the deprecated arguments.
728 raise InvalidArgument(
729 f"Categories {sorted(both_cats)!r} are present in both "
730 f"{categories=} and {exclude_categories=}"
731 )
732 elif exclude_categories is not None:
733 categories = set(all_categories()) - set(exclude_categories)
734 del exclude_categories
735
736 if codec is not None:
737 try:
738 codec = codecs.lookup(codec).name
739 # Check this is not a str-to-str or bytes-to-bytes codec; see
740 # https://docs.python.org/3/library/codecs.html#binary-transforms
741 "".encode(codec)
742 except LookupError:
743 raise InvalidArgument(f"{codec=} is not valid on this system") from None
744 except Exception:
745 raise InvalidArgument(f"{codec=} is not a valid codec") from None
746
747 for char in include_characters:
748 try:
749 char.encode(encoding=codec, errors="strict")
750 except UnicodeEncodeError:
751 raise InvalidArgument(
752 f"Character {char!r} in {include_characters=} "
753 f"cannot be encoded with {codec=}"
754 ) from None
755
756 # ascii and utf-8 are sufficient common that we have faster special handling
757 if codec == "ascii":
758 if (max_codepoint is None) or (max_codepoint > 127):
759 max_codepoint = 127
760 codec = None
761 elif codec == "utf-8":
762 if categories is None:
763 categories = all_categories()
764 categories = tuple(c for c in categories if c != "Cs")
765
766 return OneCharStringStrategy.from_characters_args(
767 categories=categories,
768 exclude_characters=exclude_characters,
769 min_codepoint=min_codepoint,
770 max_codepoint=max_codepoint,
771 include_characters=include_characters,
772 codec=codec,
773 )
774
775
776# Hide the deprecated aliases from documentation and casual inspection
777characters.__signature__ = (__sig := get_signature(characters)).replace( # type: ignore
778 parameters=[p for p in __sig.parameters.values() if "list" not in p.name]
779)
780
781
782@cacheable
783@defines_strategy(force_reusable_values=True)
784def text(
785 alphabet: Union[Collection[str], SearchStrategy[str]] = characters(codec="utf-8"),
786 *,
787 min_size: int = 0,
788 max_size: Optional[int] = None,
789) -> SearchStrategy[str]:
790 """Generates strings with characters drawn from ``alphabet``, which should
791 be a collection of length one strings or a strategy generating such strings.
792
793 The default alphabet strategy can generate the full unicode range but
794 excludes surrogate characters because they are invalid in the UTF-8
795 encoding. You can use :func:`~hypothesis.strategies.characters` without
796 arguments to find surrogate-related bugs such as :bpo:`34454`.
797
798 ``min_size`` and ``max_size`` have the usual interpretations.
799 Note that Python measures string length by counting codepoints: U+00C5
800 ``Å`` is a single character, while U+0041 U+030A ``Å`` is two - the ``A``,
801 and a combining ring above.
802
803 Examples from this strategy shrink towards shorter strings, and with the
804 characters in the text shrinking as per the alphabet strategy.
805 This strategy does not :func:`~python:unicodedata.normalize` examples,
806 so generated strings may be in any or none of the 'normal forms'.
807 """
808 check_valid_sizes(min_size, max_size)
809 if isinstance(alphabet, SearchStrategy):
810 char_strategy = unwrap_strategies(alphabet)
811 if isinstance(char_strategy, SampledFromStrategy):
812 # Check this via the up-front validation logic below, and incidentally
813 # convert into a `characters()` strategy for standard text shrinking.
814 return text(char_strategy.elements, min_size=min_size, max_size=max_size)
815 elif not isinstance(char_strategy, OneCharStringStrategy):
816 char_strategy = char_strategy.map(_check_is_single_character)
817 else:
818 non_string = [c for c in alphabet if not isinstance(c, str)]
819 if non_string:
820 raise InvalidArgument(
821 "The following elements in alphabet are not unicode "
822 f"strings: {non_string!r}"
823 )
824 not_one_char = [c for c in alphabet if len(c) != 1]
825 if not_one_char:
826 raise InvalidArgument(
827 "The following elements in alphabet are not of length one, "
828 f"which leads to violation of size constraints: {not_one_char!r}"
829 )
830 if alphabet in ["ascii", "utf-8"]:
831 warnings.warn(
832 f"st.text({alphabet!r}): it seems like you are trying to use the "
833 f"codec {alphabet!r}. st.text({alphabet!r}) instead generates "
834 f"strings using the literal characters {list(alphabet)!r}. To specify "
835 f"the {alphabet} codec, use st.text(st.characters(codec={alphabet!r})). "
836 "If you intended to use character literals, you can silence this "
837 "warning by reordering the characters.",
838 HypothesisWarning,
839 # this stacklevel is of course incorrect, but breaking out of the
840 # levels of LazyStrategy and validation isn't worthwhile.
841 stacklevel=1,
842 )
843 char_strategy = (
844 characters(categories=(), include_characters=alphabet)
845 if alphabet
846 else nothing()
847 )
848 if (max_size == 0 or char_strategy.is_empty) and not min_size:
849 return just("")
850 # mypy is unhappy with ListStrategy(SearchStrategy[list[Ex]]) and then TextStrategy
851 # setting Ex = str. Mypy is correct to complain because we have an LSP violation
852 # here in the TextStrategy.do_draw override. Would need refactoring to resolve.
853 return TextStrategy(char_strategy, min_size=min_size, max_size=max_size) # type: ignore
854
855
856@overload
857def from_regex(
858 regex: Union[bytes, Pattern[bytes]],
859 *,
860 fullmatch: bool = False,
861) -> SearchStrategy[bytes]: # pragma: no cover
862 ...
863
864
865@overload
866def from_regex(
867 regex: Union[str, Pattern[str]],
868 *,
869 fullmatch: bool = False,
870 alphabet: Union[str, SearchStrategy[str]] = characters(codec="utf-8"),
871) -> SearchStrategy[str]: # pragma: no cover
872 ...
873
874
875@cacheable
876@defines_strategy()
877def from_regex(
878 regex: Union[AnyStr, Pattern[AnyStr]],
879 *,
880 fullmatch: bool = False,
881 alphabet: Union[str, SearchStrategy[str], None] = None,
882) -> SearchStrategy[AnyStr]:
883 r"""Generates strings that contain a match for the given regex (i.e. ones
884 for which :func:`python:re.search` will return a non-None result).
885
886 ``regex`` may be a pattern or :func:`compiled regex <python:re.compile>`.
887 Both byte-strings and unicode strings are supported, and will generate
888 examples of the same type.
889
890 You can use regex flags such as :obj:`python:re.IGNORECASE` or
891 :obj:`python:re.DOTALL` to control generation. Flags can be passed either
892 in compiled regex or inside the pattern with a ``(?iLmsux)`` group.
893
894 Some regular expressions are only partly supported - the underlying
895 strategy checks local matching and relies on filtering to resolve
896 context-dependent expressions. Using too many of these constructs may
897 cause health-check errors as too many examples are filtered out. This
898 mainly includes (positive or negative) lookahead and lookbehind groups.
899
900 If you want the generated string to match the whole regex you should use
901 boundary markers. So e.g. ``r"\A.\Z"`` will return a single character
902 string, while ``"."`` will return any string, and ``r"\A.$"`` will return
903 a single character optionally followed by a ``"\n"``.
904 Alternatively, passing ``fullmatch=True`` will ensure that the whole
905 string is a match, as if you had used the ``\A`` and ``\Z`` markers.
906
907 The ``alphabet=`` argument constrains the characters in the generated
908 string, as for :func:`text`, and is only supported for unicode strings.
909
910 Examples from this strategy shrink towards shorter strings and lower
911 character values, with exact behaviour that may depend on the pattern.
912 """
913 check_type((str, bytes, re.Pattern), regex, "regex")
914 check_type(bool, fullmatch, "fullmatch")
915 pattern = regex.pattern if isinstance(regex, re.Pattern) else regex
916 if alphabet is not None:
917 check_type((str, SearchStrategy), alphabet, "alphabet")
918 if not isinstance(pattern, str):
919 raise InvalidArgument("alphabet= is not supported for bytestrings")
920 alphabet = OneCharStringStrategy.from_alphabet(alphabet)
921 elif isinstance(pattern, str):
922 alphabet = characters(codec="utf-8")
923
924 # TODO: We would like to move this to the top level, but pending some major
925 # refactoring it's hard to do without creating circular imports.
926 from hypothesis.strategies._internal.regex import regex_strategy
927
928 return regex_strategy(regex, fullmatch, alphabet=alphabet)
929
930
931@cacheable
932@defines_strategy(force_reusable_values=True)
933def binary(
934 *,
935 min_size: int = 0,
936 max_size: Optional[int] = None,
937) -> SearchStrategy[bytes]:
938 """Generates :class:`python:bytes`.
939
940 The generated :class:`python:bytes` will have a length of at least ``min_size``
941 and at most ``max_size``. If ``max_size`` is None there is no upper limit.
942
943 Examples from this strategy shrink towards smaller strings and lower byte
944 values.
945 """
946 check_valid_sizes(min_size, max_size)
947 return BytesStrategy(min_size, max_size)
948
949
950@cacheable
951@defines_strategy()
952def randoms(
953 *,
954 note_method_calls: bool = False,
955 use_true_random: bool = False,
956) -> SearchStrategy[random.Random]:
957 """Generates instances of ``random.Random``. The generated Random instances
958 are of a special HypothesisRandom subclass.
959
960 - If ``note_method_calls`` is set to ``True``, Hypothesis will print the
961 randomly drawn values in any falsifying test case. This can be helpful
962 for debugging the behaviour of randomized algorithms.
963 - If ``use_true_random`` is set to ``True`` then values will be drawn from
964 their usual distribution, otherwise they will actually be Hypothesis
965 generated values (and will be shrunk accordingly for any failing test
966 case). Setting ``use_true_random=False`` will tend to expose bugs that
967 would occur with very low probability when it is set to True, and this
968 flag should only be set to True when your code relies on the distribution
969 of values for correctness.
970
971 For managing global state, see the :func:`~hypothesis.strategies.random_module`
972 strategy and :func:`~hypothesis.register_random` function.
973 """
974 check_type(bool, note_method_calls, "note_method_calls")
975 check_type(bool, use_true_random, "use_true_random")
976
977 from hypothesis.strategies._internal.random import RandomStrategy
978
979 return RandomStrategy(
980 use_true_random=use_true_random, note_method_calls=note_method_calls
981 )
982
983
984class RandomSeeder:
985 def __init__(self, seed):
986 self.seed = seed
987
988 def __repr__(self):
989 return f"RandomSeeder({self.seed!r})"
990
991
992class RandomModule(SearchStrategy):
993 def do_draw(self, data: ConjectureData) -> RandomSeeder:
994 # It would be unsafe to do run this method more than once per test case,
995 # because cleanup() runs tasks in FIFO order (at time of writing!).
996 # Fortunately, the random_module() strategy wraps us in shared(), so
997 # it's cached for all but the first of any number of calls.
998 seed = data.draw(integers(0, 2**32 - 1))
999 seed_all, restore_all = get_seeder_and_restorer(seed)
1000 seed_all()
1001 cleanup(restore_all)
1002 return RandomSeeder(seed)
1003
1004
1005@cacheable
1006@defines_strategy()
1007def random_module() -> SearchStrategy[RandomSeeder]:
1008 """Hypothesis always seeds global PRNGs before running a test, and restores the
1009 previous state afterwards.
1010
1011 If having a fixed seed would unacceptably weaken your tests, and you
1012 cannot use a ``random.Random`` instance provided by
1013 :func:`~hypothesis.strategies.randoms`, this strategy calls
1014 :func:`python:random.seed` with an arbitrary integer and passes you
1015 an opaque object whose repr displays the seed value for debugging.
1016 If ``numpy.random`` is available, that state is also managed, as is anything
1017 managed by :func:`hypothesis.register_random`.
1018
1019 Examples from these strategy shrink to seeds closer to zero.
1020 """
1021 return shared(RandomModule(), key="hypothesis.strategies.random_module()")
1022
1023
1024class BuildsStrategy(SearchStrategy[Ex]):
1025 def __init__(
1026 self,
1027 target: Callable[..., Ex],
1028 args: tuple[SearchStrategy[Any], ...],
1029 kwargs: dict[str, SearchStrategy[Any]],
1030 ):
1031 super().__init__()
1032 self.target = target
1033 self.args = args
1034 self.kwargs = kwargs
1035
1036 def do_draw(self, data: ConjectureData) -> Ex:
1037 args = [data.draw(s) for s in self.args]
1038 kwargs = {k: data.draw(v) for k, v in self.kwargs.items()}
1039 try:
1040 obj = self.target(*args, **kwargs)
1041 except TypeError as err:
1042 if (
1043 isinstance(self.target, type)
1044 and issubclass(self.target, enum.Enum)
1045 and not (self.args or self.kwargs)
1046 ):
1047 name = self.target.__module__ + "." + self.target.__qualname__
1048 raise InvalidArgument(
1049 f"Calling {name} with no arguments raised an error - "
1050 f"try using sampled_from({name}) instead of builds({name})"
1051 ) from err
1052 if not (self.args or self.kwargs):
1053 from .types import is_a_new_type, is_generic_type
1054
1055 if is_a_new_type(self.target) or is_generic_type(self.target):
1056 raise InvalidArgument(
1057 f"Calling {self.target!r} with no arguments raised an "
1058 f"error - try using from_type({self.target!r}) instead "
1059 f"of builds({self.target!r})"
1060 ) from err
1061 if getattr(self.target, "__no_type_check__", None) is True:
1062 # Note: could use PEP-678 __notes__ here. Migrate over once we're
1063 # using an `exceptiongroup` backport with support for that.
1064 raise TypeError(
1065 "This might be because the @no_type_check decorator prevented "
1066 "Hypothesis from inferring a strategy for some required arguments."
1067 ) from err
1068 raise
1069
1070 current_build_context().record_call(obj, self.target, args, kwargs)
1071 return obj
1072
1073 def do_validate(self) -> None:
1074 tuples(*self.args).validate()
1075 fixed_dictionaries(self.kwargs).validate()
1076
1077 def __repr__(self) -> str:
1078 bits = [get_pretty_function_description(self.target)]
1079 bits.extend(map(repr, self.args))
1080 bits.extend(f"{k}={v!r}" for k, v in self.kwargs.items())
1081 return f"builds({', '.join(bits)})"
1082
1083
1084@cacheable
1085@defines_strategy()
1086def builds(
1087 target: Callable[..., Ex],
1088 /,
1089 *args: SearchStrategy[Any],
1090 **kwargs: Union[SearchStrategy[Any], EllipsisType],
1091) -> SearchStrategy[Ex]:
1092 """Generates values by drawing from ``args`` and ``kwargs`` and passing
1093 them to the callable (provided as the first positional argument) in the
1094 appropriate argument position.
1095
1096 e.g. ``builds(target, integers(), flag=booleans())`` would draw an
1097 integer ``i`` and a boolean ``b`` and call ``target(i, flag=b)``.
1098
1099 If the callable has type annotations, they will be used to infer a strategy
1100 for required arguments that were not passed to builds. You can also tell
1101 builds to infer a strategy for an optional argument by passing ``...``
1102 (:obj:`python:Ellipsis`) as a keyword argument to builds, instead of a strategy for
1103 that argument to the callable.
1104
1105 If the callable is a class defined with :pypi:`attrs`, missing required
1106 arguments will be inferred from the attribute on a best-effort basis,
1107 e.g. by checking :ref:`attrs standard validators <attrs:api-validators>`.
1108 Dataclasses are handled natively by the inference from type hints.
1109
1110 Examples from this strategy shrink by shrinking the argument values to
1111 the callable.
1112 """
1113 if not callable(target):
1114 raise InvalidArgument(
1115 "The first positional argument to builds() must be a callable "
1116 "target to construct."
1117 )
1118
1119 if ... in args: # type: ignore # we only annotated the allowed types
1120 # Avoid an implementation nightmare juggling tuples and worse things
1121 raise InvalidArgument(
1122 "... was passed as a positional argument to "
1123 "builds(), but is only allowed as a keyword arg"
1124 )
1125 required = required_args(target, args, kwargs)
1126 to_infer = {k for k, v in kwargs.items() if v is ...}
1127 if required or to_infer:
1128 if isinstance(target, type) and attr.has(target):
1129 # Use our custom introspection for attrs classes
1130 from hypothesis.strategies._internal.attrs import from_attrs
1131
1132 return from_attrs(target, args, kwargs, required | to_infer)
1133 # Otherwise, try using type hints
1134 hints = get_type_hints(target)
1135 if to_infer - set(hints):
1136 badargs = ", ".join(sorted(to_infer - set(hints)))
1137 raise InvalidArgument(
1138 f"passed ... for {badargs}, but we cannot infer a strategy "
1139 "because these arguments have no type annotation"
1140 )
1141 infer_for = {k: v for k, v in hints.items() if k in (required | to_infer)}
1142 if infer_for:
1143 from hypothesis.strategies._internal.types import _global_type_lookup
1144
1145 for kw, t in infer_for.items():
1146 if t in _global_type_lookup:
1147 kwargs[kw] = from_type(t)
1148 else:
1149 # We defer resolution of these type annotations so that the obvious
1150 # approach to registering recursive types just works. I.e.,
1151 # if we're inside `register_type_strategy(cls, builds(cls, ...))`
1152 # and `...` contains recursion on `cls`. See
1153 # https://github.com/HypothesisWorks/hypothesis/issues/3026
1154 kwargs[kw] = deferred(lambda t=t: from_type(t)) # type: ignore
1155
1156 # validated by handling all EllipsisType in the to_infer case
1157 kwargs = cast(dict[str, SearchStrategy], kwargs)
1158 return BuildsStrategy(target, args, kwargs)
1159
1160
1161@cacheable
1162@defines_strategy(never_lazy=True)
1163def from_type(thing: type[T]) -> SearchStrategy[T]:
1164 """Looks up the appropriate search strategy for the given type.
1165
1166 |st.from_type| is used internally to fill in missing arguments to
1167 |st.builds| and can be used interactively
1168 to explore what strategies are available or to debug type resolution.
1169
1170 You can use |st.register_type_strategy| to
1171 handle your custom types, or to globally redefine certain strategies -
1172 for example excluding NaN from floats, or use timezone-aware instead of
1173 naive time and datetime strategies.
1174
1175 |st.from_type| looks up a strategy in the following order:
1176
1177 1. If ``thing`` is in the default lookup mapping or user-registered lookup,
1178 return the corresponding strategy. The default lookup covers all types
1179 with Hypothesis strategies, including extras where possible.
1180 2. If ``thing`` is from the :mod:`python:typing` module, return the
1181 corresponding strategy (special logic).
1182 3. If ``thing`` has one or more subtypes in the merged lookup, return
1183 the union of the strategies for those types that are not subtypes of
1184 other elements in the lookup.
1185 4. Finally, if ``thing`` has type annotations for all required arguments,
1186 and is not an abstract class, it is resolved via
1187 |st.builds|.
1188 5. Because :mod:`abstract types <python:abc>` cannot be instantiated,
1189 we treat abstract types as the union of their concrete subclasses.
1190 Note that this lookup works via inheritance but not via
1191 :obj:`~python:abc.ABCMeta.register`, so you may still need to use
1192 |st.register_type_strategy|.
1193
1194 There is a valuable recipe for leveraging |st.from_type| to generate
1195 "everything except" values from a specified type. I.e.
1196
1197 .. code-block:: python
1198
1199 def everything_except(excluded_types):
1200 return (
1201 from_type(type)
1202 .flatmap(from_type)
1203 .filter(lambda x: not isinstance(x, excluded_types))
1204 )
1205
1206 For example, ``everything_except(int)`` returns a strategy that can
1207 generate anything that |st.from_type| can ever generate, except for
1208 instances of |int|, and excluding instances of types
1209 added via |st.register_type_strategy|.
1210
1211 This is useful when writing tests which check that invalid input is
1212 rejected in a certain way.
1213 """
1214 try:
1215 with warnings.catch_warnings():
1216 warnings.simplefilter("error")
1217 return _from_type(thing)
1218 except Exception:
1219 return _from_type_deferred(thing)
1220
1221
1222def _from_type_deferred(thing: type[Ex]) -> SearchStrategy[Ex]:
1223 # This tricky little dance is because we want to show the repr of the actual
1224 # underlying strategy wherever possible, as a form of user education, but
1225 # would prefer to fall back to the default "from_type(...)" repr instead of
1226 # "deferred(...)" for recursive types or invalid arguments.
1227 try:
1228 thing_repr = nicerepr(thing)
1229 if hasattr(thing, "__module__"):
1230 module_prefix = f"{thing.__module__}."
1231 if not thing_repr.startswith(module_prefix):
1232 thing_repr = module_prefix + thing_repr
1233 repr_ = f"from_type({thing_repr})"
1234 except Exception: # pragma: no cover
1235 repr_ = None
1236 return LazyStrategy(
1237 lambda thing: deferred(lambda: _from_type(thing)),
1238 (thing,),
1239 {},
1240 force_repr=repr_,
1241 )
1242
1243
1244_recurse_guard: ContextVar = ContextVar("recurse_guard")
1245
1246
1247def _from_type(thing: type[Ex]) -> SearchStrategy[Ex]:
1248 # TODO: We would like to move this to the top level, but pending some major
1249 # refactoring it's hard to do without creating circular imports.
1250 from hypothesis.strategies._internal import types
1251
1252 def as_strategy(strat_or_callable, thing):
1253 # User-provided strategies need some validation, and callables even more
1254 # of it. We do this in three places, hence the helper function
1255 if not isinstance(strat_or_callable, SearchStrategy):
1256 assert callable(strat_or_callable) # Validated in register_type_strategy
1257 strategy = strat_or_callable(thing)
1258 else:
1259 strategy = strat_or_callable
1260 if strategy is NotImplemented:
1261 return NotImplemented
1262 if not isinstance(strategy, SearchStrategy):
1263 raise ResolutionFailed(
1264 f"Error: {thing} was registered for {nicerepr(strat_or_callable)}, "
1265 f"but returned non-strategy {strategy!r}"
1266 )
1267 if strategy.is_empty:
1268 raise ResolutionFailed(f"Error: {thing!r} resolved to an empty strategy")
1269 return strategy
1270
1271 def from_type_guarded(thing):
1272 """Returns the result of producer, or ... if recursion on thing is encountered"""
1273 try:
1274 recurse_guard = _recurse_guard.get()
1275 except LookupError:
1276 # We can't simply define the contextvar with default=[], as the
1277 # default object would be shared across contexts
1278 _recurse_guard.set(recurse_guard := [])
1279 if thing in recurse_guard:
1280 raise RewindRecursive(thing)
1281 recurse_guard.append(thing)
1282 try:
1283 return _from_type(thing)
1284 except RewindRecursive as rr:
1285 if rr.target != thing:
1286 raise
1287 return ... # defer resolution
1288 finally:
1289 recurse_guard.pop()
1290
1291 # Let registered extra modules handle their own recognized types first, before
1292 # e.g. Unions are resolved
1293 try:
1294 known = thing in types._global_type_lookup
1295 except TypeError:
1296 # thing is not always hashable!
1297 pass
1298 else:
1299 if not known:
1300 for module, resolver in types._global_extra_lookup.items():
1301 if module in sys.modules:
1302 strat = resolver(thing)
1303 if strat is not None:
1304 return strat
1305 if not isinstance(thing, type):
1306 if types.is_a_new_type(thing):
1307 # Check if we have an explicitly registered strategy for this thing,
1308 # resolve it so, and otherwise resolve as for the base type.
1309 if thing in types._global_type_lookup:
1310 strategy = as_strategy(types._global_type_lookup[thing], thing)
1311 if strategy is not NotImplemented:
1312 return strategy
1313 return _from_type(thing.__supertype__)
1314 if types.is_a_type_alias_type(
1315 thing
1316 ): # pragma: no cover # covered by 3.12+ tests
1317 if thing in types._global_type_lookup:
1318 strategy = as_strategy(types._global_type_lookup[thing], thing)
1319 if strategy is not NotImplemented:
1320 return strategy
1321 return _from_type(thing.__value__)
1322 # Unions are not instances of `type` - but we still want to resolve them!
1323 if types.is_a_union(thing):
1324 args = sorted(thing.__args__, key=types.type_sorting_key)
1325 return one_of([_from_type(t) for t in args])
1326 if thing in types.LiteralStringTypes: # pragma: no cover
1327 # We can't really cover this because it needs either
1328 # typing-extensions or python3.11+ typing.
1329 # `LiteralString` from runtime's point of view is just a string.
1330 # Fallback to regular text.
1331 return text()
1332 # We also have a special case for TypeVars.
1333 # They are represented as instances like `~T` when they come here.
1334 # We need to work with their type instead.
1335 if isinstance(thing, TypeVar) and type(thing) in types._global_type_lookup:
1336 strategy = as_strategy(types._global_type_lookup[type(thing)], thing)
1337 if strategy is not NotImplemented:
1338 return strategy
1339 if not types.is_a_type(thing):
1340 if isinstance(thing, str):
1341 # See https://github.com/HypothesisWorks/hypothesis/issues/3016
1342 raise InvalidArgument(
1343 f"Got {thing!r} as a type annotation, but the forward-reference "
1344 "could not be resolved from a string to a type. Consider using "
1345 "`from __future__ import annotations` instead of forward-reference "
1346 "strings."
1347 )
1348 raise InvalidArgument(f"{thing=} must be a type") # pragma: no cover
1349 if thing in types.NON_RUNTIME_TYPES:
1350 # Some code like `st.from_type(TypeAlias)` does not make sense.
1351 # Because there are types in python that do not exist in runtime.
1352 raise InvalidArgument(
1353 f"Could not resolve {thing!r} to a strategy, "
1354 f"because there is no such thing as a runtime instance of {thing!r}"
1355 )
1356 # Now that we know `thing` is a type, the first step is to check for an
1357 # explicitly registered strategy. This is the best (and hopefully most
1358 # common) way to resolve a type to a strategy. Note that the value in the
1359 # lookup may be a strategy or a function from type -> strategy; and we
1360 # convert empty results into an explicit error.
1361 try:
1362 if thing in types._global_type_lookup:
1363 strategy = as_strategy(types._global_type_lookup[thing], thing)
1364 if strategy is not NotImplemented:
1365 return strategy
1366 elif (
1367 isinstance(thing, GenericAlias)
1368 and (to := get_origin(thing)) in types._global_type_lookup
1369 ):
1370 strategy = as_strategy(types._global_type_lookup[to], thing)
1371 if strategy is not NotImplemented:
1372 return strategy
1373 except TypeError: # pragma: no cover
1374 # This was originally due to a bizarre divergence in behaviour on Python 3.9.0:
1375 # typing.Callable[[], foo] has __args__ = (foo,) but collections.abc.Callable
1376 # has __args__ = ([], foo); and as a result is non-hashable.
1377 # We've kept it because we turn out to have more type errors from... somewhere.
1378 # FIXME: investigate that, maybe it should be fixed more precisely?
1379 pass
1380 if (hasattr(typing, "_TypedDictMeta") and type(thing) is typing._TypedDictMeta) or (
1381 hasattr(types.typing_extensions, "_TypedDictMeta") # type: ignore
1382 and type(thing) is types.typing_extensions._TypedDictMeta # type: ignore
1383 ): # pragma: no cover
1384
1385 def _get_annotation_arg(key, annotation_type):
1386 try:
1387 return get_args(annotation_type)[0]
1388 except IndexError:
1389 raise InvalidArgument(
1390 f"`{key}: {annotation_type.__name__}` is not a valid type annotation"
1391 ) from None
1392
1393 # Taken from `Lib/typing.py` and modified:
1394 def _get_typeddict_qualifiers(key, annotation_type):
1395 qualifiers = []
1396 while True:
1397 annotation_origin = types.extended_get_origin(annotation_type)
1398 if annotation_origin is Annotated:
1399 if annotation_args := get_args(annotation_type):
1400 annotation_type = annotation_args[0]
1401 else:
1402 break
1403 elif annotation_origin in types.RequiredTypes:
1404 qualifiers.append(types.RequiredTypes)
1405 annotation_type = _get_annotation_arg(key, annotation_type)
1406 elif annotation_origin in types.NotRequiredTypes:
1407 qualifiers.append(types.NotRequiredTypes)
1408 annotation_type = _get_annotation_arg(key, annotation_type)
1409 elif annotation_origin in types.ReadOnlyTypes:
1410 qualifiers.append(types.ReadOnlyTypes)
1411 annotation_type = _get_annotation_arg(key, annotation_type)
1412 else:
1413 break
1414 return set(qualifiers), annotation_type
1415
1416 # The __optional_keys__ attribute may or may not be present, but if there's no
1417 # way to tell and we just have to assume that everything is required.
1418 # See https://github.com/python/cpython/pull/17214 for details.
1419 optional = set(getattr(thing, "__optional_keys__", ()))
1420 required = set(
1421 getattr(thing, "__required_keys__", get_type_hints(thing).keys())
1422 )
1423 anns = {}
1424 for k, v in get_type_hints(thing).items():
1425 qualifiers, v = _get_typeddict_qualifiers(k, v)
1426 # We ignore `ReadOnly` type for now, only unwrap it.
1427 if types.RequiredTypes in qualifiers:
1428 optional.discard(k)
1429 required.add(k)
1430 if types.NotRequiredTypes in qualifiers:
1431 optional.add(k)
1432 required.discard(k)
1433
1434 anns[k] = from_type_guarded(v)
1435 if anns[k] is ...:
1436 anns[k] = _from_type_deferred(v)
1437
1438 if not required.isdisjoint(optional): # pragma: no cover
1439 # It is impossible to cover, because `typing.py` or `typing-extensions`
1440 # won't allow creating incorrect TypedDicts,
1441 # this is just a sanity check from our side.
1442 raise InvalidArgument(
1443 f"Required keys overlap with optional keys in a TypedDict:"
1444 f" {required=}, {optional=}"
1445 )
1446 if (
1447 (not anns)
1448 and thing.__annotations__
1449 and ".<locals>." in getattr(thing, "__qualname__", "")
1450 ):
1451 raise InvalidArgument("Failed to retrieve type annotations for local type")
1452 return fixed_dictionaries( # type: ignore
1453 mapping={k: v for k, v in anns.items() if k in required},
1454 optional={k: v for k, v in anns.items() if k in optional},
1455 )
1456
1457 # If there's no explicitly registered strategy, maybe a subtype of thing
1458 # is registered - if so, we can resolve it to the subclass strategy.
1459 # We'll start by checking if thing is from from the typing module,
1460 # because there are several special cases that don't play well with
1461 # subclass and instance checks.
1462 if isinstance(thing, types.typing_root_type) or (
1463 isinstance(get_origin(thing), type) and get_args(thing)
1464 ):
1465 return types.from_typing_type(thing)
1466 # If it's not from the typing module, we get all registered types that are
1467 # a subclass of `thing` and are not themselves a subtype of any other such
1468 # type. For example, `Number -> integers() | floats()`, but bools() is
1469 # not included because bool is a subclass of int as well as Number.
1470 strategies = [
1471 s
1472 for s in (
1473 as_strategy(v, thing)
1474 for k, v in sorted(types._global_type_lookup.items(), key=repr)
1475 if isinstance(k, type)
1476 and issubclass(k, thing)
1477 and sum(types.try_issubclass(k, typ) for typ in types._global_type_lookup)
1478 == 1
1479 )
1480 if s is not NotImplemented
1481 ]
1482 if any(not s.is_empty for s in strategies):
1483 return one_of(strategies)
1484 # If we don't have a strategy registered for this type or any subtype, we
1485 # may be able to fall back on type annotations.
1486 if issubclass(thing, enum.Enum):
1487 return sampled_from(thing)
1488 # Finally, try to build an instance by calling the type object. Unlike builds(),
1489 # this block *does* try to infer strategies for arguments with default values.
1490 # That's because of the semantic different; builds() -> "call this with ..."
1491 # so we only infer when *not* doing so would be an error; from_type() -> "give
1492 # me arbitrary instances" so the greater variety is acceptable.
1493 # And if it's *too* varied, express your opinions with register_type_strategy()
1494 if not isabstract(thing):
1495 # If we know that builds(thing) will fail, give a better error message
1496 required = required_args(thing)
1497 if required and not (
1498 required.issubset(get_type_hints(thing))
1499 or attr.has(thing)
1500 or is_typed_named_tuple(thing) # weird enough that we have a specific check
1501 ):
1502 raise ResolutionFailed(
1503 f"Could not resolve {thing!r} to a strategy; consider "
1504 "using register_type_strategy"
1505 )
1506 try:
1507 hints = get_type_hints(thing)
1508 params = get_signature(thing).parameters
1509 except Exception:
1510 params = {} # type: ignore
1511
1512 posonly_args = []
1513 kwargs = {}
1514 for k, p in params.items():
1515 if (
1516 p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY)
1517 and k in hints
1518 and k != "return"
1519 ):
1520 ps = from_type_guarded(hints[k])
1521 if p.default is not Parameter.empty and ps is not ...:
1522 ps = just(p.default) | ps
1523 if p.kind is Parameter.POSITIONAL_ONLY:
1524 # builds() doesn't infer strategies for positional args, so:
1525 if ps is ...: # pragma: no cover # rather fiddly to test
1526 if p.default is Parameter.empty:
1527 raise ResolutionFailed(
1528 f"Could not resolve {thing!r} to a strategy; "
1529 "consider using register_type_strategy"
1530 )
1531 ps = just(p.default)
1532 posonly_args.append(ps)
1533 else:
1534 kwargs[k] = ps
1535 if (
1536 params
1537 and not (posonly_args or kwargs)
1538 and not issubclass(thing, BaseException)
1539 ):
1540 from_type_repr = repr_call(from_type, (thing,), {})
1541 builds_repr = repr_call(builds, (thing,), {})
1542 warnings.warn(
1543 f"{from_type_repr} resolved to {builds_repr}, because we could not "
1544 "find any (non-varargs) arguments. Use st.register_type_strategy() "
1545 "to resolve to a strategy which can generate more than one value, "
1546 "or silence this warning.",
1547 SmallSearchSpaceWarning,
1548 stacklevel=2,
1549 )
1550 return builds(thing, *posonly_args, **kwargs)
1551 # And if it's an abstract type, we'll resolve to a union of subclasses instead.
1552 subclasses = thing.__subclasses__()
1553 if not subclasses:
1554 raise ResolutionFailed(
1555 f"Could not resolve {thing!r} to a strategy, because it is an abstract "
1556 "type without any subclasses. Consider using register_type_strategy"
1557 )
1558 subclass_strategies: SearchStrategy = nothing()
1559 for sc in subclasses:
1560 try:
1561 subclass_strategies |= _from_type(sc)
1562 except Exception:
1563 pass
1564 if subclass_strategies.is_empty:
1565 # We're unable to resolve subclasses now, but we might be able to later -
1566 # so we'll just go back to the mixed distribution.
1567 return sampled_from(subclasses).flatmap(_from_type)
1568 return subclass_strategies
1569
1570
1571@cacheable
1572@defines_strategy(force_reusable_values=True)
1573def fractions(
1574 min_value: Optional[Union[Real, str]] = None,
1575 max_value: Optional[Union[Real, str]] = None,
1576 *,
1577 max_denominator: Optional[int] = None,
1578) -> SearchStrategy[Fraction]:
1579 """Returns a strategy which generates Fractions.
1580
1581 If ``min_value`` is not None then all generated values are no less than
1582 ``min_value``. If ``max_value`` is not None then all generated values are no
1583 greater than ``max_value``. ``min_value`` and ``max_value`` may be anything accepted
1584 by the :class:`~fractions.Fraction` constructor.
1585
1586 If ``max_denominator`` is not None then the denominator of any generated
1587 values is no greater than ``max_denominator``. Note that ``max_denominator`` must
1588 be None or a positive integer.
1589
1590 Examples from this strategy shrink towards smaller denominators, then
1591 closer to zero.
1592 """
1593 min_value = try_convert(Fraction, min_value, "min_value")
1594 max_value = try_convert(Fraction, max_value, "max_value")
1595 # These assertions tell Mypy what happened in try_convert
1596 assert min_value is None or isinstance(min_value, Fraction)
1597 assert max_value is None or isinstance(max_value, Fraction)
1598
1599 check_valid_interval(min_value, max_value, "min_value", "max_value")
1600 check_valid_integer(max_denominator, "max_denominator")
1601
1602 if max_denominator is not None:
1603 if max_denominator < 1:
1604 raise InvalidArgument(f"{max_denominator=} must be >= 1")
1605 if min_value is not None and min_value.denominator > max_denominator:
1606 raise InvalidArgument(
1607 f"The {min_value=} has a denominator greater than the "
1608 f"{max_denominator=}"
1609 )
1610 if max_value is not None and max_value.denominator > max_denominator:
1611 raise InvalidArgument(
1612 f"The {max_value=} has a denominator greater than the "
1613 f"{max_denominator=}"
1614 )
1615
1616 if min_value is not None and min_value == max_value:
1617 return just(min_value)
1618
1619 def dm_func(denom):
1620 """Take denom, construct numerator strategy, and build fraction."""
1621 # Four cases of algebra to get integer bounds and scale factor.
1622 min_num, max_num = None, None
1623 if max_value is None and min_value is None:
1624 pass
1625 elif min_value is None:
1626 max_num = denom * max_value.numerator
1627 denom *= max_value.denominator
1628 elif max_value is None:
1629 min_num = denom * min_value.numerator
1630 denom *= min_value.denominator
1631 else:
1632 low = min_value.numerator * max_value.denominator
1633 high = max_value.numerator * min_value.denominator
1634 scale = min_value.denominator * max_value.denominator
1635 # After calculating our integer bounds and scale factor, we remove
1636 # the gcd to avoid drawing more bytes for the example than needed.
1637 # Note that `div` can be at most equal to `scale`.
1638 div = math.gcd(scale, math.gcd(low, high))
1639 min_num = denom * low // div
1640 max_num = denom * high // div
1641 denom *= scale // div
1642
1643 return builds(
1644 Fraction, integers(min_value=min_num, max_value=max_num), just(denom)
1645 )
1646
1647 if max_denominator is None:
1648 return integers(min_value=1).flatmap(dm_func)
1649
1650 return (
1651 integers(1, max_denominator)
1652 .flatmap(dm_func)
1653 .map(lambda f: f.limit_denominator(max_denominator))
1654 )
1655
1656
1657def _as_finite_decimal(
1658 value: Union[Real, str, None], name: str, allow_infinity: Optional[bool]
1659) -> Optional[Decimal]:
1660 """Convert decimal bounds to decimals, carefully."""
1661 assert name in ("min_value", "max_value")
1662 if value is None:
1663 return None
1664 if not isinstance(value, Decimal):
1665 with localcontext(Context()): # ensure that default traps are enabled
1666 value = try_convert(Decimal, value, name)
1667 assert isinstance(value, Decimal)
1668 if value.is_finite():
1669 return value
1670 if value.is_infinite() and (value < 0 if "min" in name else value > 0):
1671 if allow_infinity or allow_infinity is None:
1672 return None
1673 raise InvalidArgument(f"{allow_infinity=}, but {name}={value!r}")
1674 # This could be infinity, quiet NaN, or signalling NaN
1675 raise InvalidArgument(f"Invalid {name}={value!r}")
1676
1677
1678@cacheable
1679@defines_strategy(force_reusable_values=True)
1680def decimals(
1681 min_value: Optional[Union[Real, str]] = None,
1682 max_value: Optional[Union[Real, str]] = None,
1683 *,
1684 allow_nan: Optional[bool] = None,
1685 allow_infinity: Optional[bool] = None,
1686 places: Optional[int] = None,
1687) -> SearchStrategy[Decimal]:
1688 """Generates instances of :class:`python:decimal.Decimal`, which may be:
1689
1690 - A finite rational number, between ``min_value`` and ``max_value``.
1691 - Not a Number, if ``allow_nan`` is True. None means "allow NaN, unless
1692 ``min_value`` and ``max_value`` are not None".
1693 - Positive or negative infinity, if ``max_value`` and ``min_value``
1694 respectively are None, and ``allow_infinity`` is not False. None means
1695 "allow infinity, unless excluded by the min and max values".
1696
1697 Note that where floats have one ``NaN`` value, Decimals have four: signed,
1698 and either *quiet* or *signalling*. See `the decimal module docs
1699 <https://docs.python.org/3/library/decimal.html#special-values>`_ for
1700 more information on special values.
1701
1702 If ``places`` is not None, all finite values drawn from the strategy will
1703 have that number of digits after the decimal place.
1704
1705 Examples from this strategy do not have a well defined shrink order but
1706 try to maximize human readability when shrinking.
1707 """
1708 # Convert min_value and max_value to Decimal values, and validate args
1709 check_valid_integer(places, "places")
1710 if places is not None and places < 0:
1711 raise InvalidArgument(f"{places=} may not be negative")
1712 min_value = _as_finite_decimal(min_value, "min_value", allow_infinity)
1713 max_value = _as_finite_decimal(max_value, "max_value", allow_infinity)
1714 check_valid_interval(min_value, max_value, "min_value", "max_value")
1715 if allow_infinity and (None not in (min_value, max_value)):
1716 raise InvalidArgument("Cannot allow infinity between finite bounds")
1717 # Set up a strategy for finite decimals. Note that both floating and
1718 # fixed-point decimals require careful handling to remain isolated from
1719 # any external precision context - in short, we always work out the
1720 # required precision for lossless operation and use context methods.
1721 if places is not None:
1722 # Fixed-point decimals are basically integers with a scale factor
1723 def ctx(val):
1724 """Return a context in which this value is lossless."""
1725 precision = ceil(math.log10(abs(val) or 1)) + places + 1
1726 return Context(prec=max([precision, 1]))
1727
1728 def int_to_decimal(val):
1729 context = ctx(val)
1730 return context.quantize(context.multiply(val, factor), factor)
1731
1732 factor = Decimal(10) ** -places
1733 min_num, max_num = None, None
1734 if min_value is not None:
1735 min_num = ceil(ctx(min_value).divide(min_value, factor))
1736 if max_value is not None:
1737 max_num = floor(ctx(max_value).divide(max_value, factor))
1738 if min_num is not None and max_num is not None and min_num > max_num:
1739 raise InvalidArgument(
1740 f"There are no decimals with {places} places between "
1741 f"{min_value=} and {max_value=}"
1742 )
1743 strat = integers(min_num, max_num).map(int_to_decimal)
1744 else:
1745 # Otherwise, they're like fractions featuring a power of ten
1746 def fraction_to_decimal(val):
1747 precision = (
1748 ceil(math.log10(abs(val.numerator) or 1) + math.log10(val.denominator))
1749 + 1
1750 )
1751 return Context(prec=precision or 1).divide(
1752 Decimal(val.numerator), val.denominator
1753 )
1754
1755 strat = fractions(min_value, max_value).map(fraction_to_decimal)
1756 # Compose with sampled_from for infinities and NaNs as appropriate
1757 special: list[Decimal] = []
1758 if allow_nan or (allow_nan is None and (None in (min_value, max_value))):
1759 special.extend(map(Decimal, ("NaN", "-NaN", "sNaN", "-sNaN")))
1760 if allow_infinity or (allow_infinity is None and max_value is None):
1761 special.append(Decimal("Infinity"))
1762 if allow_infinity or (allow_infinity is None and min_value is None):
1763 special.append(Decimal("-Infinity"))
1764 return strat | (sampled_from(special) if special else nothing())
1765
1766
1767@defines_strategy(never_lazy=True)
1768def recursive(
1769 base: SearchStrategy[Ex],
1770 extend: Callable[[SearchStrategy[Any]], SearchStrategy[T]],
1771 *,
1772 max_leaves: int = 100,
1773) -> SearchStrategy[Union[T, Ex]]:
1774 """base: A strategy to start from.
1775
1776 extend: A function which takes a strategy and returns a new strategy.
1777
1778 max_leaves: The maximum number of elements to be drawn from base on a given
1779 run.
1780
1781 This returns a strategy ``S`` such that ``S = extend(base | S)``. That is,
1782 values may be drawn from base, or from any strategy reachable by mixing
1783 applications of | and extend.
1784
1785 An example may clarify: ``recursive(booleans(), lists)`` would return a
1786 strategy that may return arbitrarily nested and mixed lists of booleans.
1787 So e.g. ``False``, ``[True]``, ``[False, []]``, and ``[[[[True]]]]`` are
1788 all valid values to be drawn from that strategy.
1789
1790 Examples from this strategy shrink by trying to reduce the amount of
1791 recursion and by shrinking according to the shrinking behaviour of base
1792 and the result of extend.
1793
1794 """
1795
1796 return RecursiveStrategy(base, extend, max_leaves)
1797
1798
1799class PermutationStrategy(SearchStrategy):
1800 def __init__(self, values):
1801 super().__init__()
1802 self.values = values
1803
1804 def do_draw(self, data):
1805 # Reversed Fisher-Yates shuffle: swap each element with itself or with
1806 # a later element. This shrinks i==j for each element, i.e. to no
1807 # change. We don't consider the last element as it's always a no-op.
1808 result = list(self.values)
1809 for i in range(len(result) - 1):
1810 j = data.draw_integer(i, len(result) - 1)
1811 result[i], result[j] = result[j], result[i]
1812 return result
1813
1814
1815@defines_strategy()
1816def permutations(values: Sequence[T]) -> SearchStrategy[list[T]]:
1817 """Return a strategy which returns permutations of the ordered collection
1818 ``values``.
1819
1820 Examples from this strategy shrink by trying to become closer to the
1821 original order of values.
1822 """
1823 values = check_sample(values, "permutations")
1824 if not values:
1825 return builds(list)
1826
1827 return PermutationStrategy(values)
1828
1829
1830class CompositeStrategy(SearchStrategy):
1831 def __init__(self, definition, args, kwargs):
1832 super().__init__()
1833 self.definition = definition
1834 self.args = args
1835 self.kwargs = kwargs
1836
1837 def do_draw(self, data):
1838 return self.definition(data.draw, *self.args, **self.kwargs)
1839
1840 def calc_label(self) -> int:
1841 return calc_label_from_cls(self.definition)
1842
1843
1844class DrawFn(Protocol):
1845 """This type only exists so that you can write type hints for functions
1846 decorated with :func:`@composite <hypothesis.strategies.composite>`.
1847
1848 .. code-block:: python
1849
1850 def draw(strategy: SearchStrategy[Ex], label: object = None) -> Ex: ...
1851
1852 @composite
1853 def list_and_index(draw: DrawFn) -> tuple[int, str]:
1854 i = draw(integers()) # type of `i` inferred as 'int'
1855 s = draw(text()) # type of `s` inferred as 'str'
1856 return i, s
1857 """
1858
1859 def __init__(self):
1860 raise TypeError("Protocols cannot be instantiated") # pragma: no cover
1861
1862 # Protocol overrides our signature for __init__,
1863 # so we override it right back to make the docs look nice.
1864 __signature__: Signature = Signature(parameters=[])
1865
1866 # We define this as a callback protocol because a simple typing.Callable is
1867 # insufficient to fully represent the interface, due to the optional `label`
1868 # parameter.
1869 def __call__(self, strategy: SearchStrategy[Ex], label: object = None) -> Ex:
1870 raise NotImplementedError
1871
1872
1873def _composite(f):
1874 # Wrapped below, using ParamSpec if available
1875 if isinstance(f, (classmethod, staticmethod)):
1876 special_method = type(f)
1877 f = f.__func__
1878 else:
1879 special_method = None
1880
1881 sig = get_signature(f)
1882 params = tuple(sig.parameters.values())
1883
1884 if not (params and "POSITIONAL" in params[0].kind.name):
1885 raise InvalidArgument(
1886 "Functions wrapped with composite must take at least one "
1887 "positional argument."
1888 )
1889 if params[0].default is not sig.empty:
1890 raise InvalidArgument("A default value for initial argument will never be used")
1891 if not (f is typing._overload_dummy or is_first_param_referenced_in_function(f)):
1892 note_deprecation(
1893 "There is no reason to use @st.composite on a function which "
1894 "does not call the provided draw() function internally.",
1895 since="2022-07-17",
1896 has_codemod=False,
1897 )
1898 if get_origin(sig.return_annotation) is SearchStrategy:
1899 ret_repr = repr(sig.return_annotation).replace("hypothesis.strategies.", "st.")
1900 warnings.warn(
1901 f"Return-type annotation is `{ret_repr}`, but the decorated "
1902 "function should return a value (not a strategy)",
1903 HypothesisWarning,
1904 stacklevel=3 if sys.version_info[:2] > (3, 9) else 5, # ugh
1905 )
1906 if params[0].kind.name != "VAR_POSITIONAL":
1907 params = params[1:]
1908 newsig = sig.replace(
1909 parameters=params,
1910 return_annotation=(
1911 SearchStrategy
1912 if sig.return_annotation is sig.empty
1913 else SearchStrategy[sig.return_annotation]
1914 ),
1915 )
1916
1917 @defines_strategy()
1918 @define_function_signature(f.__name__, f.__doc__, newsig)
1919 def accept(*args, **kwargs):
1920 return CompositeStrategy(f, args, kwargs)
1921
1922 accept.__module__ = f.__module__
1923 accept.__signature__ = newsig
1924 if special_method is not None:
1925 return special_method(accept)
1926 return accept
1927
1928
1929composite_doc = """
1930Defines a strategy that is built out of potentially arbitrarily many other
1931strategies.
1932
1933@composite provides a callable ``draw`` as the first parameter to the decorated
1934function, which can be used to dynamically draw a value from any strategy. For
1935example:
1936
1937.. code-block:: python
1938
1939 from hypothesis import strategies as st, given
1940
1941 @st.composite
1942 def values(draw):
1943 n1 = draw(st.integers())
1944 n2 = draw(st.integers(min_value=n1))
1945 return (n1, n2)
1946
1947 @given(values())
1948 def f(value):
1949 (n1, n2) = value
1950 assert n1 <= n2
1951
1952@composite cannot mix test code and generation code. If you need that, use
1953|st.data|.
1954
1955If :func:`@composite <hypothesis.strategies.composite>` is used to decorate a
1956method or classmethod, the ``draw`` argument must come before ``self`` or
1957``cls``. While we therefore recommend writing strategies as standalone functions
1958and using |st.register_type_strategy| to associate them with a class, methods
1959are supported and the ``@composite`` decorator may be applied either before or
1960after ``@classmethod`` or ``@staticmethod``. See :issue:`2578` and :pull:`2634`
1961for more details.
1962
1963Examples from this strategy shrink by shrinking the output of each draw call.
1964"""
1965if typing.TYPE_CHECKING or ParamSpec is not None:
1966 P = ParamSpec("P")
1967
1968 def composite(
1969 f: Callable[Concatenate[DrawFn, P], Ex],
1970 ) -> Callable[P, SearchStrategy[Ex]]:
1971 return _composite(f)
1972
1973else: # pragma: no cover
1974
1975 @cacheable
1976 def composite(f: Callable[..., Ex]) -> Callable[..., SearchStrategy[Ex]]:
1977 return _composite(f)
1978
1979
1980composite.__doc__ = composite_doc
1981
1982
1983@defines_strategy(force_reusable_values=True)
1984@cacheable
1985def complex_numbers(
1986 *,
1987 min_magnitude: Real = 0,
1988 max_magnitude: Optional[Real] = None,
1989 allow_infinity: Optional[bool] = None,
1990 allow_nan: Optional[bool] = None,
1991 allow_subnormal: bool = True,
1992 width: Literal[32, 64, 128] = 128,
1993) -> SearchStrategy[complex]:
1994 """Returns a strategy that generates :class:`~python:complex`
1995 numbers.
1996
1997 This strategy draws complex numbers with constrained magnitudes.
1998 The ``min_magnitude`` and ``max_magnitude`` parameters should be
1999 non-negative :class:`~python:numbers.Real` numbers; a value
2000 of ``None`` corresponds an infinite upper bound.
2001
2002 If ``min_magnitude`` is nonzero or ``max_magnitude`` is finite, it
2003 is an error to enable ``allow_nan``. If ``max_magnitude`` is finite,
2004 it is an error to enable ``allow_infinity``.
2005
2006 ``allow_infinity``, ``allow_nan``, and ``allow_subnormal`` are
2007 applied to each part of the complex number separately, as for
2008 :func:`~hypothesis.strategies.floats`.
2009
2010 The magnitude constraints are respected up to a relative error
2011 of (around) floating-point epsilon, due to implementation via
2012 the system ``sqrt`` function.
2013
2014 The ``width`` argument specifies the maximum number of bits of precision
2015 required to represent the entire generated complex number.
2016 Valid values are 32, 64 or 128, which correspond to the real and imaginary
2017 components each having width 16, 32 or 64, respectively.
2018 Passing ``width=64`` will still use the builtin 128-bit
2019 :class:`~python:complex` class, but always for values which can be
2020 exactly represented as two 32-bit floats.
2021
2022 Examples from this strategy shrink by shrinking their real and
2023 imaginary parts, as :func:`~hypothesis.strategies.floats`.
2024
2025 If you need to generate complex numbers with particular real and
2026 imaginary parts or relationships between parts, consider using
2027 :func:`builds(complex, ...) <hypothesis.strategies.builds>` or
2028 :func:`@composite <hypothesis.strategies.composite>` respectively.
2029 """
2030 check_valid_magnitude(min_magnitude, "min_magnitude")
2031 check_valid_magnitude(max_magnitude, "max_magnitude")
2032 check_valid_interval(min_magnitude, max_magnitude, "min_magnitude", "max_magnitude")
2033 if max_magnitude == math.inf:
2034 max_magnitude = None
2035
2036 if allow_infinity is None:
2037 allow_infinity = bool(max_magnitude is None)
2038 elif allow_infinity and max_magnitude is not None:
2039 raise InvalidArgument(f"Cannot have {allow_infinity=} with {max_magnitude=}")
2040 if allow_nan is None:
2041 allow_nan = bool(min_magnitude == 0 and max_magnitude is None)
2042 elif allow_nan and not (min_magnitude == 0 and max_magnitude is None):
2043 raise InvalidArgument(
2044 f"Cannot have {allow_nan=}, {min_magnitude=}, {max_magnitude=}"
2045 )
2046 check_type(bool, allow_subnormal, "allow_subnormal")
2047 if width not in (32, 64, 128):
2048 raise InvalidArgument(
2049 f"{width=}, but must be 32, 64 or 128 (other complex dtypes "
2050 "such as complex192 or complex256 are not supported)"
2051 # For numpy, these types would be supported (but not by CPython):
2052 # https://numpy.org/doc/stable/reference/arrays.scalars.html#complex-floating-point-types
2053 )
2054 component_width = width // 2
2055 allow_kw = {
2056 "allow_nan": allow_nan,
2057 "allow_infinity": allow_infinity,
2058 # If we have a nonzero normal min_magnitude and draw a zero imaginary part,
2059 # then allow_subnormal=True would be an error with the min_value to the floats()
2060 # strategy for the real part. We therefore replace True with None.
2061 "allow_subnormal": None if allow_subnormal else allow_subnormal,
2062 "width": component_width,
2063 }
2064
2065 if min_magnitude == 0 and max_magnitude is None:
2066 # In this simple but common case, there are no constraints on the
2067 # magnitude and therefore no relationship between the real and
2068 # imaginary parts.
2069 return builds(complex, floats(**allow_kw), floats(**allow_kw)) # type: ignore
2070
2071 @composite
2072 def constrained_complex(draw):
2073 # We downcast drawn floats to the desired (component) width so we
2074 # guarantee the resulting complex values are representable. Note
2075 # truncating the mantissa bits with float_of() cannot increase the
2076 # magnitude of a float, so we are guaranteed to stay within the allowed
2077 # range. See https://github.com/HypothesisWorks/hypothesis/issues/3573
2078
2079 # Draw the imaginary part, and determine the maximum real part given
2080 # this and the max_magnitude
2081 if max_magnitude is None:
2082 zi = draw(floats(**allow_kw))
2083 rmax = None
2084 else:
2085 zi = draw(
2086 floats(
2087 -float_of(max_magnitude, component_width),
2088 float_of(max_magnitude, component_width),
2089 **allow_kw,
2090 )
2091 )
2092 rmax = float_of(cathetus(max_magnitude, zi), component_width)
2093 # Draw the real part from the allowed range given the imaginary part
2094 if min_magnitude == 0 or math.fabs(zi) >= min_magnitude:
2095 zr = draw(floats(None if rmax is None else -rmax, rmax, **allow_kw))
2096 else:
2097 rmin = float_of(cathetus(min_magnitude, zi), component_width)
2098 zr = draw(floats(rmin, rmax, **allow_kw))
2099 # Order of conditions carefully tuned so that for a given pair of
2100 # magnitude arguments, we always either draw or do not draw the bool
2101 # (crucial for good shrinking behaviour) but only invert when needed.
2102 if min_magnitude > 0 and draw(booleans()) and math.fabs(zi) <= min_magnitude:
2103 zr = -zr
2104 return complex(zr, zi)
2105
2106 return constrained_complex()
2107
2108
2109@defines_strategy(never_lazy=True)
2110def shared(
2111 base: SearchStrategy[Ex],
2112 *,
2113 key: Optional[Hashable] = None,
2114) -> SearchStrategy[Ex]:
2115 """Returns a strategy that draws a single shared value per run, drawn from
2116 base. Any two shared instances with the same key will share the same value,
2117 otherwise the identity of this strategy will be used. That is:
2118
2119 >>> s = integers() # or any other strategy
2120 >>> x = shared(s)
2121 >>> y = shared(s)
2122
2123 In the above x and y may draw different (or potentially the same) values.
2124 In the following they will always draw the same:
2125
2126 >>> x = shared(s, key="hi")
2127 >>> y = shared(s, key="hi")
2128
2129 Examples from this strategy shrink as per their base strategy.
2130 """
2131 return SharedStrategy(base, key)
2132
2133
2134@composite
2135def _maybe_nil_uuids(draw, uuid):
2136 # Equivalent to `random_uuids | just(...)`, with a stronger bias to the former.
2137 if draw(data()).conjecture_data.draw_boolean(1 / 64):
2138 return UUID("00000000-0000-0000-0000-000000000000")
2139 return uuid
2140
2141
2142@cacheable
2143@defines_strategy(force_reusable_values=True)
2144def uuids(
2145 *, version: Optional[Literal[1, 2, 3, 4, 5]] = None, allow_nil: bool = False
2146) -> SearchStrategy[UUID]:
2147 """Returns a strategy that generates :class:`UUIDs <uuid.UUID>`.
2148
2149 If the optional version argument is given, value is passed through
2150 to :class:`~python:uuid.UUID` and only UUIDs of that version will
2151 be generated.
2152
2153 If ``allow_nil`` is True, generate the nil UUID much more often.
2154 Otherwise, all returned values from this will be unique, so e.g. if you do
2155 ``lists(uuids())`` the resulting list will never contain duplicates.
2156
2157 Examples from this strategy don't have any meaningful shrink order.
2158 """
2159 check_type(bool, allow_nil, "allow_nil")
2160 if version not in (None, 1, 2, 3, 4, 5):
2161 raise InvalidArgument(
2162 f"{version=}, but version must be in "
2163 "(None, 1, 2, 3, 4, 5) to pass to the uuid.UUID constructor."
2164 )
2165 random_uuids = shared(
2166 randoms(use_true_random=True), key="hypothesis.strategies.uuids.generator"
2167 ).map(lambda r: UUID(version=version, int=r.getrandbits(128)))
2168
2169 if allow_nil:
2170 if version is not None:
2171 raise InvalidArgument("The nil UUID is not of any version")
2172 return random_uuids.flatmap(_maybe_nil_uuids)
2173 return random_uuids
2174
2175
2176class RunnerStrategy(SearchStrategy):
2177 def __init__(self, default):
2178 super().__init__()
2179 self.default = default
2180
2181 def do_draw(self, data):
2182 if data.hypothesis_runner is not_set:
2183 if self.default is not_set:
2184 raise InvalidArgument(
2185 "Cannot use runner() strategy with no "
2186 "associated runner or explicit default."
2187 )
2188 return self.default
2189 return data.hypothesis_runner
2190
2191
2192@defines_strategy(force_reusable_values=True)
2193def runner(*, default: Any = not_set) -> SearchStrategy[Any]:
2194 """A strategy for getting "the current test runner", whatever that may be.
2195 The exact meaning depends on the entry point, but it will usually be the
2196 associated 'self' value for it.
2197
2198 If you are using this in a rule for stateful testing, this strategy
2199 will return the instance of the :class:`~hypothesis.stateful.RuleBasedStateMachine`
2200 that the rule is running for.
2201
2202 If there is no current test runner and a default is provided, return
2203 that default. If no default is provided, raises InvalidArgument.
2204
2205 Examples from this strategy do not shrink (because there is only one).
2206 """
2207 return RunnerStrategy(default)
2208
2209
2210class DataObject:
2211 """This type only exists so that you can write type hints for tests using
2212 the :func:`~hypothesis.strategies.data` strategy. Do not use it directly!
2213 """
2214
2215 # Note that "only exists" here really means "is only exported to users",
2216 # but we want to treat it as "semi-stable", not document it as "public API".
2217
2218 def __init__(self, data: ConjectureData) -> None:
2219 self.count = 0
2220 self.conjecture_data = data
2221
2222 __signature__ = Signature() # hide internals from Sphinx introspection
2223
2224 def __repr__(self) -> str:
2225 return "data(...)"
2226
2227 def draw(self, strategy: SearchStrategy[Ex], label: Any = None) -> Ex:
2228 """Like :obj:`~hypothesis.strategies.DrawFn`."""
2229 check_strategy(strategy, "strategy")
2230 self.count += 1
2231 desc = f"Draw {self.count}{'' if label is None else f' ({label})'}"
2232 with deprecate_random_in_strategy("{}from {!r}", desc, strategy):
2233 result = self.conjecture_data.draw(strategy, observe_as=f"generate:{desc}")
2234
2235 # optimization to avoid needless printer.pretty
2236 if should_note():
2237 printer = RepresentationPrinter(context=current_build_context())
2238 printer.text(f"{desc}: ")
2239 if self.conjecture_data.provider.avoid_realization:
2240 printer.text("<symbolic>")
2241 else:
2242 printer.pretty(result)
2243 note(printer.getvalue())
2244 return result
2245
2246
2247class DataStrategy(SearchStrategy):
2248 supports_find = False
2249
2250 def do_draw(self, data):
2251 if not hasattr(data, "hypothesis_shared_data_strategy"):
2252 data.hypothesis_shared_data_strategy = DataObject(data)
2253 return data.hypothesis_shared_data_strategy
2254
2255 def __repr__(self) -> str:
2256 return "data()"
2257
2258 def map(self, f):
2259 self.__not_a_first_class_strategy("map")
2260
2261 def filter(self, condition: Callable[[Ex], Any]) -> NoReturn:
2262 self.__not_a_first_class_strategy("filter")
2263
2264 def flatmap(self, f):
2265 self.__not_a_first_class_strategy("flatmap")
2266
2267 def example(self) -> NoReturn:
2268 self.__not_a_first_class_strategy("example")
2269
2270 def __not_a_first_class_strategy(self, name: str) -> NoReturn:
2271 raise InvalidArgument(
2272 f"Cannot call {name} on a DataStrategy. You should probably "
2273 "be using @composite for whatever it is you're trying to do."
2274 )
2275
2276
2277@cacheable
2278@defines_strategy(never_lazy=True)
2279def data() -> SearchStrategy[DataObject]:
2280 """
2281 Provides an object ``data`` with a ``data.draw`` function which acts like
2282 the ``draw`` callable provided by |st.composite|, in that it can be used
2283 to dynamically draw values from strategies. |st.data| is more powerful
2284 than |st.composite|, because it allows you to mix generation and test code.
2285
2286 Here's an example of dynamically generating values using |st.data|:
2287
2288 .. code-block:: python
2289
2290 from hypothesis import strategies as st, given
2291
2292 @given(st.data())
2293 def test_values(data):
2294 n1 = data.draw(st.integers())
2295 n2 = data.draw(st.integers(min_value=n1))
2296 assert n1 + 1 <= n2
2297
2298 If the test fails, each draw will be printed with the falsifying example.
2299 e.g. the above is wrong (it has a boundary condition error), so will print:
2300
2301 .. code-block:: pycon
2302
2303 Falsifying example: test_values(data=data(...))
2304 Draw 1: 0
2305 Draw 2: 0
2306
2307 Optionally, you can provide a label to identify values generated by each call
2308 to ``data.draw()``. These labels can be used to identify values in the
2309 output of a falsifying example.
2310
2311 For instance:
2312
2313 .. code-block:: python
2314
2315 @given(st.data())
2316 def test_draw_sequentially(data):
2317 x = data.draw(st.integers(), label="First number")
2318 y = data.draw(st.integers(min_value=x), label="Second number")
2319 assert x < y
2320
2321 will produce:
2322
2323 .. code-block:: pycon
2324
2325 Falsifying example: test_draw_sequentially(data=data(...))
2326 Draw 1 (First number): 0
2327 Draw 2 (Second number): 0
2328
2329 Examples from this strategy shrink by shrinking the output of each draw call.
2330 """
2331 return DataStrategy()
2332
2333
2334def register_type_strategy(
2335 custom_type: type[Ex],
2336 strategy: Union[SearchStrategy[Ex], Callable[[type[Ex]], SearchStrategy[Ex]]],
2337) -> None:
2338 """Add an entry to the global type-to-strategy lookup.
2339
2340 This lookup is used in :func:`~hypothesis.strategies.builds` and
2341 |@given|.
2342
2343 :func:`~hypothesis.strategies.builds` will be used automatically for
2344 classes with type annotations on ``__init__`` , so you only need to
2345 register a strategy if one or more arguments need to be more tightly
2346 defined than their type-based default, or if you want to supply a strategy
2347 for an argument with a default value.
2348
2349 ``strategy`` may be a search strategy, or a function that takes a type and
2350 returns a strategy (useful for generic types). The function may return
2351 :data:`NotImplemented` to conditionally not provide a strategy for the type
2352 (the type will still be resolved by other methods, if possible, as if the
2353 function was not registered).
2354
2355 Note that you may not register a parametrised generic type (such as
2356 ``MyCollection[int]``) directly, because the resolution logic does not
2357 handle this case correctly. Instead, you may register a *function* for
2358 ``MyCollection`` and `inspect the type parameters within that function
2359 <https://stackoverflow.com/q/48572831>`__.
2360 """
2361 # TODO: We would like to move this to the top level, but pending some major
2362 # refactoring it's hard to do without creating circular imports.
2363 from hypothesis.strategies._internal import types
2364
2365 if not types.is_a_type(custom_type):
2366 raise InvalidArgument(f"{custom_type=} must be a type")
2367 if custom_type in types.NON_RUNTIME_TYPES:
2368 raise InvalidArgument(
2369 f"{custom_type=} is not allowed to be registered, "
2370 f"because there is no such thing as a runtime instance of {custom_type!r}"
2371 )
2372 if not (isinstance(strategy, SearchStrategy) or callable(strategy)):
2373 raise InvalidArgument(
2374 f"{strategy=} must be a SearchStrategy, or a function that takes "
2375 "a generic type and returns a specific SearchStrategy"
2376 )
2377 if isinstance(strategy, SearchStrategy):
2378 with warnings.catch_warnings():
2379 warnings.simplefilter("error", HypothesisSideeffectWarning)
2380
2381 # Calling is_empty forces materialization of lazy strategies. If this is done at import
2382 # time, lazy strategies will warn about it; here, we force that warning to raise to
2383 # avoid the materialization. Ideally, we'd just check if the strategy is lazy, but the
2384 # lazy strategy may be wrapped underneath another strategy so that's complicated.
2385 try:
2386 if strategy.is_empty:
2387 raise InvalidArgument(f"{strategy=} must not be empty")
2388 except HypothesisSideeffectWarning: # pragma: no cover
2389 pass
2390 if types.has_type_arguments(custom_type):
2391 raise InvalidArgument(
2392 f"Cannot register generic type {custom_type!r}, because it has type "
2393 "arguments which would not be handled. Instead, register a function "
2394 f"for {get_origin(custom_type)!r} which can inspect specific type "
2395 "objects and return a strategy."
2396 )
2397 if (
2398 "pydantic.generics" in sys.modules
2399 and issubclass(custom_type, sys.modules["pydantic.generics"].GenericModel)
2400 and not re.search(r"[A-Za-z_]+\[.+\]", repr(custom_type))
2401 and callable(strategy)
2402 ): # pragma: no cover
2403 # See https://github.com/HypothesisWorks/hypothesis/issues/2940
2404 raise InvalidArgument(
2405 f"Cannot register a function for {custom_type!r}, because parametrized "
2406 "`pydantic.generics.GenericModel` subclasses aren't actually generic "
2407 "types at runtime. In this case, you should register a strategy "
2408 "directly for each parametrized form that you anticipate using."
2409 )
2410
2411 types._global_type_lookup[custom_type] = strategy
2412 from_type.__clear_cache() # type: ignore
2413
2414
2415@cacheable
2416@defines_strategy(never_lazy=True)
2417def deferred(definition: Callable[[], SearchStrategy[Ex]]) -> SearchStrategy[Ex]:
2418 """A deferred strategy allows you to write a strategy that references other
2419 strategies that have not yet been defined. This allows for the easy
2420 definition of recursive and mutually recursive strategies.
2421
2422 The definition argument should be a zero-argument function that returns a
2423 strategy. It will be evaluated the first time the strategy is used to
2424 produce an example.
2425
2426 Example usage:
2427
2428 >>> import hypothesis.strategies as st
2429 >>> x = st.deferred(lambda: st.booleans() | st.tuples(x, x))
2430 >>> x.example()
2431 (((False, (True, True)), (False, True)), (True, True))
2432 >>> x.example()
2433 True
2434
2435 Mutual recursion also works fine:
2436
2437 >>> a = st.deferred(lambda: st.booleans() | b)
2438 >>> b = st.deferred(lambda: st.tuples(a, a))
2439 >>> a.example()
2440 True
2441 >>> b.example()
2442 (False, (False, ((False, True), False)))
2443
2444 Examples from this strategy shrink as they normally would from the strategy
2445 returned by the definition.
2446 """
2447 return DeferredStrategy(definition)
2448
2449
2450def domains() -> SearchStrategy[str]:
2451 import hypothesis.provisional
2452
2453 return hypothesis.provisional.domains()
2454
2455
2456@defines_strategy(force_reusable_values=True)
2457def emails(
2458 *, domains: SearchStrategy[str] = LazyStrategy(domains, (), {})
2459) -> SearchStrategy[str]:
2460 """A strategy for generating email addresses as unicode strings. The
2461 address format is specified in :rfc:`5322#section-3.4.1`. Values shrink
2462 towards shorter local-parts and host domains.
2463
2464 If ``domains`` is given then it must be a strategy that generates domain
2465 names for the emails, defaulting to :func:`~hypothesis.provisional.domains`.
2466
2467 This strategy is useful for generating "user data" for tests, as
2468 mishandling of email addresses is a common source of bugs.
2469 """
2470 local_chars = string.ascii_letters + string.digits + "!#$%&'*+-/=^_`{|}~"
2471 local_part = text(local_chars, min_size=1, max_size=64)
2472 # TODO: include dot-atoms, quoted strings, escaped chars, etc in local part
2473 return builds("{}@{}".format, local_part, domains).filter(
2474 lambda addr: len(addr) <= 254
2475 )
2476
2477
2478def _functions(*, like, returns, pure):
2479 # Wrapped up to use ParamSpec below
2480 check_type(bool, pure, "pure")
2481 if not callable(like):
2482 raise InvalidArgument(
2483 "The first argument to functions() must be a callable to imitate, "
2484 f"but got non-callable like={nicerepr(like)!r}"
2485 )
2486 if returns in (None, ...):
2487 # Passing `None` has never been *documented* as working, but it still
2488 # did from May 2020 to Jan 2022 so we'll avoid breaking it without cause.
2489 hints = get_type_hints(like)
2490 returns = from_type(hints.get("return", type(None)))
2491 check_strategy(returns, "returns")
2492 return FunctionStrategy(like, returns, pure)
2493
2494
2495if typing.TYPE_CHECKING or ParamSpec is not None:
2496
2497 @overload
2498 def functions(
2499 *, pure: bool = ...
2500 ) -> SearchStrategy[Callable[[], None]]: # pragma: no cover
2501 ...
2502
2503 @overload
2504 def functions(
2505 *,
2506 like: Callable[P, T],
2507 pure: bool = ...,
2508 ) -> SearchStrategy[Callable[P, T]]: # pragma: no cover
2509 ...
2510
2511 @overload
2512 def functions(
2513 *,
2514 returns: SearchStrategy[T],
2515 pure: bool = ...,
2516 ) -> SearchStrategy[Callable[[], T]]: # pragma: no cover
2517 ...
2518
2519 @overload
2520 def functions(
2521 *,
2522 like: Callable[P, Any],
2523 returns: SearchStrategy[T],
2524 pure: bool = ...,
2525 ) -> SearchStrategy[Callable[P, T]]: # pragma: no cover
2526 ...
2527
2528 @defines_strategy()
2529 def functions(*, like=lambda: None, returns=..., pure=False):
2530 # We shouldn't need overloads here, but mypy disallows default args for
2531 # generics: https://github.com/python/mypy/issues/3737
2532 """functions(*, like=lambda: None, returns=..., pure=False)
2533
2534 A strategy for functions, which can be used in callbacks.
2535
2536 The generated functions will mimic the interface of ``like``, which must
2537 be a callable (including a class, method, or function). The return value
2538 for the function is drawn from the ``returns`` argument, which must be a
2539 strategy. If ``returns`` is not passed, we attempt to infer a strategy
2540 from the return-type annotation if present, falling back to :func:`~none`.
2541
2542 If ``pure=True``, all arguments passed to the generated function must be
2543 hashable, and if passed identical arguments the original return value will
2544 be returned again - *not* regenerated, so beware mutable values.
2545
2546 If ``pure=False``, generated functions do not validate their arguments, and
2547 may return a different value if called again with the same arguments.
2548
2549 Generated functions can only be called within the scope of the ``@given``
2550 which created them. This strategy does not support ``.example()``.
2551 """
2552 return _functions(like=like, returns=returns, pure=pure)
2553
2554else: # pragma: no cover
2555
2556 @defines_strategy()
2557 def functions(
2558 *,
2559 like: Callable[..., Any] = lambda: None,
2560 returns: Union[SearchStrategy[Any], EllipsisType] = ...,
2561 pure: bool = False,
2562 ) -> SearchStrategy[Callable[..., Any]]:
2563 """functions(*, like=lambda: None, returns=..., pure=False)
2564
2565 A strategy for functions, which can be used in callbacks.
2566
2567 The generated functions will mimic the interface of ``like``, which must
2568 be a callable (including a class, method, or function). The return value
2569 for the function is drawn from the ``returns`` argument, which must be a
2570 strategy. If ``returns`` is not passed, we attempt to infer a strategy
2571 from the return-type annotation if present, falling back to :func:`~none`.
2572
2573 If ``pure=True``, all arguments passed to the generated function must be
2574 hashable, and if passed identical arguments the original return value will
2575 be returned again - *not* regenerated, so beware mutable values.
2576
2577 If ``pure=False``, generated functions do not validate their arguments, and
2578 may return a different value if called again with the same arguments.
2579
2580 Generated functions can only be called within the scope of the ``@given``
2581 which created them. This strategy does not support ``.example()``.
2582 """
2583 return _functions(like=like, returns=returns, pure=pure)
2584
2585
2586@composite
2587def slices(draw: Any, size: int) -> slice:
2588 """Generates slices that will select indices up to the supplied size
2589
2590 Generated slices will have start and stop indices that range from -size to size - 1
2591 and will step in the appropriate direction. Slices should only produce an empty selection
2592 if the start and end are the same.
2593
2594 Examples from this strategy shrink toward 0 and smaller values
2595 """
2596 check_valid_size(size, "size")
2597 if size == 0:
2598 step = draw(none() | integers().filter(bool))
2599 return slice(None, None, step)
2600 # For slices start is inclusive and stop is exclusive
2601 start = draw(integers(0, size - 1) | none())
2602 stop = draw(integers(0, size) | none())
2603
2604 # Limit step size to be reasonable
2605 if start is None and stop is None:
2606 max_step = size
2607 elif start is None:
2608 max_step = stop
2609 elif stop is None:
2610 max_step = start
2611 else:
2612 max_step = abs(start - stop)
2613
2614 step = draw(integers(1, max_step or 1))
2615
2616 if (draw(booleans()) and start == stop) or (stop or 0) < (start or 0):
2617 step *= -1
2618
2619 if draw(booleans()) and start is not None:
2620 start -= size
2621 if draw(booleans()) and stop is not None:
2622 stop -= size
2623 if (not draw(booleans())) and step == 1:
2624 step = None
2625
2626 return slice(start, stop, step)