strategies.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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. import sys
  11. import warnings
  12. from collections import abc, defaultdict
  13. from functools import lru_cache
  14. from random import shuffle
  15. from typing import (
  16. TYPE_CHECKING,
  17. Any,
  18. Callable,
  19. ClassVar,
  20. Dict,
  21. Generic,
  22. List,
  23. Sequence,
  24. TypeVar,
  25. Union,
  26. cast,
  27. overload,
  28. )
  29. from hypothesis._settings import HealthCheck, Phase, Verbosity, settings
  30. from hypothesis.control import _current_build_context
  31. from hypothesis.errors import (
  32. HypothesisException,
  33. HypothesisWarning,
  34. InvalidArgument,
  35. NonInteractiveExampleWarning,
  36. UnsatisfiedAssumption,
  37. )
  38. from hypothesis.internal.conjecture import utils as cu
  39. from hypothesis.internal.conjecture.data import ConjectureData
  40. from hypothesis.internal.conjecture.utils import (
  41. calc_label_from_cls,
  42. calc_label_from_name,
  43. combine_labels,
  44. )
  45. from hypothesis.internal.coverage import check_function
  46. from hypothesis.internal.reflection import (
  47. get_pretty_function_description,
  48. is_identity_function,
  49. )
  50. from hypothesis.strategies._internal.utils import defines_strategy
  51. from hypothesis.utils.conventions import UniqueIdentifier
  52. if sys.version_info >= (3, 13):
  53. Ex = TypeVar("Ex", covariant=True, default=Any)
  54. elif TYPE_CHECKING:
  55. from typing_extensions import TypeVar # type: ignore[assignment]
  56. Ex = TypeVar("Ex", covariant=True, default=Any)
  57. else:
  58. Ex = TypeVar("Ex", covariant=True)
  59. Ex_Inv = TypeVar("Ex_Inv")
  60. T = TypeVar("T")
  61. T3 = TypeVar("T3")
  62. T4 = TypeVar("T4")
  63. T5 = TypeVar("T5")
  64. calculating = UniqueIdentifier("calculating")
  65. MAPPED_SEARCH_STRATEGY_DO_DRAW_LABEL = calc_label_from_name(
  66. "another attempted draw in MappedStrategy"
  67. )
  68. FILTERED_SEARCH_STRATEGY_DO_DRAW_LABEL = calc_label_from_name(
  69. "single loop iteration in FilteredStrategy"
  70. )
  71. def recursive_property(name, default):
  72. """Handle properties which may be mutually recursive among a set of
  73. strategies.
  74. These are essentially lazily cached properties, with the ability to set
  75. an override: If the property has not been explicitly set, we calculate
  76. it on first access and memoize the result for later.
  77. The problem is that for properties that depend on each other, a naive
  78. calculation strategy may hit infinite recursion. Consider for example
  79. the property is_empty. A strategy defined as x = st.deferred(lambda: x)
  80. is certainly empty (in order to draw a value from x we would have to
  81. draw a value from x, for which we would have to draw a value from x,
  82. ...), but in order to calculate it the naive approach would end up
  83. calling x.is_empty in order to calculate x.is_empty in order to etc.
  84. The solution is one of fixed point calculation. We start with a default
  85. value that is the value of the property in the absence of evidence to
  86. the contrary, and then update the values of the property for all
  87. dependent strategies until we reach a fixed point.
  88. The approach taken roughly follows that in section 4.2 of Adams,
  89. Michael D., Celeste Hollenbeck, and Matthew Might. "On the complexity
  90. and performance of parsing with derivatives." ACM SIGPLAN Notices 51.6
  91. (2016): 224-236.
  92. """
  93. cache_key = "cached_" + name
  94. calculation = "calc_" + name
  95. force_key = "force_" + name
  96. def forced_value(target):
  97. try:
  98. return getattr(target, force_key)
  99. except AttributeError:
  100. return getattr(target, cache_key)
  101. def accept(self):
  102. try:
  103. return forced_value(self)
  104. except AttributeError:
  105. pass
  106. mapping = {}
  107. sentinel = object()
  108. hit_recursion = [False]
  109. # For a first pass we do a direct recursive calculation of the
  110. # property, but we block recursively visiting a value in the
  111. # computation of its property: When that happens, we simply
  112. # note that it happened and return the default value.
  113. def recur(strat):
  114. try:
  115. return forced_value(strat)
  116. except AttributeError:
  117. pass
  118. result = mapping.get(strat, sentinel)
  119. if result is calculating:
  120. hit_recursion[0] = True
  121. return default
  122. elif result is sentinel:
  123. mapping[strat] = calculating
  124. mapping[strat] = getattr(strat, calculation)(recur)
  125. return mapping[strat]
  126. return result
  127. recur(self)
  128. # If we hit self-recursion in the computation of any strategy
  129. # value, our mapping at the end is imprecise - it may or may
  130. # not have the right values in it. We now need to proceed with
  131. # a more careful fixed point calculation to get the exact
  132. # values. Hopefully our mapping is still pretty good and it
  133. # won't take a large number of updates to reach a fixed point.
  134. if hit_recursion[0]:
  135. needs_update = set(mapping)
  136. # We track which strategies use which in the course of
  137. # calculating their property value. If A ever uses B in
  138. # the course of calculating its value, then whenever the
  139. # value of B changes we might need to update the value of
  140. # A.
  141. listeners = defaultdict(set)
  142. else:
  143. needs_update = None
  144. def recur2(strat):
  145. def recur_inner(other):
  146. try:
  147. return forced_value(other)
  148. except AttributeError:
  149. pass
  150. listeners[other].add(strat)
  151. result = mapping.get(other, sentinel)
  152. if result is sentinel:
  153. needs_update.add(other)
  154. mapping[other] = default
  155. return default
  156. return result
  157. return recur_inner
  158. count = 0
  159. seen = set()
  160. while needs_update:
  161. count += 1
  162. # If we seem to be taking a really long time to stabilize we
  163. # start tracking seen values to attempt to detect an infinite
  164. # loop. This should be impossible, and most code will never
  165. # hit the count, but having an assertion for it means that
  166. # testing is easier to debug and we don't just have a hung
  167. # test.
  168. # Note: This is actually covered, by test_very_deep_deferral
  169. # in tests/cover/test_deferred_strategies.py. Unfortunately it
  170. # runs into a coverage bug. See
  171. # https://github.com/nedbat/coveragepy/issues/605
  172. # for details.
  173. if count > 50: # pragma: no cover
  174. key = frozenset(mapping.items())
  175. assert key not in seen, (key, name)
  176. seen.add(key)
  177. to_update = needs_update
  178. needs_update = set()
  179. for strat in to_update:
  180. new_value = getattr(strat, calculation)(recur2(strat))
  181. if new_value != mapping[strat]:
  182. needs_update.update(listeners[strat])
  183. mapping[strat] = new_value
  184. # We now have a complete and accurate calculation of the
  185. # property values for everything we have seen in the course of
  186. # running this calculation. We simultaneously update all of
  187. # them (not just the strategy we started out with).
  188. for k, v in mapping.items():
  189. setattr(k, cache_key, v)
  190. return getattr(self, cache_key)
  191. accept.__name__ = name
  192. return property(accept)
  193. class SearchStrategy(Generic[Ex]):
  194. """A SearchStrategy is an object that knows how to explore data of a given
  195. type.
  196. Except where noted otherwise, methods on this class are not part of
  197. the public API and their behaviour may change significantly between
  198. minor version releases. They will generally be stable between patch
  199. releases.
  200. """
  201. supports_find = True
  202. validate_called = False
  203. __label = None
  204. __module__ = "hypothesis.strategies"
  205. def available(self, data):
  206. """Returns whether this strategy can *currently* draw any
  207. values. This typically useful for stateful testing where ``Bundle``
  208. grows over time a list of value to choose from.
  209. Unlike ``empty`` property, this method's return value may change
  210. over time.
  211. Note: ``data`` parameter will only be used for introspection and no
  212. value drawn from it.
  213. """
  214. return not self.is_empty
  215. # Returns True if this strategy can never draw a value and will always
  216. # result in the data being marked invalid.
  217. # The fact that this returns False does not guarantee that a valid value
  218. # can be drawn - this is not intended to be perfect, and is primarily
  219. # intended to be an optimisation for some cases.
  220. is_empty = recursive_property("is_empty", True)
  221. # Returns True if values from this strategy can safely be reused without
  222. # this causing unexpected behaviour.
  223. # True if values from this strategy can be implicitly reused (e.g. as
  224. # background values in a numpy array) without causing surprising
  225. # user-visible behaviour. Should be false for built-in strategies that
  226. # produce mutable values, and for strategies that have been mapped/filtered
  227. # by arbitrary user-provided functions.
  228. has_reusable_values = recursive_property("has_reusable_values", True)
  229. # Whether this strategy is suitable for holding onto in a cache.
  230. is_cacheable = recursive_property("is_cacheable", True)
  231. def calc_is_cacheable(self, recur):
  232. return True
  233. def calc_is_empty(self, recur):
  234. # Note: It is correct and significant that the default return value
  235. # from calc_is_empty is False despite the default value for is_empty
  236. # being true. The reason for this is that strategies should be treated
  237. # as empty absent evidence to the contrary, but most basic strategies
  238. # are trivially non-empty and it would be annoying to have to override
  239. # this method to show that.
  240. return False
  241. def calc_has_reusable_values(self, recur):
  242. return False
  243. def example(self) -> Ex:
  244. """Provide an example of the sort of value that this strategy
  245. generates. This is biased to be slightly simpler than is typical for
  246. values from this strategy, for clarity purposes.
  247. This method shouldn't be taken too seriously. It's here for interactive
  248. exploration of the API, not for any sort of real testing.
  249. This method is part of the public API.
  250. """
  251. if getattr(sys, "ps1", None) is None: # pragma: no branch
  252. # The other branch *is* covered in cover/test_examples.py; but as that
  253. # uses `pexpect` for an interactive session `coverage` doesn't see it.
  254. warnings.warn(
  255. "The `.example()` method is good for exploring strategies, but should "
  256. "only be used interactively. We recommend using `@given` for tests - "
  257. "it performs better, saves and replays failures to avoid flakiness, "
  258. "and reports minimal examples. (strategy: %r)" % (self,),
  259. NonInteractiveExampleWarning,
  260. stacklevel=2,
  261. )
  262. context = _current_build_context.value
  263. if context is not None:
  264. if context.data is not None and context.data.depth > 0:
  265. raise HypothesisException(
  266. "Using example() inside a strategy definition is a bad "
  267. "idea. Instead consider using hypothesis.strategies.builds() "
  268. "or @hypothesis.strategies.composite to define your strategy."
  269. " See https://hypothesis.readthedocs.io/en/latest/data.html"
  270. "#hypothesis.strategies.builds or "
  271. "https://hypothesis.readthedocs.io/en/latest/data.html"
  272. "#composite-strategies for more details."
  273. )
  274. else:
  275. raise HypothesisException(
  276. "Using example() inside a test function is a bad "
  277. "idea. Instead consider using hypothesis.strategies.data() "
  278. "to draw more examples during testing. See "
  279. "https://hypothesis.readthedocs.io/en/latest/data.html"
  280. "#drawing-interactively-in-tests for more details."
  281. )
  282. try:
  283. return self.__examples.pop()
  284. except (AttributeError, IndexError):
  285. self.__examples: List[Ex] = []
  286. from hypothesis.core import given
  287. # Note: this function has a weird name because it might appear in
  288. # tracebacks, and we want users to know that they can ignore it.
  289. @given(self)
  290. @settings(
  291. database=None,
  292. max_examples=100,
  293. deadline=None,
  294. verbosity=Verbosity.quiet,
  295. phases=(Phase.generate,),
  296. suppress_health_check=list(HealthCheck),
  297. )
  298. def example_generating_inner_function(ex):
  299. self.__examples.append(ex)
  300. example_generating_inner_function()
  301. shuffle(self.__examples)
  302. return self.__examples.pop()
  303. def map(self, pack: Callable[[Ex], T]) -> "SearchStrategy[T]":
  304. """Returns a new strategy that generates values by generating a value
  305. from this strategy and then calling pack() on the result, giving that.
  306. This method is part of the public API.
  307. """
  308. if is_identity_function(pack):
  309. return self # type: ignore # Mypy has no way to know that `Ex == T`
  310. return MappedStrategy(self, pack=pack)
  311. def flatmap(
  312. self, expand: Callable[[Ex], "SearchStrategy[T]"]
  313. ) -> "SearchStrategy[T]":
  314. """Returns a new strategy that generates values by generating a value
  315. from this strategy, say x, then generating a value from
  316. strategy(expand(x))
  317. This method is part of the public API.
  318. """
  319. from hypothesis.strategies._internal.flatmapped import FlatMapStrategy
  320. return FlatMapStrategy(expand=expand, strategy=self)
  321. def filter(self, condition: Callable[[Ex], Any]) -> "SearchStrategy[Ex]":
  322. """Returns a new strategy that generates values from this strategy
  323. which satisfy the provided condition. Note that if the condition is too
  324. hard to satisfy this might result in your tests failing with
  325. Unsatisfiable.
  326. This method is part of the public API.
  327. """
  328. return FilteredStrategy(conditions=(condition,), strategy=self)
  329. def _filter_for_filtered_draw(self, condition):
  330. # Hook for parent strategies that want to perform fallible filtering
  331. # on one of their internal strategies (e.g. UniqueListStrategy).
  332. # The returned object must have a `.do_filtered_draw(data)` method
  333. # that behaves like `do_draw`, but returns the sentinel object
  334. # `filter_not_satisfied` if the condition could not be satisfied.
  335. # This is separate from the main `filter` method so that strategies
  336. # can override `filter` without having to also guarantee a
  337. # `do_filtered_draw` method.
  338. return FilteredStrategy(conditions=(condition,), strategy=self)
  339. @property
  340. def branches(self) -> List["SearchStrategy[Ex]"]:
  341. return [self]
  342. def __or__(self, other: "SearchStrategy[T]") -> "SearchStrategy[Union[Ex, T]]":
  343. """Return a strategy which produces values by randomly drawing from one
  344. of this strategy or the other strategy.
  345. This method is part of the public API.
  346. """
  347. if not isinstance(other, SearchStrategy):
  348. raise ValueError(f"Cannot | a SearchStrategy with {other!r}")
  349. return OneOfStrategy((self, other))
  350. def __bool__(self) -> bool:
  351. warnings.warn(
  352. f"bool({self!r}) is always True, did you mean to draw a value?",
  353. HypothesisWarning,
  354. stacklevel=2,
  355. )
  356. return True
  357. def validate(self) -> None:
  358. """Throw an exception if the strategy is not valid.
  359. This can happen due to lazy construction
  360. """
  361. if self.validate_called:
  362. return
  363. try:
  364. self.validate_called = True
  365. self.do_validate()
  366. self.is_empty
  367. self.has_reusable_values
  368. except Exception:
  369. self.validate_called = False
  370. raise
  371. LABELS: ClassVar[Dict[type, int]] = {}
  372. @property
  373. def class_label(self):
  374. cls = self.__class__
  375. try:
  376. return cls.LABELS[cls]
  377. except KeyError:
  378. pass
  379. result = calc_label_from_cls(cls)
  380. cls.LABELS[cls] = result
  381. return result
  382. @property
  383. def label(self) -> int:
  384. if self.__label is calculating:
  385. return 0
  386. if self.__label is None:
  387. self.__label = calculating
  388. self.__label = self.calc_label()
  389. return cast(int, self.__label)
  390. def calc_label(self):
  391. return self.class_label
  392. def do_validate(self):
  393. pass
  394. def do_draw(self, data: ConjectureData) -> Ex:
  395. raise NotImplementedError(f"{type(self).__name__}.do_draw")
  396. def __init__(self):
  397. pass
  398. def is_simple_data(value):
  399. try:
  400. hash(value)
  401. return True
  402. except TypeError:
  403. return False
  404. class SampledFromStrategy(SearchStrategy):
  405. """A strategy which samples from a set of elements. This is essentially
  406. equivalent to using a OneOfStrategy over Just strategies but may be more
  407. efficient and convenient.
  408. """
  409. _MAX_FILTER_CALLS = 10_000
  410. def __init__(self, elements, repr_=None, transformations=()):
  411. super().__init__()
  412. self.elements = cu.check_sample(elements, "sampled_from")
  413. assert self.elements
  414. self.repr_ = repr_
  415. self._transformations = transformations
  416. def map(self, pack):
  417. return type(self)(
  418. self.elements,
  419. repr_=self.repr_,
  420. transformations=(*self._transformations, ("map", pack)),
  421. )
  422. def filter(self, condition):
  423. return type(self)(
  424. self.elements,
  425. repr_=self.repr_,
  426. transformations=(*self._transformations, ("filter", condition)),
  427. )
  428. def __repr__(self):
  429. return (
  430. self.repr_
  431. or "sampled_from(["
  432. + ", ".join(map(get_pretty_function_description, self.elements))
  433. + "])"
  434. ) + "".join(
  435. f".{name}({get_pretty_function_description(f)})"
  436. for name, f in self._transformations
  437. )
  438. def calc_has_reusable_values(self, recur):
  439. # Because our custom .map/.filter implementations skip the normal
  440. # wrapper strategies (which would automatically return False for us),
  441. # we need to manually return False here if any transformations have
  442. # been applied.
  443. return not self._transformations
  444. def calc_is_cacheable(self, recur):
  445. return is_simple_data(self.elements)
  446. def _transform(self, element):
  447. # Used in UniqueSampledListStrategy
  448. for name, f in self._transformations:
  449. if name == "map":
  450. result = f(element)
  451. if build_context := _current_build_context.value:
  452. build_context.record_call(result, f, [element], {})
  453. element = result
  454. else:
  455. assert name == "filter"
  456. if not f(element):
  457. return filter_not_satisfied
  458. return element
  459. def do_draw(self, data):
  460. result = self.do_filtered_draw(data)
  461. if isinstance(result, SearchStrategy) and all(
  462. isinstance(x, SearchStrategy) for x in self.elements
  463. ):
  464. data._sampled_from_all_strategies_elements_message = (
  465. "sample_from was given a collection of strategies: "
  466. "{!r}. Was one_of intended?",
  467. self.elements,
  468. )
  469. if result is filter_not_satisfied:
  470. data.mark_invalid(f"Aborted test because unable to satisfy {self!r}")
  471. return result
  472. def get_element(self, i):
  473. return self._transform(self.elements[i])
  474. def do_filtered_draw(self, data):
  475. # Set of indices that have been tried so far, so that we never test
  476. # the same element twice during a draw.
  477. known_bad_indices = set()
  478. # Start with ordinary rejection sampling. It's fast if it works, and
  479. # if it doesn't work then it was only a small amount of overhead.
  480. for _ in range(3):
  481. i = data.draw_integer(0, len(self.elements) - 1)
  482. if i not in known_bad_indices:
  483. element = self.get_element(i)
  484. if element is not filter_not_satisfied:
  485. return element
  486. if not known_bad_indices:
  487. data.events[f"Retried draw from {self!r} to satisfy filter"] = ""
  488. known_bad_indices.add(i)
  489. # If we've tried all the possible elements, give up now.
  490. max_good_indices = len(self.elements) - len(known_bad_indices)
  491. if not max_good_indices:
  492. return filter_not_satisfied
  493. # Impose an arbitrary cutoff to prevent us from wasting too much time
  494. # on very large element lists.
  495. max_good_indices = min(max_good_indices, self._MAX_FILTER_CALLS - 3)
  496. # Before building the list of allowed indices, speculatively choose
  497. # one of them. We don't yet know how many allowed indices there will be,
  498. # so this choice might be out-of-bounds, but that's OK.
  499. speculative_index = data.draw_integer(0, max_good_indices - 1)
  500. # Calculate the indices of allowed values, so that we can choose one
  501. # of them at random. But if we encounter the speculatively-chosen one,
  502. # just use that and return immediately. Note that we also track the
  503. # allowed elements, in case of .map(some_stateful_function)
  504. allowed = []
  505. for i in range(min(len(self.elements), self._MAX_FILTER_CALLS - 3)):
  506. if i not in known_bad_indices:
  507. element = self.get_element(i)
  508. if element is not filter_not_satisfied:
  509. allowed.append((i, element))
  510. if len(allowed) > speculative_index:
  511. # Early-exit case: We reached the speculative index, so
  512. # we just return the corresponding element.
  513. data.draw_integer(0, len(self.elements) - 1, forced=i)
  514. return element
  515. # The speculative index didn't work out, but at this point we've built
  516. # and can choose from the complete list of allowed indices and elements.
  517. if allowed:
  518. i, element = data.choice(allowed)
  519. data.draw_integer(0, len(self.elements) - 1, forced=i)
  520. return element
  521. # If there are no allowed indices, the filter couldn't be satisfied.
  522. return filter_not_satisfied
  523. class OneOfStrategy(SearchStrategy[Ex]):
  524. """Implements a union of strategies. Given a number of strategies this
  525. generates values which could have come from any of them.
  526. The conditional distribution draws uniformly at random from some
  527. non-empty subset of these strategies and then draws from the
  528. conditional distribution of that strategy.
  529. """
  530. def __init__(self, strategies):
  531. super().__init__()
  532. strategies = tuple(strategies)
  533. self.original_strategies = list(strategies)
  534. self.__element_strategies = None
  535. self.__in_branches = False
  536. def calc_is_empty(self, recur):
  537. return all(recur(e) for e in self.original_strategies)
  538. def calc_has_reusable_values(self, recur):
  539. return all(recur(e) for e in self.original_strategies)
  540. def calc_is_cacheable(self, recur):
  541. return all(recur(e) for e in self.original_strategies)
  542. @property
  543. def element_strategies(self):
  544. if self.__element_strategies is None:
  545. # While strategies are hashable, they use object.__hash__ and are
  546. # therefore distinguished only by identity.
  547. #
  548. # In principle we could "just" define a __hash__ method
  549. # (and __eq__, but that's easy in terms of type() and hash())
  550. # to make this more powerful, but this is harder than it sounds:
  551. #
  552. # 1. Strategies are often distinguished by non-hashable attributes,
  553. # or by attributes that have the same hash value ("^.+" / b"^.+").
  554. # 2. LazyStrategy: can't reify the wrapped strategy without breaking
  555. # laziness, so there's a hash each for the lazy and the nonlazy.
  556. #
  557. # Having made several attempts, the minor benefits of making strategies
  558. # hashable are simply not worth the engineering effort it would take.
  559. # See also issues #2291 and #2327.
  560. seen = {self}
  561. strategies = []
  562. for arg in self.original_strategies:
  563. check_strategy(arg)
  564. if not arg.is_empty:
  565. for s in arg.branches:
  566. if s not in seen and not s.is_empty:
  567. seen.add(s)
  568. strategies.append(s)
  569. self.__element_strategies = strategies
  570. return self.__element_strategies
  571. def calc_label(self):
  572. return combine_labels(
  573. self.class_label, *(p.label for p in self.original_strategies)
  574. )
  575. def do_draw(self, data: ConjectureData) -> Ex:
  576. strategy = data.draw(
  577. SampledFromStrategy(self.element_strategies).filter(
  578. lambda s: s.available(data)
  579. )
  580. )
  581. return data.draw(strategy)
  582. def __repr__(self):
  583. return "one_of(%s)" % ", ".join(map(repr, self.original_strategies))
  584. def do_validate(self):
  585. for e in self.element_strategies:
  586. e.validate()
  587. @property
  588. def branches(self):
  589. if not self.__in_branches:
  590. try:
  591. self.__in_branches = True
  592. return self.element_strategies
  593. finally:
  594. self.__in_branches = False
  595. else:
  596. return [self]
  597. def filter(self, condition):
  598. return FilteredStrategy(
  599. OneOfStrategy([s.filter(condition) for s in self.original_strategies]),
  600. conditions=(),
  601. )
  602. @overload
  603. def one_of(
  604. __args: Sequence[SearchStrategy[Any]],
  605. ) -> SearchStrategy[Any]: # pragma: no cover
  606. ...
  607. @overload
  608. def one_of(__a1: SearchStrategy[Ex]) -> SearchStrategy[Ex]: # pragma: no cover
  609. ...
  610. @overload
  611. def one_of(
  612. __a1: SearchStrategy[Ex], __a2: SearchStrategy[T]
  613. ) -> SearchStrategy[Union[Ex, T]]: # pragma: no cover
  614. ...
  615. @overload
  616. def one_of(
  617. __a1: SearchStrategy[Ex], __a2: SearchStrategy[T], __a3: SearchStrategy[T3]
  618. ) -> SearchStrategy[Union[Ex, T, T3]]: # pragma: no cover
  619. ...
  620. @overload
  621. def one_of(
  622. __a1: SearchStrategy[Ex],
  623. __a2: SearchStrategy[T],
  624. __a3: SearchStrategy[T3],
  625. __a4: SearchStrategy[T4],
  626. ) -> SearchStrategy[Union[Ex, T, T3, T4]]: # pragma: no cover
  627. ...
  628. @overload
  629. def one_of(
  630. __a1: SearchStrategy[Ex],
  631. __a2: SearchStrategy[T],
  632. __a3: SearchStrategy[T3],
  633. __a4: SearchStrategy[T4],
  634. __a5: SearchStrategy[T5],
  635. ) -> SearchStrategy[Union[Ex, T, T3, T4, T5]]: # pragma: no cover
  636. ...
  637. @overload
  638. def one_of(*args: SearchStrategy[Any]) -> SearchStrategy[Any]: # pragma: no cover
  639. ...
  640. @defines_strategy(never_lazy=True)
  641. def one_of(
  642. *args: Union[Sequence[SearchStrategy[Any]], SearchStrategy[Any]]
  643. ) -> SearchStrategy[Any]:
  644. # Mypy workaround alert: Any is too loose above; the return parameter
  645. # should be the union of the input parameters. Unfortunately, Mypy <=0.600
  646. # raises errors due to incompatible inputs instead. See #1270 for links.
  647. # v0.610 doesn't error; it gets inference wrong for 2+ arguments instead.
  648. """Return a strategy which generates values from any of the argument
  649. strategies.
  650. This may be called with one iterable argument instead of multiple
  651. strategy arguments, in which case ``one_of(x)`` and ``one_of(*x)`` are
  652. equivalent.
  653. Examples from this strategy will generally shrink to ones that come from
  654. strategies earlier in the list, then shrink according to behaviour of the
  655. strategy that produced them. In order to get good shrinking behaviour,
  656. try to put simpler strategies first. e.g. ``one_of(none(), text())`` is
  657. better than ``one_of(text(), none())``.
  658. This is especially important when using recursive strategies. e.g.
  659. ``x = st.deferred(lambda: st.none() | st.tuples(x, x))`` will shrink well,
  660. but ``x = st.deferred(lambda: st.tuples(x, x) | st.none())`` will shrink
  661. very badly indeed.
  662. """
  663. if len(args) == 1 and not isinstance(args[0], SearchStrategy):
  664. try:
  665. args = tuple(args[0])
  666. except TypeError:
  667. pass
  668. if len(args) == 1 and isinstance(args[0], SearchStrategy):
  669. # This special-case means that we can one_of over lists of any size
  670. # without incurring any performance overhead when there is only one
  671. # strategy, and keeps our reprs simple.
  672. return args[0]
  673. if args and not any(isinstance(a, SearchStrategy) for a in args):
  674. # And this special case is to give a more-specific error message if it
  675. # seems that the user has confused `one_of()` for `sampled_from()`;
  676. # the remaining validation is left to OneOfStrategy. See PR #2627.
  677. raise InvalidArgument(
  678. f"Did you mean st.sampled_from({list(args)!r})? st.one_of() is used "
  679. "to combine strategies, but all of the arguments were of other types."
  680. )
  681. return OneOfStrategy(args)
  682. class MappedStrategy(SearchStrategy[Ex]):
  683. """A strategy which is defined purely by conversion to and from another
  684. strategy.
  685. Its parameter and distribution come from that other strategy.
  686. """
  687. def __init__(self, strategy, pack):
  688. super().__init__()
  689. self.mapped_strategy = strategy
  690. self.pack = pack
  691. def calc_is_empty(self, recur):
  692. return recur(self.mapped_strategy)
  693. def calc_is_cacheable(self, recur):
  694. return recur(self.mapped_strategy)
  695. def __repr__(self):
  696. if not hasattr(self, "_cached_repr"):
  697. self._cached_repr = f"{self.mapped_strategy!r}.map({get_pretty_function_description(self.pack)})"
  698. return self._cached_repr
  699. def do_validate(self):
  700. self.mapped_strategy.validate()
  701. def do_draw(self, data: ConjectureData) -> Any:
  702. with warnings.catch_warnings():
  703. if isinstance(self.pack, type) and issubclass(
  704. self.pack, (abc.Mapping, abc.Set)
  705. ):
  706. warnings.simplefilter("ignore", BytesWarning)
  707. for _ in range(3):
  708. try:
  709. data.start_example(MAPPED_SEARCH_STRATEGY_DO_DRAW_LABEL)
  710. x = data.draw(self.mapped_strategy)
  711. result = self.pack(x) # type: ignore
  712. data.stop_example()
  713. _current_build_context.value.record_call(result, self.pack, [x], {})
  714. return result
  715. except UnsatisfiedAssumption:
  716. data.stop_example(discard=True)
  717. raise UnsatisfiedAssumption
  718. @property
  719. def branches(self) -> List[SearchStrategy[Ex]]:
  720. return [
  721. MappedStrategy(strategy, pack=self.pack)
  722. for strategy in self.mapped_strategy.branches
  723. ]
  724. def filter(self, condition: Callable[[Ex], Any]) -> "SearchStrategy[Ex]":
  725. # Includes a special case so that we can rewrite filters on collection
  726. # lengths, when most collections are `st.lists(...).map(the_type)`.
  727. ListStrategy = _list_strategy_type()
  728. if not isinstance(self.mapped_strategy, ListStrategy) or not (
  729. (isinstance(self.pack, type) and issubclass(self.pack, abc.Collection))
  730. or self.pack in _collection_ish_functions()
  731. ):
  732. return super().filter(condition)
  733. # Check whether our inner list strategy can rewrite this filter condition.
  734. # If not, discard the result and _only_ apply a new outer filter.
  735. new = ListStrategy.filter(self.mapped_strategy, condition)
  736. if getattr(new, "filtered_strategy", None) is self.mapped_strategy:
  737. return super().filter(condition) # didn't rewrite
  738. # Apply a new outer filter even though we rewrote the inner strategy,
  739. # because some collections can change the list length (dict, set, etc).
  740. return FilteredStrategy(type(self)(new, self.pack), conditions=(condition,))
  741. @lru_cache
  742. def _list_strategy_type():
  743. from hypothesis.strategies._internal.collections import ListStrategy
  744. return ListStrategy
  745. def _collection_ish_functions():
  746. funcs = [sorted]
  747. if np := sys.modules.get("numpy"):
  748. # c.f. https://numpy.org/doc/stable/reference/routines.array-creation.html
  749. # Probably only `np.array` and `np.asarray` will be used in practice,
  750. # but why should that stop us when we've already gone this far?
  751. funcs += [
  752. np.empty_like,
  753. np.eye,
  754. np.identity,
  755. np.ones_like,
  756. np.zeros_like,
  757. np.array,
  758. np.asarray,
  759. np.asanyarray,
  760. np.ascontiguousarray,
  761. np.asmatrix,
  762. np.copy,
  763. np.rec.array,
  764. np.rec.fromarrays,
  765. np.rec.fromrecords,
  766. np.diag,
  767. # bonus undocumented functions from tab-completion:
  768. np.asarray_chkfinite,
  769. np.asfarray,
  770. np.asfortranarray,
  771. ]
  772. return funcs
  773. filter_not_satisfied = UniqueIdentifier("filter not satisfied")
  774. class FilteredStrategy(SearchStrategy[Ex]):
  775. def __init__(self, strategy, conditions):
  776. super().__init__()
  777. if isinstance(strategy, FilteredStrategy):
  778. # Flatten chained filters into a single filter with multiple conditions.
  779. self.flat_conditions = strategy.flat_conditions + conditions
  780. self.filtered_strategy = strategy.filtered_strategy
  781. else:
  782. self.flat_conditions = conditions
  783. self.filtered_strategy = strategy
  784. assert isinstance(self.flat_conditions, tuple)
  785. assert not isinstance(self.filtered_strategy, FilteredStrategy)
  786. self.__condition = None
  787. def calc_is_empty(self, recur):
  788. return recur(self.filtered_strategy)
  789. def calc_is_cacheable(self, recur):
  790. return recur(self.filtered_strategy)
  791. def __repr__(self):
  792. if not hasattr(self, "_cached_repr"):
  793. self._cached_repr = "{!r}{}".format(
  794. self.filtered_strategy,
  795. "".join(
  796. f".filter({get_pretty_function_description(cond)})"
  797. for cond in self.flat_conditions
  798. ),
  799. )
  800. return self._cached_repr
  801. def do_validate(self):
  802. # Start by validating our inner filtered_strategy. If this was a LazyStrategy,
  803. # validation also reifies it so that subsequent calls to e.g. `.filter()` will
  804. # be passed through.
  805. self.filtered_strategy.validate()
  806. # So now we have a reified inner strategy, we'll replay all our saved
  807. # predicates in case some or all of them can be rewritten. Note that this
  808. # replaces the `fresh` strategy too!
  809. fresh = self.filtered_strategy
  810. for cond in self.flat_conditions:
  811. fresh = fresh.filter(cond)
  812. if isinstance(fresh, FilteredStrategy):
  813. # In this case we have at least some non-rewritten filter predicates,
  814. # so we just re-initialize the strategy.
  815. FilteredStrategy.__init__(
  816. self, fresh.filtered_strategy, fresh.flat_conditions
  817. )
  818. else:
  819. # But if *all* the predicates were rewritten... well, do_validate() is
  820. # an in-place method so we still just re-initialize the strategy!
  821. FilteredStrategy.__init__(self, fresh, ())
  822. def filter(self, condition):
  823. # If we can, it's more efficient to rewrite our strategy to satisfy the
  824. # condition. We therefore exploit the fact that the order of predicates
  825. # doesn't matter (`f(x) and g(x) == g(x) and f(x)`) by attempting to apply
  826. # condition directly to our filtered strategy as the inner-most filter.
  827. out = self.filtered_strategy.filter(condition)
  828. # If it couldn't be rewritten, we'll get a new FilteredStrategy - and then
  829. # combine the conditions of each in our expected newest=last order.
  830. if isinstance(out, FilteredStrategy):
  831. return FilteredStrategy(
  832. out.filtered_strategy, self.flat_conditions + out.flat_conditions
  833. )
  834. # But if it *could* be rewritten, we can return the more efficient form!
  835. return FilteredStrategy(out, self.flat_conditions)
  836. @property
  837. def condition(self):
  838. if self.__condition is None:
  839. if len(self.flat_conditions) == 1:
  840. # Avoid an extra indirection in the common case of only one condition.
  841. self.__condition = self.flat_conditions[0]
  842. elif len(self.flat_conditions) == 0:
  843. # Possible, if unlikely, due to filter predicate rewriting
  844. self.__condition = lambda _: True
  845. else:
  846. self.__condition = lambda x: all(
  847. cond(x) for cond in self.flat_conditions
  848. )
  849. return self.__condition
  850. def do_draw(self, data: ConjectureData) -> Ex:
  851. result = self.do_filtered_draw(data)
  852. if result is not filter_not_satisfied:
  853. return result
  854. data.mark_invalid(f"Aborted test because unable to satisfy {self!r}")
  855. raise NotImplementedError("Unreachable, for Mypy")
  856. def do_filtered_draw(self, data):
  857. for i in range(3):
  858. data.start_example(FILTERED_SEARCH_STRATEGY_DO_DRAW_LABEL)
  859. value = data.draw(self.filtered_strategy)
  860. if self.condition(value):
  861. data.stop_example()
  862. return value
  863. else:
  864. data.stop_example(discard=True)
  865. if i == 0:
  866. data.events[f"Retried draw from {self!r} to satisfy filter"] = ""
  867. return filter_not_satisfied
  868. @property
  869. def branches(self) -> List[SearchStrategy[Ex]]:
  870. return [
  871. FilteredStrategy(strategy=strategy, conditions=self.flat_conditions)
  872. for strategy in self.filtered_strategy.branches
  873. ]
  874. @check_function
  875. def check_strategy(arg, name=""):
  876. assert isinstance(name, str)
  877. if not isinstance(arg, SearchStrategy):
  878. hint = ""
  879. if isinstance(arg, (list, tuple)):
  880. hint = ", such as st.sampled_from({}),".format(name or "...")
  881. if name:
  882. name += "="
  883. raise InvalidArgument(
  884. "Expected a SearchStrategy%s but got %s%r (type=%s)"
  885. % (hint, name, arg, type(arg).__name__)
  886. )