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