How to use note_retried method in hypothesis

Best Python code snippet using hypothesis

strategies.py

Source:strategies.py Github

copy

Full Screen

...388 return False389 ok = filter_strategy.condition(self.elements[i])390 if not ok:391 if not known_bad_indices:392 filter_strategy.note_retried(data)393 known_bad_indices.add(i)394 return ok395 # Start with ordinary rejection sampling. It's fast if it works, and396 # if it doesn't work then it was only a small amount of overhead.397 for _ in range(3):398 i = cu.integer_range(data, 0, len(self.elements) - 1)399 if check_index(i):400 return self.elements[i]401 # If we've tried all the possible elements, give up now.402 max_good_indices = len(self.elements) - len(known_bad_indices)403 if not max_good_indices:404 return filter_not_satisfied405 # Figure out the bit-length of the index that we will write back after406 # choosing an allowed element.407 write_length = len(self.elements).bit_length()408 # Impose an arbitrary cutoff to prevent us from wasting too much time409 # on very large element lists.410 cutoff = 10000411 max_good_indices = min(max_good_indices, cutoff)412 # Before building the list of allowed indices, speculatively choose413 # one of them. We don't yet know how many allowed indices there will be,414 # so this choice might be out-of-bounds, but that's OK.415 speculative_index = cu.integer_range(data, 0, max_good_indices - 1)416 # Calculate the indices of allowed values, so that we can choose one417 # of them at random. But if we encounter the speculatively-chosen one,418 # just use that and return immediately.419 allowed_indices = []420 for i in range(min(len(self.elements), cutoff)):421 if check_index(i):422 allowed_indices.append(i)423 if len(allowed_indices) > speculative_index:424 # Early-exit case: We reached the speculative index, so425 # we just return the corresponding element.426 data.draw_bits(write_length, forced=i)427 return self.elements[i]428 # The speculative index didn't work out, but at this point we've built429 # the complete list of allowed indices, so we can just choose one of430 # them.431 if allowed_indices:432 i = cu.choice(data, allowed_indices)433 data.draw_bits(write_length, forced=i)434 return self.elements[i]435 # If there are no allowed indices, the filter couldn't be satisfied.436 return filter_not_satisfied437class OneOfStrategy(SearchStrategy):438 """Implements a union of strategies. Given a number of strategies this439 generates values which could have come from any of them.440 The conditional distribution draws uniformly at random from some441 non-empty subset of these strategies and then draws from the442 conditional distribution of that strategy.443 """444 def __init__(self, strategies):445 SearchStrategy.__init__(self)446 strategies = tuple(strategies)447 self.original_strategies = list(strategies)448 self.__element_strategies = None449 self.__in_branches = False450 def calc_is_empty(self, recur):451 return all(recur(e) for e in self.original_strategies)452 def calc_has_reusable_values(self, recur):453 return all(recur(e) for e in self.original_strategies)454 def calc_is_cacheable(self, recur):455 return all(recur(e) for e in self.original_strategies)456 @property457 def element_strategies(self):458 if self.__element_strategies is None:459 # While strategies are hashable, they use object.__hash__ and are460 # therefore distinguished only by identity.461 #462 # In principle we could "just" define a __hash__ method463 # (and __eq__, but that's easy in terms of type() and hash())464 # to make this more powerful, but this is harder than it sounds:465 #466 # 1. Strategies are often distinguished by non-hashable attributes,467 # or by attributes that have the same hash value ("^.+" / b"^.+").468 # 2. LazyStrategy: can't reify the wrapped strategy without breaking469 # laziness, so there's a hash each for the lazy and the nonlazy.470 #471 # Having made several attempts, the minor benefits of making strategies472 # hashable are simply not worth the engineering effort it would take.473 # See also issues #2291 and #2327.474 seen = {self}475 strategies = []476 for arg in self.original_strategies:477 check_strategy(arg)478 if not arg.is_empty:479 for s in arg.branches:480 if s not in seen and not s.is_empty:481 seen.add(s)482 strategies.append(s)483 self.__element_strategies = strategies484 return self.__element_strategies485 def calc_label(self):486 return combine_labels(487 self.class_label, *[p.label for p in self.original_strategies]488 )489 def do_draw(self, data: ConjectureData) -> Ex:490 strategy = data.draw(491 SampledFromStrategy(self.element_strategies).filter(492 lambda s: s.available(data)493 )494 )495 return data.draw(strategy)496 def __repr__(self):497 return "one_of(%s)" % ", ".join(map(repr, self.original_strategies))498 def do_validate(self):499 for e in self.element_strategies:500 e.validate()501 @property502 def branches(self):503 if not self.__in_branches:504 try:505 self.__in_branches = True506 return self.element_strategies507 finally:508 self.__in_branches = False509 else:510 return [self]511class MappedSearchStrategy(SearchStrategy):512 """A strategy which is defined purely by conversion to and from another513 strategy.514 Its parameter and distribution come from that other strategy.515 """516 def __init__(self, strategy, pack=None):517 SearchStrategy.__init__(self)518 self.mapped_strategy = strategy519 if pack is not None:520 self.pack = pack521 def calc_is_empty(self, recur):522 return recur(self.mapped_strategy)523 def calc_is_cacheable(self, recur):524 return recur(self.mapped_strategy)525 def __repr__(self):526 if not hasattr(self, "_cached_repr"):527 self._cached_repr = "%r.map(%s)" % (528 self.mapped_strategy,529 get_pretty_function_description(self.pack),530 )531 return self._cached_repr532 def do_validate(self):533 self.mapped_strategy.validate()534 def pack(self, x):535 """Take a value produced by the underlying mapped_strategy and turn it536 into a value suitable for outputting from this strategy."""537 raise NotImplementedError("%s.pack()" % (self.__class__.__name__))538 def do_draw(self, data: ConjectureData) -> Ex:539 for _ in range(3):540 i = data.index541 try:542 data.start_example(MAPPED_SEARCH_STRATEGY_DO_DRAW_LABEL)543 result = self.pack(data.draw(self.mapped_strategy))544 data.stop_example()545 return result546 except UnsatisfiedAssumption:547 data.stop_example(discard=True)548 if data.index == i:549 raise550 raise UnsatisfiedAssumption()551 @property552 def branches(self) -> List[SearchStrategy[Ex]]:553 return [554 MappedSearchStrategy(pack=self.pack, strategy=strategy)555 for strategy in self.mapped_strategy.branches556 ]557filter_not_satisfied = UniqueIdentifier("filter not satisfied")558class FilteredStrategy(SearchStrategy):559 def __init__(self, strategy, conditions):560 super().__init__()561 if isinstance(strategy, FilteredStrategy):562 # Flatten chained filters into a single filter with multiple563 # conditions.564 self.flat_conditions = strategy.flat_conditions + conditions565 self.filtered_strategy = strategy.filtered_strategy566 else:567 self.flat_conditions = conditions568 self.filtered_strategy = strategy569 assert self.flat_conditions570 assert isinstance(self.flat_conditions, tuple)571 assert not isinstance(self.filtered_strategy, FilteredStrategy)572 self.__condition = None573 def calc_is_empty(self, recur):574 return recur(self.filtered_strategy)575 def calc_is_cacheable(self, recur):576 return recur(self.filtered_strategy)577 def __repr__(self):578 if not hasattr(self, "_cached_repr"):579 self._cached_repr = "%r%s" % (580 self.filtered_strategy,581 "".join(582 ".filter(%s)" % get_pretty_function_description(cond)583 for cond in self.flat_conditions584 ),585 )586 return self._cached_repr587 def do_validate(self):588 self.filtered_strategy.validate()589 @property590 def condition(self):591 if self.__condition is None:592 assert self.flat_conditions593 if len(self.flat_conditions) == 1:594 # Avoid an extra indirection in the common case of only one595 # condition.596 self.__condition = self.flat_conditions[0]597 else:598 self.__condition = lambda x: all(599 cond(x) for cond in self.flat_conditions600 )601 return self.__condition602 def do_draw(self, data: ConjectureData) -> Ex:603 result = self.filtered_strategy.do_filtered_draw(604 data=data, filter_strategy=self605 )606 if result is not filter_not_satisfied:607 return result608 data.note_event("Aborted test because unable to satisfy %r" % (self,))609 data.mark_invalid()610 raise NotImplementedError("Unreachable, for Mypy")611 def note_retried(self, data):612 data.note_event(lazyformat("Retried draw from %r to satisfy filter", self))613 def default_do_filtered_draw(self, data):614 for i in range(3):615 start_index = data.index616 value = data.draw(self.filtered_strategy)617 if self.condition(value):618 return value619 else:620 if i == 0:621 self.note_retried(data)622 # This is to guard against the case where we consume no data.623 # As long as we consume data, we'll eventually pass or raise.624 # But if we don't this could be an infinite loop.625 assume(data.index > start_index)626 return filter_not_satisfied627 @property628 def branches(self) -> List[SearchStrategy[Ex]]:629 return [630 FilteredStrategy(strategy=strategy, conditions=self.flat_conditions)631 for strategy in self.filtered_strategy.branches632 ]633@check_function634def check_strategy(arg, name=""):635 if not isinstance(arg, SearchStrategy):...

Full Screen

Full Screen

misc.py

Source:misc.py Github

copy

Full Screen

...75 return False76 ok = filter_strategy.condition(self.elements[i])77 if not ok:78 if not known_bad_indices:79 filter_strategy.note_retried(data)80 known_bad_indices.add(i)81 return ok82 # Start with ordinary rejection sampling. It's fast if it works, and83 # if it doesn't work then it was only a small amount of overhead.84 for _ in hrange(3):85 i = d.integer_range(data, 0, len(self.elements) - 1)86 if check_index(i):87 return self.elements[i]88 # If we've tried all the possible elements, give up now.89 max_good_indices = len(self.elements) - len(known_bad_indices)90 if not max_good_indices:91 return filter_not_satisfied92 # Figure out the bit-length of the index that we will write back after93 # choosing an allowed element....

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run hypothesis automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful