class TestComplementaryIntervals(unittest.TestCase): @given(spaced_ranges(min_num_ranges=1, max_num_ranges=10, min_interval=0, max_interval=10)) def test_contiguous(self, intervals): complements = complementary_intervals(intervals) interleaved = list(roundrobin(complements, intervals)) self.assertTrue(intervals_are_contiguous(interleaved)) @given(spaced_ranges(min_num_ranges=1, max_num_ranges=10, min_interval=0, max_interval=10), integers_in_range(0, 10)) def test_contiguous_with_offset_start(self, intervals, start_offset): first_interval_start = intervals[0].start start_index = first_interval_start - start_offset complements = list(complementary_intervals(intervals, start=start_index)) self.assertEqual(complements[0], range(start_index, first_interval_start)) @given(spaced_ranges(min_num_ranges=1, max_num_ranges=10, min_interval=0, max_interval=10), integers_in_range(0, 10)) @example(intervals=[range(0, 0)], end_offset=1) def test_contiguous_with_offset_end(self, intervals, end_offset): last_interval_end = intervals[-1].stop end_index = last_interval_end + end_offset complements = list(complementary_intervals(intervals, stop=end_index)) self.assertEqual(complements[-1], range(last_interval_end, end_index))
def multiline_ascii_encodable_text(min_num_lines, max_num_lines): """A Hypothesis strategy to produce a multiline Unicode string. Args: min_num_lines: The minimum number of lines in the produced strings. max_num_lines: The maximum number of lines in the produced strings. Returns: A strategy for generating Unicode strings containing only newlines and characters which are encodable as printable 7-bit ASCII characters. """ return strategy(integers_in_range(min_num_lines, max_num_lines)) \ .flatmap(lambda n: ([integers_in_range(*PRINTABLE_ASCII_RANGE)],) * n) \ .map(lambda xs: '\n'.join(bytes(x).decode('ascii') for x in xs))
def spaced_ranges(min_num_ranges, max_num_ranges, min_interval, max_interval): """A Hypothesis strategy to produce separated, non-overlapping ranges. Args: min_num_ranges: The minimum number of ranges to produce. TODO: Correct? max_num_ranges: The maximum number of ranges to produce. min_interval: The minimum interval used for the lengths of the alternating ranges and spaces. max_interval: The maximum interval used for the lengths of the alternating ranges and spaces. """ return strategy(integers_in_range(min_num_ranges, max_num_ranges)) \ .map(lambda n: 2*n) \ .flatmap(lambda n: (integers_in_range(min_interval, max_interval),) * n) \ .map(list).map(lambda lst: list(accumulate(lst))) \ .map(lambda lst: list(batched(lst, 2))) \ .map(lambda pairs: list(starmap(range, pairs)))
def model_to_base_specifier(model): import hypothesis.extra.fakefactory as ff from hypothesis.extra.datetime import timezone_aware_datetime mappings = { dm.SmallIntegerField: integers_in_range(-32768, 32767), dm.IntegerField: integers_in_range(-2147483648, 2147483647), dm.BigIntegerField: integers_in_range(-9223372036854775808, 9223372036854775807), dm.PositiveIntegerField: integers_in_range(0, 2147483647), dm.PositiveSmallIntegerField: integers_in_range(0, 32767), dm.BinaryField: binary_type, dm.BooleanField: bool, dm.CharField: text_type, dm.DateTimeField: timezone_aware_datetime, dm.EmailField: ff.FakeFactory('email'), dm.FloatField: float, dm.NullBooleanField: one_of((None, bool)), } result = {} for f in model._meta.concrete_fields: if isinstance(f, dm.AutoField): continue try: mapped = mappings[type(f)] except KeyError: if isinstance(f, dm.ForeignKey): mapped = f.rel.to if model in referenced_models(mapped): if f.null: continue else: raise ModelNotSupported(( 'non-nullable cycle starting %s -> %s. This is ' 'currently not supported.' ) % (model.__name__, mapped.__name__)) elif f.null: continue else: raise ModelNotSupported(( 'No mapping defined for field type %s and %s is not ' 'nullable') % ( type(f).__name__, f.name )) if f.null: mapped = one_of((None, mapped)) result[f.name] = mapped return result
def header(header_class, **kwargs): """Create a strategy for producing headers of a specific class. Args: header_class: The type of header to be produced. This class will be introspected to determine suitable strategies for each named field. **kwargs: Any supplied keyword arguments can be used to fix the value of particular header fields. """ field_strategies = {} for field_name in header_class.ordered_field_names(): if field_name in kwargs: field_strategy = just(kwargs.pop(field_name)) else: value_type = getattr(header_class, field_name).value_type field_strategy = integers_in_range(value_type.MINIMUM, value_type.MAXIMUM) field_strategies[field_name] = field_strategy if len(kwargs) > 0: raise TypeError("Unrecognised binary header field names {} for {}".format( ', '.join(kwargs.keys()), header_class.__name__)) return strategy(field_strategies).map(lambda kw: header_class(**kw))
def header(header_class, **kwargs): """Create a strategy for producing headers of a specific class. Args: header_class: The type of header to be produced. This class will be introspected to determine suitable strategies for each named field. **kwargs: Any supplied keyword arguments can be used to fix the value of particular header fields. """ field_strategies = {} for field_name in header_class.ordered_field_names(): if field_name in kwargs: field_strategy = just(kwargs.pop(field_name)) else: value_type = getattr(header_class, field_name).value_type field_strategy = integers_in_range(value_type.MINIMUM, value_type.MAXIMUM) field_strategies[field_name] = field_strategy if len(kwargs) > 0: raise TypeError( "Unrecognised binary header field names {} for {}".format( ', '.join(kwargs.keys()), header_class.__name__)) return strategy(field_strategies).map(lambda kw: header_class(**kw))
def test_tuple_strategy_too_large_to_fit(): x = frozenset({specifiers.integers_in_range(0, 30)}) assert not math.isinf(strategy(x).size_lower_bound) for _ in hrange(8): x = (x, x) assert math.isinf( strategy((int, x)).size_lower_bound)
def test_minimize_multiple_elements_in_silly_large_int_range_min_is_not_dupe(): ir = integers_in_range(0, 2**256) target = list(range(20)) x = minimal([ir], lambda x: (assume(len(x) >= 20) and all(x[i] >= target[i] for i in target))) assert x == target
def test_two_incompatible_unreified_templates(): r = Random(1) strat = strategy(Bitfields).flatmap(lambda x: integers_in_range(0, x)) x = some_template(strat, r) y = some_template(strat, r) assert x.source_template != y.source_template assert not strat.strictly_simpler(x, y) assert not strat.strictly_simpler(y, x)
def test_minimize_sets_of_sets(): elements = integers_in_range(1, 100) size = 15 set_of_sets = minimal({frozenset({elements})}, lambda s: len(s) >= size) assert frozenset() in set_of_sets assert len(set_of_sets) == size for s in set_of_sets: if len(s) > 1: assert any(s != t and t.issubset(s) for t in set_of_sets)
def test_should_not_count_duplicates_towards_max_examples(): seen = set() @given(integers_in_range(1, 10), settings=hs.Settings( max_examples=9 )) def test_i_see_you(x): seen.add(x) test_i_see_you() assert len(seen) == 9
def test_minimize_multiple_elements_in_silly_large_int_range_min_is_not_dupe(): ir = integers_in_range(0, 2 ** 256) target = list(range(20)) x = minimal( [ir], lambda x: ( assume(len(x) >= 20) and all(x[i] >= target[i] for i in target)) ) assert x == target
def dtype_strategy(dtype, settings): if dtype.kind == 'b': result = bool elif dtype.kind == 'f': result = float elif dtype.kind == 'c': result = complex elif dtype.kind in ('S', 'a', 'V'): result = binary_type elif dtype.kind == 'u': result = integers_in_range(0, 1 << (4 * dtype.itemsize) - 1) elif dtype.kind == 'i': min_integer = -1 << (4 * dtype.itemsize - 1) result = integers_in_range(min_integer, -min_integer - 1) elif dtype.kind == 'U': result = text_type else: raise NotImplementedError( 'No strategy implementation for %r' % (dtype,) ) return strategy(result, settings).map(dtype.type)
class TestBatched(unittest.TestCase): @given([int], integers_in_range(1, 1000)) def test_batch_sizes_unpadded(self, items, batch_size): assume(batch_size > 0) batches = list(batched(items, batch_size)) self.assertTrue(all(len(batch) == batch_size for batch in batches[:-1])) @given([int], integers_in_range(1, 1000)) def test_final_batch_sizes(self, items, batch_size): assume(len(items) > 0) assume(batch_size > 0) batches = list(batched(items, batch_size)) self.assertTrue(len(batches[-1]) <= batch_size) @given([int], integers_in_range(1, 1000), int) def test_batch_sizes_padded(self, items, batch_size, pad): assume(batch_size > 0) batches = list(batched(items, batch_size, padding=pad)) self.assertTrue(all(len(batch) == batch_size for batch in batches)) @given([int], integers_in_range(1, 1000), int) def test_pad_contents(self, items, batch_size, pad): assume(len(items) > 0) assume(0 < batch_size < 1000) num_left_over = len(items) % batch_size pad_length = batch_size - num_left_over if num_left_over != 0 else 0 assume(pad_length != 0) batches = list(batched(items, batch_size, padding=pad)) self.assertEqual(batches[-1][batch_size - pad_length:], [pad] * pad_length) def test_pad(self): batches = list(batched([0, 0], 3, 42)) self.assertEqual(batches[-1], [0, 0, 42])
def test_minimize_sets_of_sets(): elements = integers_in_range(1, 100) size = 15 set_of_sets = minimal( {frozenset({elements})}, lambda s: len(s) >= size ) assert frozenset() in set_of_sets assert len(set_of_sets) == size for s in set_of_sets: if len(s) > 1: assert any( s != t and t.issubset(s) for t in set_of_sets )
def test_minimize_multiple_elements_in_silly_large_int_range(): desired_result = [-(2**255)] * 20 def condition(x): assume(len(x) >= 20) return all(t >= -(2**255) for t in x) ir = integers_in_range(-(2**256), 2**256) x = minimal( [ir], condition, # This is quite hard and I don't yet have a good solution for # making it less so, so this one gets a higher timeout. timeout_after=20, ) assert x == desired_result
def test_minimize_multiple_elements_in_silly_large_int_range(): desired_result = [-(2 ** 255)] * 20 def condition(x): assume(len(x) >= 20) return all(t >= -(2 ** 255) for t in x) ir = integers_in_range(-(2 ** 256), 2 ** 256) x = minimal( [ir], condition, # This is quite hard and I don't yet have a good solution for # making it less so, so this one gets a higher timeout. timeout_after=20, ) assert x == desired_result
frozenset(), {}, NAryTree(bool, bool, bool), ABC(bool, bool, bool), ABC(bool, bool, int), { 'a': int, 'b': bool }, one_of((int, (bool, ))), sampled_from(range(10)), one_of((just('a'), just('b'), just('c'))), sampled_from(('a', 'b', 'c')), int, integers_from(3), integers_in_range(-2**32, 2**64), float, floats_in_range(-2.0, 3.0), text_type, binary_type, bool, (bool, bool), frozenset({int}), complex, Fraction, Decimal, [[bool]], OrderedPair, ConstantList(int), strategy(streaming(int)).map(lambda x: list(x[:2]) and x), strategy(int).filter(lambda x: abs(x) > 100),
def test_minimize_single_element_in_silly_large_int_range(): ir = integers_in_range(-(2**256), 2**256) assert minimal(ir, lambda x: x >= -(2**255)) == -(2**255)
from hypothesis import assume, given from hypothesis.specifiers import integers_in_range from myhdl import Signal, intbv from uhdl import Sig width = integers_in_range(2, 100) def check_sigs(expected, *sigs): __tracebackhide__ = True for s in sigs: assert expected == s assert len(expected) == len(s) @given(bool) def test_bool(x): check_sigs(Signal(x), Sig(x)) @given(width) def test_only_width(x): check_sigs(Signal(intbv()[x:]), Sig(w=x)) @given(int, width) def test_width_and_initial_value(val, width): check_sigs(Signal(intbv(val)[width:]), Sig(val, width), Sig(val, w=width), Sig(val=val, w=width))
assert x == 42 @fails @given(text_type, text_type) def test_text_addition_is_not_commutative(x, y): assert x + y == y + x @fails @given(binary_type, binary_type) def test_binary_addition_is_not_commutative(x, y): assert x + y == y + x @given(integers_in_range(1, 10)) def test_integers_are_in_range(x): assert 1 <= x <= 10 @given(integers_from(100)) def test_integers_from_are_from(x): assert x >= 100 def test_does_not_catch_interrupt_during_falsify(): calls = [0] @given(int) def flaky_base_exception(x): if not calls[0]:
def test_large_enough_integer_ranges_are_infinite(): assert math.isinf( strategy(specifiers.integers_in_range(1, 2 ** 64)).size_lower_bound)
# END HEADER from __future__ import division, print_function, absolute_import, \ unicode_literals from random import Random from collections import namedtuple from hypothesis.specifiers import just, one_of, sampled_from, \ floats_in_range, integers_in_range from tests.common.specifiers import Descriptor, DescriptorWithValue from hypothesis.strategytests import TemplatesFor, strategy_test_suite from hypothesis.internal.compat import text_type, binary_type from hypothesis.searchstrategy.narytree import NAryTree TestIntegerRange = strategy_test_suite(integers_in_range(0, 5)) TestFloatRange = strategy_test_suite(floats_in_range(0.5, 10)) TestSampled = strategy_test_suite(sampled_from(elements=(1, 2, 3))) TestOneOf = strategy_test_suite(one_of((int, int, bool))) TestOneOfSameType = strategy_test_suite( one_of((integers_in_range(1, 10), integers_in_range(8, 15))) ) TestRandom = strategy_test_suite(Random) TestInts = strategy_test_suite(int) TestBoolLists = strategy_test_suite([bool]) TestString = strategy_test_suite(text_type) BinaryString = strategy_test_suite(binary_type) TestIntBool = strategy_test_suite((int, bool)) TestFloats = strategy_test_suite(float) TestComplex = strategy_test_suite(complex)
def test_minimizes_integer_range_to_boundary(boundary): assert find(integers_in_range(boundary, boundary + 100), lambda x: True) == boundary
def test_find_small_number_in_large_range(): assert find(integers_in_range((-2**32), 2**32), lambda x: x >= 101) == 101
def test_one_of_strategy_goes_infinite(): x = strategy(specifiers.integers_in_range(0, 2 ** 32 - 2)) assert not math.isinf(x.size_lower_bound) for _ in hrange(10): x |= x assert math.isinf(x.size_lower_bound)
# END HEADER from __future__ import division, print_function, absolute_import, \ unicode_literals from random import Random import pytest from hypothesis import Settings, given, assume, strategy from hypothesis.database import ExampleDatabase from hypothesis.specifiers import just, floats_in_range, integers_in_range from hypothesis.searchstrategy.strategies import BuildContext ConstantLists = strategy(int).flatmap(lambda i: [just(i)]) OrderedPairs = strategy(integers_in_range(1, 200)).flatmap( lambda e: (integers_in_range(0, e - 1), just(e)) ) with Settings(max_examples=200): @given(ConstantLists) def test_constant_lists_are_constant(x): assume(len(x) >= 3) assert len(set(x)) == 1 @given(OrderedPairs) def test_in_order(x): assert x[0] < x[1] def test_flatmap_retrieve_from_db():
class TestPowerHungry(unittest.TestCase): @given(st.lists(sp.integers_in_range(-1000, 1000))) def test_answer_hypothesis(self, xs): assume(xs) assume(len(xs) <= 50) print(xs) self.assertEqual(answer(xs), answer4(xs)) def test_answer(self): # Example cases self.assertEqual(answer([2, -3, 1, 0, -5]), '30') self.assertEqual(answer([2, 0, 2, 2, 0]), '8') self.assertEqual(answer([-2, -3, 4, -5]), '60') # My cases self.assertEqual(answer([0, 0, -1]), '0') self.assertEqual(answer([0]), '0') self.assertEqual(answer([1]), '1') self.assertEqual(answer([-1]), '-1') self.assertEqual(answer([50]), '50') self.assertEqual(answer([-50]), '-50') self.assertEqual(answer([1000]), '1000') self.assertEqual(answer([-1000]), '-1000') self.assertEqual(answer([0, 0, 0]), '0') self.assertEqual(answer([1, 1, 1]), '1') self.assertEqual(answer([0, -5]), '0') self.assertEqual(answer([0, -5, -6]), '30') self.assertEqual(answer([0, -5, -6, -10]), '60') self.assertEqual(answer([-1, 7]), '7') self.assertEqual(answer([-1, -1, 7]), '7') self.assertEqual(answer([0, -1, 7]), '7') self.assertEqual(answer([0, 5]), '5') self.assertEqual(answer([-2, -2]), '4') self.assertEqual(answer([-2, -2, -2]), '4') self.assertEqual(answer([2, -2, 2]), '4') self.assertEqual(answer([-2, 2, -2]), '8') self.assertEqual(answer([-3, -2, 4, -5]), '60') self.assertEqual(answer([-3, 4, -5, -2]), '60') self.assertEqual(answer([-1, 1, -1, 1, -1, 1]), '1') self.assertEqual(answer([1000, 500, 1, 5]), '2500000') self.assertEqual(answer([1, 500, 1000, -5]), '500000') self.assertEqual(answer([-5, 1, 500, 1000]), '500000') self.assertEqual( answer([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50 ]), '30414093201713378043612608166064768844377641568960512000000000000' ) self.assertEqual( answer([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, -50 ]), '608281864034267560872252163321295376887552831379210240000000000') self.assertEqual( answer([ 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000 ]), '1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' ) self.assertEqual( answer([ -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000 ]), '1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' )
class TestIBMFloat(unittest.TestCase): def test_zero_from_float(self): zero = IBMFloat.from_float(0.0) self.assertTrue(zero.is_zero()) def test_zero_from_bytes(self): zero = IBMFloat.from_bytes(b'\x00\x00\x00\x00') self.assertTrue(zero.is_zero()) def test_subnormal(self): ibm = IBMFloat.from_float(1.6472184286297693e-83) self.assertTrue(ibm.is_subnormal()) def test_smallest_subnormal(self): ibm = IBMFloat.from_float(5.147557589468029e-85) self.assertEqual(bytes(ibm), bytes((0x00, 0x00, 0x00, 0x01))) def test_too_small_subnormal(self): with self.assertRaises(FloatingPointError): IBMFloat.from_float(1e-86) def test_nan(self): with self.assertRaises(ValueError): IBMFloat.from_float(float('nan')) def test_inf(self): with self.assertRaises(ValueError): IBMFloat.from_float(float('inf')) def test_too_large(self): with self.assertRaises(OverflowError): IBMFloat.from_float(MAX_IBM_FLOAT * 10) def test_too_small(self): with self.assertRaises(OverflowError): IBMFloat.from_float(MIN_IBM_FLOAT * 10) @given(floats_in_range(MIN_IBM_FLOAT, MAX_IBM_FLOAT)) def test_bool(self, f): self.assertEqual(bool(IBMFloat.from_float(f)), bool(f)) @given(integers_in_range(0, 255), integers_in_range(0, 255), integers_in_range(0, 255), integers_in_range(0, 255)) def test_bytes_roundtrip(self, a, b, c, d): b = bytes((a, b, c, d)) ibm = IBMFloat.from_bytes(b) self.assertEqual(bytes(ibm), b) @given(floats_in_range(MIN_IBM_FLOAT, MAX_IBM_FLOAT)) def test_floats_roundtrip(self, f): ibm = IBMFloat.from_float(f) self.assertTrue(almost_equal(f, float(ibm), epsilon=EPSILON_IBM_FLOAT)) @given(integers_in_range(0, MAX_EXACT_INTEGER_IBM_FLOAT - 1), floats_in_range(0.0, 1.0)) def test_trunc_above_zero(self, i, f): assume(f != 1.0) ieee = i + f ibm = IBMFloat.from_float(ieee) self.assertEqual(trunc(ibm), i) @given(integers_in_range(MIN_EXACT_INTEGER_IBM_FLOAT + 1, 0), floats_in_range(0.0, 1.0)) def test_trunc_below_zero(self, i, f): assume(f != 1.0) ieee = i - f ibm = IBMFloat.from_float(ieee) self.assertEqual(trunc(ibm), i) @given( integers_in_range(MIN_EXACT_INTEGER_IBM_FLOAT, MAX_EXACT_INTEGER_IBM_FLOAT - 1), floats_in_range(0.0, 1.0)) def test_ceil(self, i, f): assume(f != 1.0) ieee = i + f ibm = IBMFloat.from_float(ieee) self.assertEqual(math.ceil(ibm), i + 1) @given( integers_in_range(MIN_EXACT_INTEGER_IBM_FLOAT, MAX_EXACT_INTEGER_IBM_FLOAT - 1), floats_in_range(0.0, 1.0)) def test_floor(self, i, f): assume(f != 1.0) ieee = i + f ibm = IBMFloat.from_float(ieee) self.assertEqual(math.floor(ibm), i) def test_normalise_subnormal_expect_failure(self): # This float has an base-16 exponent of -64 (the minimum) and cannot be normalised ibm = IBMFloat.from_float(1.6472184286297693e-83) assert ibm.is_subnormal() with self.assertRaises(FloatingPointError): ibm.normalize() def test_normalise_subnormal1(self): ibm = IBMFloat.from_bytes( (0b01000000, 0b00000000, 0b11111111, 0b00000000)) assert ibm.is_subnormal() normalized = ibm.normalize() self.assertFalse(normalized.is_subnormal()) def test_normalise_subnormal2(self): ibm = IBMFloat.from_bytes((64, 1, 0, 0)) assert ibm.is_subnormal() normalized = ibm.normalize() self.assertFalse(normalized.is_subnormal()) @given(integers_in_range(128, 255), integers_in_range(0, 255), integers_in_range(0, 255), integers_in_range(4, 23)) def test_normalise_subnormal(self, b, c, d, shift): mantissa = (b << 16) | (c << 8) | d assume(mantissa != 0) mantissa >>= shift assert mantissa != 0 sa = EXPONENT_BIAS sb = (mantissa >> 16) & 0xff sc = (mantissa >> 8) & 0xff sd = mantissa & 0xff ibm = IBMFloat.from_bytes((sa, sb, sc, sd)) assert ibm.is_subnormal() normalized = ibm.normalize() self.assertFalse(normalized.is_subnormal()) @given(integers_in_range(128, 255), integers_in_range(0, 255), integers_in_range(0, 255), integers_in_range(4, 23)) def test_zero_subnormal(self, b, c, d, shift): mantissa = (b << 16) | (c << 8) | d assume(mantissa != 0) mantissa >>= shift assert mantissa != 0 sa = EXPONENT_BIAS sb = (mantissa >> 16) & 0xff sc = (mantissa >> 8) & 0xff sd = mantissa & 0xff ibm = IBMFloat.from_bytes((sa, sb, sc, sd)) assert ibm.is_subnormal() z = ibm.zero_subnormal() self.assertTrue(z.is_zero()) @given(integers_in_range(0, 255), integers_in_range(0, 255), integers_in_range(0, 255), integers_in_range(0, 255)) def test_abs(self, a, b, c, d): ibm = IBMFloat.from_bytes((a, b, c, d)) abs_ibm = abs(ibm) self.assertGreaterEqual(abs_ibm.signbit, 0) @given(integers_in_range(0, 255), integers_in_range(0, 255), integers_in_range(0, 255), integers_in_range(0, 255)) def test_negate_non_zero(self, a, b, c, d): ibm = IBMFloat.from_bytes((a, b, c, d)) assume(not ibm.is_zero()) negated = -ibm self.assertNotEqual(ibm.signbit, negated.signbit) def test_negate_zero(self): zero = IBMFloat.from_float(0.0) negated = -zero self.assertTrue(negated.is_zero()) @given(floats_in_range(MIN_IBM_FLOAT, MAX_IBM_FLOAT)) def test_signbit(self, f): ltz = f < 0 ibm = IBMFloat.from_float(f) self.assertEqual(ltz, ibm.signbit) @given(floats_in_range(-1.0, +1.0), integers_in_range(-256, 255)) def test_ldexp_frexp(self, fraction, exponent): try: ibm = IBMFloat.ldexp(fraction, exponent) except OverflowError: assume(False) else: f, e = ibm.frexp() self.assertTrue( almost_equal(fraction * 2**exponent, f * 2**e, epsilon=EPSILON_IBM_FLOAT)) @given(floats_in_range(MIN_IBM_FLOAT, MAX_IBM_FLOAT), floats_in_range(0.0, 1.0)) def test_add(self, f, p): a = f * p b = f - a ibm_a = IBMFloat.from_float(a) ibm_b = IBMFloat.from_float(b) ibm_c = ibm_a + ibm_b ieee_a = float(ibm_a) ieee_b = float(ibm_b) ieee_c = ieee_a + ieee_b self.assertTrue( almost_equal(ieee_c, ibm_c, epsilon=EPSILON_IBM_FLOAT * 4)) @given(floats_in_range(0, MAX_IBM_FLOAT), floats_in_range(0, MAX_IBM_FLOAT)) def test_sub(self, a, b): ibm_a = IBMFloat.from_float(a) ibm_b = IBMFloat.from_float(b) ibm_c = ibm_a - ibm_b ieee_a = float(ibm_a) ieee_b = float(ibm_b) ieee_c = ieee_a - ieee_b self.assertTrue(almost_equal(ieee_c, ibm_c, epsilon=EPSILON_IBM_FLOAT))
def test_single_integer_range_is_range(): assert find(integers_in_range(1, 1), lambda x: True) == 1
ABC = namedtuple('ABC', ('a', 'b', 'c')) standard_types = [ Bitfields, EvalledIntStream, [], (), set(), frozenset(), {}, NAryTree(bool, bool, bool), ABC(bool, bool, bool), ABC(bool, bool, int), TemplatesFor(one_of(just(i) for i in hrange(10))), {'a': int, 'b': bool}, one_of((int, (bool,))), sampled_from(range(10)), one_of((just('a'), just('b'), just('c'))), sampled_from(('a', 'b', 'c')), int, integers_from(3), integers_in_range(-2 ** 32, 2 ** 64), float, floats_in_range(-2.0, 3.0), floats_in_range(3.14, 3.14), text_type, binary_type, bool, (bool, bool), frozenset({int}), complex, Fraction, Decimal, [[bool]], OrderedPair, ConstantList(int), strategy(streaming(int)).map(lambda x: list(x[:2]) and x), strategy(int).filter(lambda x: abs(x) > 100), floats_in_range(-sys.float_info.max, sys.float_info.max), None, Random,
def test_find_small_number_in_large_range(): assert find( integers_in_range((-2 ** 32), 2 ** 32), lambda x: x >= 101) == 101
from __future__ import division, print_function, absolute_import, \ unicode_literals from random import Random from decimal import Decimal from fractions import Fraction from collections import namedtuple from hypothesis.specifiers import just, one_of, sampled_from, \ integers_from, floats_in_range, integers_in_range from tests.common.specifiers import Descriptor, DescriptorWithValue from hypothesis.strategytests import TemplatesFor, strategy_test_suite from hypothesis.internal.compat import text_type, binary_type from hypothesis.searchstrategy.narytree import NAryTree TestIntegerRange = strategy_test_suite(integers_in_range(0, 5)) TestFloatRange = strategy_test_suite(floats_in_range(0.5, 10)) TestSampled = strategy_test_suite(sampled_from(elements=(1, 2, 3))) TestIntegersFrom = strategy_test_suite(integers_from(13)) TestOneOf = strategy_test_suite(one_of((int, int, bool))) TestOneOfSameType = strategy_test_suite( one_of((integers_in_range(1, 10), integers_in_range(8, 15))) ) TestRandom = strategy_test_suite(Random) TestInts = strategy_test_suite(int) TestBoolLists = strategy_test_suite([bool]) TestString = strategy_test_suite(text_type) BinaryString = strategy_test_suite(binary_type) TestIntBool = strategy_test_suite((int, bool))
class TestCatalogBuilder(unittest.TestCase): @given(dictionary(int, int)) def test_arbitrary_mapping(self, mapping): builder = CatalogBuilder(mapping) catalog = builder.create() shared_items = set(mapping.items()) & set(catalog.items()) self.assertEqual(len(shared_items), len(mapping)) @given(dictionary(int, just(42))) def test_constant_mapping(self, mapping): builder = CatalogBuilder(mapping) catalog = builder.create() shared_items = set(mapping.items()) & set(catalog.items()) self.assertEqual(len(shared_items), len(mapping)) @given(start=int, num=integers_in_range(0, 10000), step=integers_in_range(-10000, 10000), value=int) def test_regular_constant_mapping(self, start, num, step, value): assume(step != 0) mapping = {key: value for key in range(start, start + num*step, step)} builder = CatalogBuilder(mapping) catalog = builder.create() shared_items = set(mapping.items()) & set(catalog.items()) self.assertEqual(len(shared_items), len(mapping)) @given(start=int, num=integers_in_range(0, 10000), step=integers_in_range(-10000, 10000), values=streaming(int)) def test_regular_mapping(self, start, num, step, values): assume(step != 0) mapping = {key: value for key, value in zip(range(start, start + num*step, step), values)} builder = CatalogBuilder(mapping) catalog = builder.create() shared_items = set(mapping.items()) & set(catalog.items()) self.assertEqual(len(shared_items), len(mapping)) @given(num=integers_in_range(0, 10000), key_start=int, key_step=integers_in_range(-10000, 10000), value_start=int, value_step=integers_in_range(-10000, 10000)) def test_linear_regular_mapping(self, num, key_start, key_step, value_start, value_step): assume(key_step != 0) assume(value_step != 0) mapping = {key: value for key, value in zip(range(key_start, key_start + num*key_step, key_step), range(value_start, value_start + num*value_step, value_step))} builder = CatalogBuilder(mapping) catalog = builder.create() shared_items = set(mapping.items()) & set(catalog.items()) self.assertEqual(len(shared_items), len(mapping)) @given(dictionary((int, int), int)) def test_arbitrary_mapping(self, mapping): builder = CatalogBuilder(mapping) catalog = builder.create() shared_items = set(mapping.items()) & set(catalog.items()) self.assertEqual(len(shared_items), len(mapping)) @given(i_start=integers_in_range(0, 10), i_num=integers_in_range(1, 10), i_step=just(1), j_start=integers_in_range(0, 10), j_num=integers_in_range(1, 10), j_step=just(1), c=integers_in_range(1, 10)) def test_linear_regular_mapping_2d(self, i_start, i_num, i_step, j_start, j_num, j_step, c): assume(i_step != 0) assume(j_step != 0) def v(i, j): return (i - i_start) * ((j_start + j_num*j_step) - j_start) + (j - j_start) + c mapping = {(i, j): v(i, j) for i in range(i_start, i_start + i_num*i_step, i_step) for j in range(j_start, j_start + j_num*j_step, j_step)} builder = CatalogBuilder(mapping) catalog = builder.create() shared_items = set(mapping.items()) & set(catalog.items()) self.assertEqual(len(shared_items), len(mapping))
def test_integers_range(): assert find(s.integers_in_range(10, 100), lambda x: x > 10) == 11
def test_minimize_single_element_in_silly_large_int_range(): ir = integers_in_range(-(2 ** 256), 2 ** 256) assert minimal(ir, lambda x: x >= -(2 ** 255)) == -(2 ** 255)
from fractions import Fraction from collections import OrderedDict, namedtuple from hypothesis import strategy from tests.common.basic import Bitfields, BoringBitfields, \ simplify_bitfield from hypothesis.specifiers import just, one_of, strings, streaming, \ dictionary, sampled_from, integers_from, floats_in_range, \ integers_in_range from tests.common.specifiers import Descriptor from hypothesis.strategytests import TemplatesFor, strategy_test_suite from hypothesis.internal.compat import text_type, binary_type from hypothesis.searchstrategy.basic import basic_strategy from hypothesis.searchstrategy.narytree import NAryTree TestIntegerRange = strategy_test_suite(integers_in_range(0, 5)) TestGiantIntegerRange = strategy_test_suite( integers_in_range(-(2**129), 2**129)) TestFloatRange = strategy_test_suite(floats_in_range(0.5, 10)) TestSampled10 = strategy_test_suite(sampled_from(elements=list(range(10)))) TestSampled1 = strategy_test_suite(sampled_from(elements=(1, ))) TestSampled2 = strategy_test_suite(sampled_from(elements=(1, 2))) TestIntegersFrom = strategy_test_suite(integers_from(13)) TestOneOf = strategy_test_suite(one_of((int, int, bool))) TestOneOfSameType = strategy_test_suite( one_of((integers_in_range(1, 10), integers_in_range(8, 15)))) TestRandom = strategy_test_suite(Random) TestInts = strategy_test_suite(int) TestBoolLists = strategy_test_suite([bool])
def define_binary_strategy(specifier, settings): return BinaryStringStrategy( strategy=strategy([specifiers.integers_in_range(0, 255)], settings), )
ABC = namedtuple('ABC', ('a', 'b', 'c')) standard_types = [ Bitfields, [], (), set(), frozenset(), {}, NAryTree(bool, bool, bool), ABC(bool, bool, bool), ABC(bool, bool, int), {'a': int, 'b': bool}, one_of((int, (bool,))), sampled_from(range(10)), one_of((just('a'), just('b'), just('c'))), sampled_from(('a', 'b', 'c')), int, integers_from(3), integers_in_range(-2 ** 32, 2 ** 64), float, floats_in_range(-2.0, 3.0), text_type, binary_type, bool, (bool, bool), frozenset({int}), complex, Fraction, Decimal, [[bool]], OrderedPair, ConstantList(int), strategy(streaming(int)).map(lambda x: list(x[:2]) and x), strategy(int).filter(lambda x: abs(x) > 100), floats_in_range(-sys.float_info.max, sys.float_info.max), None, Random, ]
def integer_range(self, left, right): left, right = sorted((left, right)) return strategy(integers_in_range(left, right))
from fractions import Fraction from collections import OrderedDict, namedtuple from hypothesis import strategy from tests.common.basic import Bitfields, BoringBitfields, \ simplify_bitfield from hypothesis.specifiers import just, one_of, strings, streaming, \ dictionary, sampled_from, integers_from, floats_in_range, \ integers_in_range from tests.common.specifiers import Descriptor from hypothesis.strategytests import TemplatesFor, strategy_test_suite from hypothesis.internal.compat import text_type, binary_type from hypothesis.searchstrategy.basic import basic_strategy from hypothesis.searchstrategy.narytree import NAryTree TestIntegerRange = strategy_test_suite(integers_in_range(0, 5)) TestGiantIntegerRange = strategy_test_suite( integers_in_range(-(2 ** 129), 2 ** 129) ) TestFloatRange = strategy_test_suite(floats_in_range(0.5, 10)) TestSampled10 = strategy_test_suite(sampled_from(elements=list(range(10)))) TestSampled1 = strategy_test_suite(sampled_from(elements=(1,))) TestSampled2 = strategy_test_suite(sampled_from(elements=(1, 2))) TestIntegersFrom = strategy_test_suite(integers_from(13)) TestOneOf = strategy_test_suite(one_of((int, int, bool))) TestOneOfSameType = strategy_test_suite( one_of((integers_in_range(1, 10), integers_in_range(8, 15))) ) TestRandom = strategy_test_suite(Random)
from hypothesis import assume, given from hypothesis.specifiers import integers_in_range from myhdl import Signal, intbv from uhdl import Sig width = integers_in_range(2, 100) def check_sigs(expected, *sigs): __tracebackhide__ = True for s in sigs: assert expected == s assert len(expected) == len(s) @given(bool) def test_bool(x): check_sigs(Signal(x), Sig(x)) @given(width) def test_only_width(x): check_sigs(Signal(intbv()[x:]), Sig(w=x)) @given(int, width) def test_width_and_initial_value(val, width): check_sigs(Signal(intbv(val)[width:]), Sig(val, width), Sig(val, w=width),
def test_out_of_range_integers_are_bad(): with pytest.raises(BadData): strategy(integers_in_range(0, 1)).from_basic(-1) with pytest.raises(BadData): strategy(integers_from(11)).from_basic(9)
# END HEADER from __future__ import division, print_function, absolute_import, \ unicode_literals from random import Random import pytest from hypothesis import Settings, given, assume, strategy from hypothesis.database import ExampleDatabase from hypothesis.specifiers import just, floats_in_range, integers_in_range from hypothesis.searchstrategy.strategies import BuildContext ConstantLists = strategy(int).flatmap(lambda i: [just(i)]) OrderedPairs = strategy(integers_in_range( 1, 200)).flatmap(lambda e: (integers_in_range(0, e - 1), just(e))) with Settings(max_examples=200): @given(ConstantLists) def test_constant_lists_are_constant(x): assume(len(x) >= 3) assert len(set(x)) == 1 @given(OrderedPairs) def test_in_order(x): assert x[0] < x[1] def test_flatmap_retrieve_from_db(): constant_float_lists = strategy(floats_in_range(
def test_minimizes_integer_range_to_boundary(boundary): assert find( integers_in_range(boundary, boundary + 100), lambda x: True ) == boundary