def test_fuzz_fractions_bounds(data): denom = data.draw(none() | integers(1, 100), label="denominator") fracs = none() | fractions(max_denominator=denom) low, high = data.draw(tuples(fracs, fracs), label="low, high") if low is not None and high is not None and low > high: low, high = high, low try: val = data.draw(fractions(low, high, denom), label="value") except InvalidArgument: reject() # fractions too close for given max_denominator if low is not None: assert low <= val if high is not None: assert val <= high if denom is not None: assert 1 <= val.denominator <= denom
def test_non_reversible_fractions_as_decimals(): def not_reversible(xs): xs = [Decimal(x.numerator) / x.denominator for x in xs] return sum(xs) != sum(reversed(xs)) sigh = minimal(lists(fractions()), not_reversible, timeout_after=20) assert len(sigh) <= 25
def test_minimal_fractions_4(): x = minimal( lists( fractions(max_denominator=100, max_value=100, min_value=-100), min_size=20), lambda s: len([t for t in s if t >= 1]) >= 20 ) assert x == [Fraction(1)] * 20
def define_fraction_strategy(specifier, settings): return st.fractions()
def test_minimal_fractions_4(): x = minimal( lists(fractions(), min_size=20), lambda s: len([t for t in s if t >= 1]) >= 20 ) assert x == [Fraction(1)] * 20
# modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # # Red Hat Author(s): Anne Mulhern <*****@*****.**> """ Utilities for testing. """ from hypothesis import strategies from justbytes import Range from justbytes import UNITS NUMBERS_STRATEGY = strategies.one_of( strategies.integers(), strategies.fractions().map(lambda x: x.limit_denominator(100)) ) SIZE_STRATEGY = strategies.builds( Range, strategies.one_of(NUMBERS_STRATEGY, strategies.builds(str, NUMBERS_STRATEGY)), strategies.sampled_from(UNITS()), )
def fractions(draw, *args, **kwargs): return F(draw(hys.fractions(*args, **kwargs)))
@settings(max_examples=100) def test_has_upper_bound(x): assert x <= 100 @given(ds.integers(min_value=100)) def test_has_lower_bound(x): assert x >= 100 @given(ds.integers(min_value=1, max_value=2)) def test_is_in_bounds(x): assert 1 <= x <= 2 @given(ds.fractions(min_value=-1, max_value=1, max_denominator=1000)) def test_fraction_is_in_bounds(x): assert -1 <= x <= 1 and abs(x.denominator) <= 1000 @given(ds.fractions(min_value=fractions.Fraction(1, 2))) def test_fraction_gt_positive(x): assert fractions.Fraction(1, 2) <= x @given(ds.fractions(max_value=fractions.Fraction(-1, 2))) def test_fraction_lt_negative(x): assert x <= fractions.Fraction(-1, 2) @given(ds.decimals(min_value=-1.5, max_value=1.5, allow_nan=False))
floats(min_value=-2.0, max_value=3.0), floats(), floats(min_value=-2.0), floats(), floats(max_value=-0.0), floats(), floats(min_value=0.0), floats(min_value=3.14, max_value=3.14), text(), binary(), booleans(), tuples(booleans(), booleans()), frozensets(integers()), sets(frozensets(booleans())), complex_numbers(), fractions(), decimals(), lists(lists(booleans())), lists(lists(booleans(), average_size=100)), lists(floats(0.0, 0.0), average_size=1.0), ordered_pair, constant_list(integers()), streaming(integers()).map(lambda x: list(x[:2]) and x), integers().filter(lambda x: abs(x) > 100), floats(min_value=-sys.float_info.max, max_value=sys.float_info.max), none(), randoms(), tuples().flatmap(lambda x: EvalledIntStream), templates_for(integers(min_value=0, max_value=0).flatmap(lambda x: integers(min_value=0, max_value=0))), booleans().flatmap(lambda x: booleans() if x else complex_numbers()), recursive(base=booleans(), extend=lambda x: lists(x, max_size=3), max_leaves=10),
size_strategies = dict( min_size=st.integers(min_value=0, max_value=100) | st.none(), max_size=st.integers(min_value=0, max_value=100) | st.none(), average_size=st.floats(min_value=0.0, max_value=100.0) | st.none() ) values = st.integers() | st.text(average_size=2.0) Strategies = st.recursive( st.one_of( st.sampled_from([ st.none(), st.booleans(), st.randoms(), st.complex_numbers(), st.randoms(), st.fractions(), st.decimals(), ]), st.builds(st.just, values), st.builds(st.sampled_from, st.lists(values, min_size=1)), builds_ignoring_invalid(st.floats, st.floats(), st.floats()), ), lambda x: st.one_of( builds_ignoring_invalid(st.lists, x, **size_strategies), builds_ignoring_invalid(st.sets, x, **size_strategies), builds_ignoring_invalid( lambda v: st.tuples(*v), st.lists(x, average_size=2.0)), builds_ignoring_invalid( lambda v: st.one_of(*v), st.lists(x, average_size=2.0, min_size=1)), builds_ignoring_invalid( st.dictionaries, x, x,
size_strategies = dict( min_size=st.integers(min_value=0, max_value=100), max_size=st.integers(min_value=0, max_value=100) | st.none(), ) values = st.integers() | st.text() Strategies = st.recursive( st.one_of( st.sampled_from([ st.none(), st.booleans(), st.randoms(), st.complex_numbers(), st.randoms(), st.fractions(), st.decimals(), ]), st.builds(st.just, values), st.builds(st.sampled_from, st.lists(values, min_size=1)), builds_ignoring_invalid(st.floats, st.floats(), st.floats()), ), lambda x: st.one_of( builds_ignoring_invalid(st.lists, x, **size_strategies), builds_ignoring_invalid(st.sets, x, **size_strategies), builds_ignoring_invalid(lambda v: st.tuples(*v), st.lists(x)), builds_ignoring_invalid(lambda v: st.one_of(*v), st.lists(x, min_size=1)), builds_ignoring_invalid(st.dictionaries, x, x,
class HypothesisSpec(RuleBasedStateMachine): def __init__(self): super(HypothesisSpec, self).__init__() self.database = None strategies = Bundle(u'strategy') strategy_tuples = Bundle(u'tuples') objects = Bundle(u'objects') basic_data = Bundle(u'basic') varied_floats = Bundle(u'varied_floats') def teardown(self): self.clear_database() @rule() def clear_database(self): if self.database is not None: self.database.close() self.database = None @rule() def set_database(self): self.teardown() self.database = ExampleDatabase() @rule(strat=strategies, r=integers(), max_shrinks=integers(0, 100)) def find_constant_failure(self, strat, r, max_shrinks): with settings( verbosity=Verbosity.quiet, max_examples=1, min_satisfying_examples=0, database=self.database, max_shrinks=max_shrinks, ): @given(strat) @seed(r) def test(x): assert False try: test() except (AssertionError, FailedHealthCheck): pass @rule( strat=strategies, r=integers(), p=floats(0, 1), max_examples=integers(1, 10), max_shrinks=integers(1, 100) ) def find_weird_failure(self, strat, r, max_examples, p, max_shrinks): with settings( verbosity=Verbosity.quiet, max_examples=max_examples, min_satisfying_examples=0, database=self.database, max_shrinks=max_shrinks, ): @given(strat) @seed(r) def test(x): assert Random( hashlib.md5(repr(x).encode(u'utf-8')).digest() ).random() <= p try: test() except (AssertionError, FailedHealthCheck): pass @rule(target=strategies, spec=sampled_from(( integers(), booleans(), floats(), complex_numbers(), fractions(), decimals(), text(), binary(), none(), tuples(), ))) def strategy(self, spec): return spec @rule(target=strategies, values=lists(integers() | text(), min_size=1)) def sampled_from_strategy(self, values): return sampled_from(values) @rule(target=strategies, spec=strategy_tuples) def strategy_for_tupes(self, spec): return tuples(*spec) @rule( target=strategies, source=strategies, level=integers(1, 10), mixer=text()) def filtered_strategy(s, source, level, mixer): def is_good(x): return bool(Random( hashlib.md5((mixer + repr(x)).encode(u'utf-8')).digest() ).randint(0, level)) return source.filter(is_good) @rule(target=strategies, elements=strategies) def list_strategy(self, elements): return lists(elements, average_size=AVERAGE_LIST_LENGTH) @rule(target=strategies, left=strategies, right=strategies) def or_strategy(self, left, right): return left | right @rule(target=varied_floats, source=floats()) def float(self, source): return source @rule( target=varied_floats, source=varied_floats, offset=integers(-100, 100)) def adjust_float(self, source, offset): return int_to_float(clamp( 0, float_to_int(source) + offset, 2 ** 64 - 1 )) @rule( target=strategies, left=varied_floats, right=varied_floats ) def float_range(self, left, right): for f in (math.isnan, math.isinf): for x in (left, right): assume(not f(x)) left, right = sorted((left, right)) assert left <= right return floats(left, right) @rule( target=strategies, source=strategies, result1=strategies, result2=strategies, mixer=text(), p=floats(0, 1)) def flatmapped_strategy(self, source, result1, result2, mixer, p): assume(result1 is not result2) def do_map(value): rep = repr(value) random = Random( hashlib.md5((mixer + rep).encode(u'utf-8')).digest() ) if random.random() <= p: return result1 else: return result2 return source.flatmap(do_map) @rule(target=strategies, value=objects) def just_strategy(self, value): return just(value) @rule(target=strategy_tuples, source=strategies) def single_tuple(self, source): return (source,) @rule(target=strategy_tuples, left=strategy_tuples, right=strategy_tuples) def cat_tuples(self, left, right): return left + right @rule(target=objects, strat=strategies, data=data()) def get_example(self, strat, data): data.draw(strat) @rule(target=strategies, left=integers(), right=integers()) def integer_range(self, left, right): left, right = sorted((left, right)) return integers(left, right) @rule(strat=strategies) def repr_is_good(self, strat): assert u' at 0x' not in repr(strat)
import logging from hypothesis import given import hypothesis.strategies as st LOGGER_NAME = "hunter2" log = logging.getLogger(LOGGER_NAME) ALL_SORTS_ITEMS = ( st.integers(), st.text(), st.floats(), st.booleans(), st.complex_numbers(), st.tuples(), st.fractions(), st.decimals(), ) ALL_SORTS = st.tuples(st.recursive(st.one_of(*ALL_SORTS_ITEMS), st.lists)) @log_when_called(log) def example_func(*args, **kwargs): pass @given(ALL_SORTS) def test_basic_log(args): with testfixtures.LogCapture() as logs: example_func(args)
empty = ', '.join(repr(s) for s in strategies if s.is_empty) if empty or not strategies: # pragma: no cover raise ResolutionFailed( 'Could not resolve %s to a strategy; consider using ' 'register_type_strategy' % (empty or thing, )) return st.one_of(strategies) _global_type_lookup = { # Types with core Hypothesis strategies type(None): st.none(), bool: st.booleans(), int: st.integers(), float: st.floats(), complex: st.complex_numbers(), fractions.Fraction: st.fractions(), decimal.Decimal: st.decimals(), text_type: st.text(), binary_type: st.binary(), datetime.datetime: st.datetimes(), datetime.date: st.dates(), datetime.time: st.times(), datetime.timedelta: st.timedeltas(), uuid.UUID: st.uuids(), tuple: st.builds(tuple), list: st.builds(list), set: st.builds(set), frozenset: st.builds(frozenset), dict: st.builds(dict), # Built-in types type: st.sampled_from([type(None), bool, int, str, list, set, dict]),
import decimal import hypothesis as H import hypothesis.strategies as st from bunch import Bunch hashables = st.one_of( st.booleans(), st.none(), st.integers(), st.tuples(st.deferred(lambda: hashables)), st.frozensets(st.deferred(lambda: hashables)), st.floats(), st.text(), st.binary(), st.fractions(), st.decimals().filter(lambda x: not decimal.Decimal.is_snan(x)), st.datetimes(), st.dates(), st.times(), st.timedeltas(), st.uuids()) all_things = st.one_of( hashables, st.one_of( st.lists(st.deferred(lambda: all_things)), st.sets(hashables), st.dictionaries(hashables, st.deferred(lambda: all_things)), ), ) bunches = st.tuples(hashables).map(lambda x: Bunch(*x)) class DescribeBunch: def it_simple_containment(self): assert None in Bunch(None) assert 1 in Bunch(1, 2)
def test_minimal_fractions_4(): x = minimal( lists(fractions(max_denominator=100, max_value=100, min_value=-100), min_size=20), lambda s: len([t for t in s if t >= 1]) >= 20) assert x == [Fraction(1)] * 20
import pytest from hypothesis import given, assume from tests.common.utils import fails from hypothesis.strategies import decimals, fractions from hypothesis.internal.compat import float_to_decimal @fails @given(decimals()) def test_all_decimals_can_be_exact_floats(x): assume(x.is_finite()) assert float_to_decimal(float(x)) == x @given(fractions(), fractions(), fractions()) def test_fraction_addition_is_well_behaved(x, y, z): assert x + y + z == y + x + z @fails @given(decimals()) def test_decimals_include_nan(x): assert not math.isnan(x) @fails @given(decimals()) def test_decimals_include_inf(x): assume(not x.is_snan()) assert not math.isinf(x)
def test_minimal_fractions_4(): assert minimal( lists(fractions()), lambda s: len(s) >= 20 and all(t >= 1 for t in s) ) == [Fraction(1)] * 20
class HypothesisSpec(RuleBasedStateMachine): def __init__(self): super(HypothesisSpec, self).__init__() self.database = None strategies = Bundle(u'strategy') strategy_tuples = Bundle(u'tuples') objects = Bundle(u'objects') streaming_strategies = Bundle(u'streams') basic_data = Bundle(u'basic') varied_floats = Bundle(u'varied_floats') strats_with_parameters = Bundle(u'strats_with_parameters') strats_with_templates = Bundle(u'strats_with_templates') strats_with_2_templates = Bundle(u'strats_with_2_templates') def teardown(self): self.clear_database() @rule(target=basic_data, st=strats_with_templates) def to_basic(self, st): return st[0].to_basic(st[1]) @rule(data=basic_data, strat=strategies) def from_basic(self, data, strat): try: template = strat.from_basic(data) except BadData: return strat.reify(template) @rule(target=basic_data, data=basic_data, r=randoms()) def mess_with_basic(self, data, r): return mutate_basic(data, r) @rule() def clear_database(self): if self.database is not None: self.database.close() self.database = None @rule() def set_database(self): self.teardown() self.database = ExampleDatabase() @rule(st=strats_with_templates) def reify(self, st): strat, temp = st strat.reify(temp) @rule(target=strats_with_templates, st=strats_with_templates) def via_basic(self, st): strat, temp = st temp = strat.from_basic(strat.to_basic(temp)) return (strat, temp) @rule(targets=(strategies, streaming_strategies), strat=strategies) def build_stream(self, strat): return strategy(streaming(strat)) @rule(targets=(strategies, streaming_strategies), strat=strategies, i=integers(1, 10)) def evalled_stream(self, strat, i): return strategy(streaming(strat)).map(lambda x: list(x[:i]) and x) @rule(stream_strat=streaming_strategies, index=integers(0, 50)) def eval_stream(self, stream_strat, index): try: stream = stream_strat.example() list(stream[:index]) except NoExamples: pass @rule(target=strats_with_templates, st=strats_with_templates, r=randoms()) def simplify(self, st, r): strat, temp = st for temp in strat.full_simplify(r, temp): break return (strat, temp) @rule(strat=strategies, r=randoms(), mshr=integers(0, 100)) def find_constant_failure(self, strat, r, mshr): with Settings( verbosity=Verbosity.quiet, max_examples=1, min_satisfying_examples=0, database=self.database, max_shrinks=mshr, ): @given( strat, random=r, ) def test(x): assert False try: test() except AssertionError: pass @rule(strat=strategies, r=randoms(), p=floats(0, 1), mex=integers(1, 10), mshr=integers(1, 100)) def find_weird_failure(self, strat, r, mex, p, mshr): with Settings( verbosity=Verbosity.quiet, max_examples=mex, min_satisfying_examples=0, database=self.database, max_shrinks=mshr, ): @given( strat, random=r, ) def test(x): assert Random(hashlib.md5( show(x).encode(u'utf-8')).digest()).random() <= p try: test() except AssertionError: pass @rule(target=strats_with_parameters, strat=strategies, r=randoms()) def draw_parameter(self, strat, r): return (strat, strat.draw_parameter(r)) @rule(target=strats_with_templates, sp=strats_with_parameters, r=randoms()) def draw_template(self, sp, r): strat, param = sp return (strat, strat.draw_template(r, param)) @rule(target=strats_with_2_templates, sp=strats_with_parameters, r=randoms()) def draw_templates(self, sp, r): strat, param = sp return ( strat, strat.draw_template(r, param), strat.draw_template(r, param), ) @rule(st=strats_with_templates) def check_serialization(self, st): strat, template = st as_basic = strat.to_basic(template) assert show(strat.reify(template)) == show( strat.reify(strat.from_basic(as_basic))) assert as_basic == strat.to_basic(strat.from_basic(as_basic)) @rule(target=strategies, spec=sampled_from(( integers(), booleans(), floats(), complex_numbers(), fractions(), decimals(), text(), binary(), none(), StateMachineSearchStrategy(), tuples(), ))) def strategy(self, spec): return spec @rule(target=strategies, values=lists(integers() | text(), min_size=1)) def sampled_from_strategy(self, values): return sampled_from(values) @rule(target=strategies, spec=strategy_tuples) def strategy_for_tupes(self, spec): return tuples(*spec) @rule(target=strategies, source=strategies, level=integers(1, 10), mixer=text()) def filtered_strategy(s, source, level, mixer): def is_good(x): return bool( Random( hashlib.md5( (mixer + show(x)).encode(u'utf-8')).digest()).randint( 0, level)) return source.filter(is_good) @rule(target=strategies, elements=strategies) def list_strategy(self, elements): return lists(elements, average_size=AVERAGE_LIST_LENGTH) @rule(target=strategies, l=strategies, r=strategies) def or_strategy(self, l, r): return l | r @rule(target=strategies, source=strategies, result=strategies, mixer=text()) def mapped_strategy(self, source, result, mixer): cache = {} def do_map(value): rep = show(value) try: return deepcopy(cache[rep]) except KeyError: pass random = Random( hashlib.md5((mixer + rep).encode(u'utf-8')).digest()) outcome_template = result.draw_and_produce(random) cache[rep] = result.reify(outcome_template) return deepcopy(cache[rep]) return source.map(do_map) @rule(target=varied_floats, source=floats()) def float(self, source): return source @rule(target=varied_floats, source=varied_floats, offset=integers(-100, 100)) def adjust_float(self, source, offset): return int_to_float(clamp(0, float_to_int(source) + offset, 2**64 - 1)) @rule(target=strategies, left=varied_floats, right=varied_floats) def float_range(self, left, right): for f in (math.isnan, math.isinf): for x in (left, right): assume(not f(x)) left, right = sorted((left, right)) assert left <= right return strategy(floats(left, right)) @rule(target=strategies, source=strategies, result1=strategies, result2=strategies, mixer=text(), p=floats(0, 1)) def flatmapped_strategy(self, source, result1, result2, mixer, p): assume(result1 is not result2) def do_map(value): rep = show(value) random = Random( hashlib.md5((mixer + rep).encode(u'utf-8')).digest()) if random.random() <= p: return result1 else: return result2 return source.flatmap(do_map) @rule(target=strategies, value=objects) def just_strategy(self, value): return strategy(just(value)) @rule(target=strategy_tuples, source=strategies) def single_tuple(self, source): return (source, ) @rule(target=strategy_tuples, l=strategy_tuples, r=strategy_tuples) def cat_tuples(self, l, r): return l + r @rule(target=objects, strat=strategies) def get_example(self, strat): try: strat.example() except NoExamples: # Because of filtering some strategies we look for don't actually # have any examples. pass @rule(target=strategies, left=integers(), right=integers()) def integer_range(self, left, right): left, right = sorted((left, right)) return strategy(integers(left, right)) @rule(strat=strategies) def repr_is_good(self, strat): assert u' at 0x' not in repr(strat) @rule(strat=strategies) def template_upper_bound_is_valid(self, strat): ub = strat.template_upper_bound assert ub >= 0 if isinstance(ub, float): assert math.isinf(ub) else: assert isinstance(ub, int) @rule(strat=strategies, r=randoms()) def can_find_as_many_templates_as_size(self, strat, r): tempstrat = templates_for(strat) n = min(10, strat.template_upper_bound) found = [] with Settings(verbosity=Verbosity.quiet, timeout=2.0): for i in range(n): try: x = find( tempstrat, lambda t: t not in found, random=r, ) except: print(u'Exception at %d/%d. template_upper_bound=%r' % (i, n, strat.template_upper_bound)) raise found.append(x)
frozensets(frozensets(integers(), max_size=2))) TestMisc1 = strategy_test_suite(fixed_dictionaries( {(2, -374): frozensets(none())})) TestMisc2 = strategy_test_suite(fixed_dictionaries( {b'': frozensets(integers())})) TestMisc3 = strategy_test_suite(tuples(sets(none() | text()))) TestEmptyTuple = strategy_test_suite(tuples()) TestEmptyList = strategy_test_suite(lists(max_size=0)) TestEmptySet = strategy_test_suite(sets(max_size=0)) TestEmptyFrozenSet = strategy_test_suite(frozensets(max_size=0)) TestEmptyDict = strategy_test_suite(fixed_dictionaries({})) TestDecimal = strategy_test_suite(decimals()) TestFraction = strategy_test_suite(fractions()) TestNonEmptyLists = strategy_test_suite( lists(integers(), average_size=5.0).filter(bool) ) TestNoneLists = strategy_test_suite(lists(none(), average_size=5.0)) TestConstantLists = strategy_test_suite( integers().flatmap(lambda i: lists(just(i), average_size=5.0)) ) TestListsWithUniqueness = strategy_test_suite( lists( lists(integers(), average_size=5.0), average_size=5.0,
from generic_testing_test_context import generic_testing @generic_testing.Given({generic_testing.ClassUnderTest: st.integers()}) class Test_int(generic_testing.intTests): pass FRACTIONS_RANGE = 10000000000 @generic_testing.Given({ generic_testing.ClassUnderTest: st.fractions( min_value=fractions.Fraction(-FRACTIONS_RANGE), max_value=fractions.Fraction(FRACTIONS_RANGE), max_denominator=FRACTIONS_RANGE, ) }) class Test_Fraction(generic_testing.FractionTests): pass FLOATS_RANGE = 1e30 @generic_testing.Given({ generic_testing.ClassUnderTest: st.floats(min_value=-FLOATS_RANGE, max_value=FLOATS_RANGE) }) class Test_float(generic_testing.floatTests):
def test_fractions(): assert minimal(ds.fractions(), lambda f: f >= 1) == 1
not hasattr(inspect, "getfullargspec"), reason="inspect.getfullargspec only exists under Python 3", ) def test_inspection_compat(): assert getfullargspec is inspect.getfullargspec @pytest.mark.skipif( not hasattr(inspect, "FullArgSpec"), reason="inspect.FullArgSpec only exists under Python 3", ) def test_inspection_result_compat(): assert FullArgSpec is inspect.FullArgSpec @given(st.fractions()) def test_ceil(x): """The compat ceil function always has the Python 3 semantics. Under Python 2, math.ceil returns a float, which cannot represent large integers - for example, `float(2**53) == float(2**53 + 1)` - and this is obviously incorrect for unlimited-precision integer operations. """ assert isinstance(ceil(x), integer_types) assert x <= ceil(x) < x + 1 @given(st.fractions()) def test_floor(x): assert isinstance(floor(x), integer_types) assert x - 1 < floor(x) <= x
def test_minimal_fractions_4(): assert minimal( lists(fractions()), lambda s: len(s) >= 20 and all(t >= 1 for t in s)) == [Fraction(1)] * 20
sampled_from(('a', 'b', 'c')), integers(), integers(min_value=3), integers(min_value=(-2 ** 32), max_value=(2 ** 64)), floats(), floats(min_value=-2.0, max_value=3.0), floats(), floats(min_value=-2.0), floats(), floats(max_value=-0.0), floats(), floats(min_value=0.0), floats(min_value=3.14, max_value=3.14), text(), binary(), booleans(), tuples(booleans(), booleans()), frozensets(integers()), sets(frozensets(booleans())), complex_numbers(), fractions(), decimals(), lists(lists(booleans(), average_size=10), average_size=10), lists(lists(booleans(), average_size=100)), lists(floats(0.0, 0.0), average_size=1.0), ordered_pair, constant_list(integers()), integers().filter(lambda x: abs(x) > 100), floats(min_value=-sys.float_info.max, max_value=sys.float_info.max), none(), randoms(), booleans().flatmap(lambda x: booleans() if x else complex_numbers()), recursive( base=booleans(), extend=lambda x: lists(x, max_size=3), max_leaves=10, ) ]
def test_too_small_to_be_useful_coin(): assert not cu.biased_coin(ConjectureData.for_buffer([1]), 0.5**65) @example([Fraction(1, 3), Fraction(1, 3), Fraction(1, 3)]) @example([Fraction(1, 1), Fraction(1, 2)]) @example([Fraction(1, 2), Fraction(4, 10)]) @example([Fraction(1, 1), Fraction(3, 5), Fraction(1, 1)]) @example([Fraction(2, 257), Fraction(2, 5), Fraction(1, 11)]) @example([0, 2, 47]) @settings( deadline=None, suppress_health_check=HealthCheck.all(), phases=[Phase.explicit] if IN_COVERAGE_TESTS else settings.default.phases, ) @given(st.lists(st.fractions(min_value=0, max_value=1), min_size=1)) def test_sampler_distribution(weights): total = sum(weights) n = len(weights) assume(total > 0) probabilities = [w / total for w in weights] sampler = cu.Sampler(weights) calculated = [Fraction(0)] * n for base, alternate, p_alternate in sampler.table: calculated[base] += (1 - p_alternate) / n calculated[alternate] += p_alternate / n
frozensets(frozensets(integers(), max_size=2))) TestMisc1 = strategy_test_suite(fixed_dictionaries( {(2, -374): frozensets(none())})) TestMisc2 = strategy_test_suite(fixed_dictionaries( {b'': frozensets(integers())})) TestMisc3 = strategy_test_suite(tuples(sets(none() | text()))) TestEmptyTuple = strategy_test_suite(tuples()) TestEmptyList = strategy_test_suite(lists(max_size=0)) TestEmptySet = strategy_test_suite(sets(max_size=0)) TestEmptyFrozenSet = strategy_test_suite(frozensets(max_size=0)) TestEmptyDict = strategy_test_suite(fixed_dictionaries({})) TestDecimal = strategy_test_suite(decimals()) TestFraction = strategy_test_suite(fractions()) TestNonEmptyLists = strategy_test_suite( lists(integers()).filter(bool) ) TestNoneLists = strategy_test_suite(lists(none())) TestConstantLists = strategy_test_suite( integers().flatmap(lambda i: lists(just(i))) ) TestListsWithUniqueness = strategy_test_suite( lists(lists(integers()), unique_by=lambda x: tuple(sorted(x)))) TestOrderedPairs = strategy_test_suite(
def test_fractions(): assert find(ds.fractions(), lambda f: f >= 1) == 1
""" from __future__ import print_function from functools import wraps import logging from hypothesis import given, strategies as st, settings, Verbosity from gc import collect as gc import traceback import sys from time import time from stricttuple import stricttuple __all__ = 'battle_tested', 'fuzz', 'disable_traceback', 'enable_traceback', 'garbage', 'crash_map', 'success_map', 'results', 'stats', 'print_stats' garbage = (st.binary(), st.booleans(), st.characters(), st.complex_numbers(), st.decimals(), st.floats(), st.fractions(), st.integers(), st.none(), st.random_module(), st.randoms(), st.text(), st.tuples(), st.uuids(), st.dictionaries(keys=st.text(), values=st.text())) garbage += ( # iterables st.lists(elements=st.one_of(*garbage)), st.iterables(elements=st.one_of(*garbage)), st.dictionaries(keys=st.text(), values=st.one_of(*garbage))) garbage = st.one_of(*garbage) def is_py3(): return sys.version_info >= (3, 0) class tb_controls():
if empty or not strategies: # pragma: no cover raise ResolutionFailed( "Could not resolve %s to a strategy; consider using " "register_type_strategy" % (empty or thing,) ) return st.one_of(strategies) _global_type_lookup = { # Types with core Hypothesis strategies type(None): st.none(), bool: st.booleans(), int: st.integers(), float: st.floats(), complex: st.complex_numbers(), fractions.Fraction: st.fractions(), decimal.Decimal: st.decimals(), text_type: st.text(), binary_type: st.binary(), datetime.datetime: st.datetimes(), datetime.date: st.dates(), datetime.time: st.times(), datetime.timedelta: st.timedeltas(), uuid.UUID: st.uuids(), tuple: st.builds(tuple), list: st.builds(list), set: st.builds(set), frozenset: st.builds(frozenset), dict: st.builds(dict), type(lambda: None): st.functions(), # Built-in types
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # # Red Hat Author(s): Anne Mulhern <*****@*****.**> """ Utilities for testing. """ from hypothesis import strategies from justbytes import Size from justbytes import UNITS NUMBERS_STRATEGY = strategies.one_of( strategies.integers(), strategies.fractions(), strategies.decimals().filter(lambda x: x.is_finite()), ) SIZE_STRATEGY = strategies.builds( Size, strategies.one_of( NUMBERS_STRATEGY, strategies.builds( str, NUMBERS_STRATEGY ) ), strategies.sampled_from(UNITS()) )
def test_minimal_fractions_1(): assert minimal(fractions()) == Fraction(0)
def test_minimal_fractions_2(): assert minimal(fractions(), lambda x: x >= 1) == Fraction(1)
def test_minimal_fractions_3(): assert minimal( lists(fractions()), lambda s: len(s) >= 20) == [Fraction(0)] * 20
empty = ', '.join(repr(s) for s in strategies if s.is_empty) if empty or not strategies: # pragma: no cover raise ResolutionFailed( 'Could not resolve %s to a strategy; consider using ' 'register_type_strategy' % (empty or thing,)) return st.one_of(strategies) _global_type_lookup = { # Types with core Hypothesis strategies type(None): st.none(), bool: st.booleans(), int: st.integers(), float: st.floats(), complex: st.complex_numbers(), fractions.Fraction: st.fractions(), decimal.Decimal: st.decimals(), text_type: st.text(), bytes: st.binary(), datetime.datetime: st.datetimes(), datetime.date: st.dates(), datetime.time: st.times(), datetime.timedelta: st.timedeltas(), uuid.UUID: st.uuids(), tuple: st.builds(tuple), list: st.builds(list), set: st.builds(set), frozenset: st.builds(frozenset), dict: st.builds(dict), # Built-in types type: st.sampled_from([type(None), bool, int, str, list, set, dict]),
# # Most of this work is copyright (C) 2013-2015 David R. MacIver # ([email protected]), but it contains contributions by others. See # https://github.com/DRMacIver/hypothesis/blob/master/CONTRIBUTING.rst for a # full list of people who may hold copyright, and consult the git log if you # need to determine who owns an individual contribution. # # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. # # END HEADER from __future__ import division, print_function, absolute_import from hypothesis import given, assume from tests.common.utils import fails from hypothesis.strategies import decimals, fractions, float_to_decimal @fails @given(decimals()) def test_all_decimals_can_be_exact_floats(x): assume(x.is_finite()) assert float_to_decimal(float(x)) == x @given(fractions(), fractions(), fractions()) def test_fraction_addition_is_well_behaved(x, y, z): assert x + y + z == y + x + z
def ply_fractions(draw): return F(draw(hys.fractions(max_denominator=101)))
] empty = ', '.join(repr(s) for s in strategies if s.is_empty) if empty or not strategies: # pragma: no cover raise ResolutionFailed( 'Could not resolve %s to a strategy; consider using ' 'register_type_strategy' % (empty or thing, )) return st.one_of(strategies) _global_type_lookup = { # Types with core Hypothesis strategies type(None): st.none(), bool: st.booleans(), float: st.floats(), complex: st.complex_numbers(), fractions.Fraction: st.fractions(), decimal.Decimal: st.decimals(), text_type: st.text(), bytes: st.binary(), datetime.datetime: st.datetimes(), datetime.date: st.dates(), datetime.time: st.times(), datetime.timedelta: st.timedeltas(), uuid.UUID: st.uuids(), tuple: st.builds(tuple), list: st.builds(list), set: st.builds(set), frozenset: st.builds(frozenset), dict: st.builds(dict), # Built-in types type: st.sampled_from([type(None), bool, int, str, list, set, dict]),
# would have to decide on arbitrary collection elements, and we'd rather # not (with typing module generic types and some builtins as exceptions). _global_type_lookup: typing.Dict[type, typing.Union[ st.SearchStrategy, typing.Callable[[type], st.SearchStrategy]]] = { type(None): st.none(), bool: st.booleans(), int: st.integers(), float: st.floats(), complex: st.complex_numbers(), fractions.Fraction: st.fractions(), decimal.Decimal: st.decimals(), str: st.text(), bytes: st.binary(), datetime.datetime: st.datetimes(), datetime.date: st.dates(), datetime.time: st.times(), datetime.timedelta: st.timedeltas(), datetime.timezone:
max_size=MAX_ITEM_BYTES ) ddb_string_set = sets(ddb_string, min_size=1) def _ddb_fraction_to_decimal(val): """Hypothesis does not support providing a custom Context, so working around that.""" return Decimal(val.numerator) / Decimal(val.denominator) def _negative(val): return val * Decimal('-1') ddb_positive_numbers = fractions( min_value=_MIN_NUMBER, max_value=_MAX_NUMBER ).map(_ddb_fraction_to_decimal) ddb_negative_numbers = ddb_positive_numbers.map(_negative) ddb_number = ddb_negative_numbers | just(Decimal('0')) | ddb_positive_numbers ddb_number_set = sets(ddb_number, min_size=1) ddb_binary = binary(min_size=1, max_size=MAX_ITEM_BYTES).map(Binary) ddb_binary_set = sets(ddb_binary, min_size=1) ddb_boolean = booleans() ddb_null = none() ddb_scalar_types = ( ddb_string | ddb_number |