Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: PoC of meta strategy, which draws others by a given weight distribution #1734

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions hypothesis-python/src/hypothesis/_strategies.py
Original file line number Diff line number Diff line change
Expand Up @@ -2319,3 +2319,9 @@ def emails():
return builds(u"{}@{}".format, local_part, domains()).filter(
lambda addr: len(addr) <= 255
)


def distributed(strategies, weights):
# type: (List[SearchStrategy], List[Union[int, float]]) -> SearchStrategy[Any]
from hypothesis.provisional import distributed
return distributed(strategies, weights)
37 changes: 37 additions & 0 deletions hypothesis-python/src/hypothesis/provisional.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,40 @@ def ip6_addr_strings():
"""
part = st.integers(0, 2 ** 16 - 1).map(u"{:04x}".format)
return st.tuples(*[part] * 8).map(lambda a: u":".join(a).upper())


def distributed(strategies, weights):
from hypothesis.internal.conjecture.utils import Sampler
from hypothesis.strategies import SearchStrategy
from hypothesis.searchstrategy.strategies import check_strategy
from hypothesis.internal.validation import check_type, InvalidArgument

class DistributedStrategy(SearchStrategy):
def __init__(self, strategies, weights):
SearchStrategy.__init__(self)
self.sampler = Sampler(weights)
self.strategies = strategies

def calc_has_reusable_values(self, recur):
return True

def do_draw(self, data):
strategy = self.strategies[self.sampler.sample(data)]
return strategy.do_draw(data)

assert strategies

for strategy in strategies:
check_strategy(strategy)

for weight in weights:
check_type((int, float), weight)
if weight < 0:
raise InvalidArgument("weight must be a positive number")

if len(strategies) != len(weights):
raise InvalidArgument(
"The number of weights must match the number of strategies"
)

return DistributedStrategy(strategies, weights)
2 changes: 2 additions & 0 deletions hypothesis-python/src/hypothesis/strategies.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
decimals,
deferred,
dictionaries,
distributed,
emails,
fixed_dictionaries,
floats,
Expand Down Expand Up @@ -83,6 +84,7 @@
"decimals",
"deferred",
"dictionaries",
"distributed",
"emails",
"fixed_dictionaries",
"floats",
Expand Down