class TestFormatExtendedTextualHeader(unittest.TestCase): @given(multiline_ascii_encodable_text(0, 100), sampled_from([ASCII, EBCDIC]), bool) def test_forty_lines_per_page(self, text, encoding, include_text_stop): pages = format_extended_textual_header(text, encoding, include_text_stop) self.assertTrue(all(len(page) == CARDS_PER_HEADER for page in pages)) @given(multiline_ascii_encodable_text(0, 100), sampled_from([ASCII, EBCDIC]), bool) def test_eighty_bytes_per_encoded_line(self, text, encoding, include_text_stop): pages = format_extended_textual_header(text, encoding, include_text_stop) self.assertTrue( all([ len(line.encode(encoding)) == CARD_LENGTH for page in pages for line in page ])) @given(multiline_ascii_encodable_text(0, 100), sampled_from([ASCII, EBCDIC]), bool) def test_lines_end_with_cr_lf(self, text, encoding, include_text_stop): pages = format_extended_textual_header(text, encoding, include_text_stop) self.assertTrue( all([line.endswith('\r\n') for page in pages for line in page])) @given(multiline_ascii_encodable_text(0, 100), sampled_from([ASCII, EBCDIC]), just(True)) def test_end_text_stanza_present(self, text, encoding, include_text_stop): pages = format_extended_textual_header(text, encoding, include_text_stop) self.assertTrue(pages[-1][0].startswith(END_TEXT_STANZA))
def test_just_strategy_uses_repr(): class WeirdRepr(object): def __repr__(self): return 'ABCDEFG' assert repr(strategy(specifiers.just( WeirdRepr()))) == 'JustStrategy(value=%r)' % (WeirdRepr(), )
def test_flatmap_retrieve_from_db(): constant_float_lists = strategy(floats_in_range( 0, 1)).flatmap(lambda x: [just(x)]) track = [] db = ExampleDatabase() @given(constant_float_lists, settings=Settings(database=db)) def record_and_test_size(xs): track.append(xs) assert sum(xs) < 1 with pytest.raises(AssertionError): record_and_test_size() assert track example = track[-1] while track: track.pop() with pytest.raises(AssertionError): record_and_test_size() assert track[0] == example
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_flatmap_retrieve_from_db(): constant_float_lists = strategy(floats_in_range(0, 1)).flatmap( lambda x: [just(x)] ) track = [] db = ExampleDatabase() @given(constant_float_lists, settings=Settings(database=db)) def record_and_test_size(xs): track.append(xs) assert sum(xs) < 1 with pytest.raises(AssertionError): record_and_test_size() assert track example = track[-1] while track: track.pop() with pytest.raises(AssertionError): record_and_test_size() assert track[0] == example
def test_just_strategy_uses_repr(): class WeirdRepr(object): def __repr__(self): return 'ABCDEFG' assert repr( strategy(specifiers.just(WeirdRepr())) ) == 'JustStrategy(value=%r)' % (WeirdRepr(),)
def define_strategy_for_float_Range(specifier, settings): if specifier.start == specifier.end: return strategy(specifiers.just(specifier.start), settings) if math.isinf(specifier.end - specifier.start): assert specifier.start < 0 and specifier.end > 0 return strategy( specifiers.FloatRange(0, specifier.end), settings ) | strategy( specifiers.FloatRange(specifier.start, 0), settings ) return FixedBoundedFloatStrategy(specifier.start, specifier.end)
def convert_to_specifier(v): if isinstance(v, HypothesisProvided): return v.value else: return just(v)
test_ints_can_occasionally_be_really_large = define_test( int, 0.01, lambda t: t >= 2**63) test_mixing_is_sometimes_distorted = define_test( [bool, ()], 0.25, distorted, condition=lambda x: len(set(map(type, x))) == 2, ) test_mixes_2_reasonably_often = define_test( [bool, ()], 0.25, lambda x: len(set(map(type, x))) > 1, condition=bool, ) test_partial_mixes_3_reasonably_often = define_test( [bool, (), specifiers.just('hi')], 0.25, lambda x: 1 < len(set(map(type, x))) < 3, condition=bool, ) test_mixes_not_too_often = define_test( [bool, ()], 0.25, lambda x: len(set(map(type, x))) == 1, condition=bool, )
def test_can_flatmap_nameless(): f = nameless_const(specifiers.just(3)) assert repr(f) in repr(integers().flatmap(f))
def test_can_simplify_on_both_sides_of_flatmap(): assert minimal( strategy(int).flatmap(lambda x: [just(x)]), lambda x: len(x) >= 10 ) == [0] * 10
def test_show_for_nasty_in_just(): assert show(specifiers.just( complex(u'inf+1.9j'))) == u"Just(value=complex('inf+1.9j'))"
def test_can_simplify_flatmap_with_bounded_left_hand_size(): assert minimal( strategy(bool).flatmap(lambda x: [just(x)]), lambda x: len(x) >= 10) == [False] * 10
# obtain one at http://mozilla.org/MPL/2.0/. # 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]
@fails @given(int, settings=timeout_settings) def test_slow_failing_test_4(x): time.sleep(0.05) assert not calls[3] calls[3] = 1 @fails @given(one_of([float, bool]), one_of([float, bool])) def test_one_of_produces_different_values(x, y): assert type(x) == type(y) @given(just(42)) def test_is_the_answer(x): 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
def test_can_flatmap_nameless(): assert '0x' not in repr(integers().flatmap( nameless_const(specifiers.just(3))))
def test_can_flatmap_nameless(): assert '0x' not in repr(strategy(int).flatmap( nameless_const(specifiers.just(3))))
def test_just_works(): s = strategy(specifiers.just('giving')) assert s.example() == 'giving'
def test_raises_in_strict_mode(): with pytest.raises(HypothesisDeprecationWarning): strategy(just('test_raises_in_strict_mode'), Settings(strict=True))
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) TestJust = strategy_test_suite(just('hi')) TestTemplates = strategy_test_suite(TemplatesFor({int})) Stuff = namedtuple('Stuff', ('a', 'b')) TestNamedTuple = strategy_test_suite(Stuff(int, int)) TestTrees = strategy_test_suite(NAryTree(int, int, int)) TestMixedSets = strategy_test_suite({int, bool, float}) TestFrozenSets = strategy_test_suite(frozenset({bool})) TestNestedSets = strategy_test_suite(frozenset({frozenset({complex})})) TestMisc1 = strategy_test_suite({(2, -374): frozenset({None})}) TestMisc2 = strategy_test_suite({b'': frozenset({int})}) TestMisc3 = strategy_test_suite(({type(None), str},),)
# obtain one at http://mozilla.org/MPL/2.0/. # 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 constant_list_strategy(spec, settings): return strategy(spec.spec, settings).flatmap(lambda v: [just(v)], )
def test_just_is_just(): assert strategy(s.just(1)).example() == 1
float, 0.5, lambda t: t + 1 > 1, condition=lambda x: x > 0, ) test_ints_can_occasionally_be_really_large = define_test( int, 0.01, lambda t: t >= 2 ** 63 ) test_mixing_is_sometimes_distorted = define_test( [bool, ()], 0.25, distorted, condition=lambda x: len(set(map(type, x))) == 2, ) test_mixes_2_reasonably_often = define_test( [bool, ()], 0.25, lambda x: len(set(map(type, x))) > 1, condition=bool, ) test_partial_mixes_3_reasonably_often = define_test( [bool, (), specifiers.just('hi')], 0.25, lambda x: 1 < len(set(map(type, x))) < 3, condition=bool, ) test_mixes_not_too_often = define_test( [bool, ()], 0.25, lambda x: len(set(map(type, x))) == 1, condition=bool, )
def test_can_simplify_on_right_hand_strategy_of_flatmap(): assert minimal(strategy(int).flatmap(lambda x: [just(x)])) == []
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)) TestFloats = strategy_test_suite(float) TestComplex = strategy_test_suite(complex) TestJust = strategy_test_suite(just('hi')) TestTemplates = strategy_test_suite(TemplatesFor({int})) Stuff = namedtuple('Stuff', ('a', 'b')) TestNamedTuple = strategy_test_suite(Stuff(int, int)) TestTrees = strategy_test_suite(NAryTree(int, int, int)) TestMixedSets = strategy_test_suite({int, bool, float}) TestFrozenSets = strategy_test_suite(frozenset({bool})) TestNestedSets = strategy_test_suite(frozenset({frozenset({complex})})) TestMisc1 = strategy_test_suite({(2, -374): frozenset({None})}) TestMisc2 = strategy_test_suite({b'': frozenset({int})}) TestMisc3 = strategy_test_suite(({type(None), str},),)
lambda v: [just(v)], ) 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),
def constant_list_strategy(spec, settings): return strategy(spec.spec, settings).flatmap( lambda v: [just(v)], )
def test_strategy_warns_on_non_strategies(recwarn): strategy(just(u'test_strategy_warns_on_non_strategies'), Settings(strict=False)) assert recwarn.pop(DeprecationWarning) is not None
@fails @given(int, verifier=Verifier(settings=timeout_settings)) def test_slow_failing_test_4(x): time.sleep(0.05) assert not calls[3] calls[3] = 1 @fails @given(one_of([int, str]), one_of([int, str])) def test_one_of_produces_different_values(x, y): assert type(x) == type(y) @given(just(42)) def test_is_the_answer(x): 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
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]) TestDictionaries = strategy_test_suite(dictionary((int, int), bool)) TestOrderedDictionaries = strategy_test_suite( dictionary(int, int, OrderedDict) ) 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) TestJust = strategy_test_suite(just('hi')) TestTemplates = strategy_test_suite(TemplatesFor({int})) TestEmptyString = strategy_test_suite(strings(alphabet='')) TestSingleString = strategy_test_suite(strings(alphabet='a')) TestManyString = strategy_test_suite(strings(alphabet='abcdef☃')) Stuff = namedtuple('Stuff', ('a', 'b')) TestNamedTuple = strategy_test_suite(Stuff(int, int)) TestTrees = strategy_test_suite(NAryTree(int, int, int)) TestMixedSets = strategy_test_suite({int, bool, float}) TestFrozenSets = strategy_test_suite(frozenset({bool})) TestNestedSets = strategy_test_suite(frozenset({frozenset({complex})}))
def test_raises_in_strict_mode(): with pytest.raises(HypothesisDeprecationWarning): strategy(just(u'test_raises_in_strict_mode'), Settings(strict=True))
lambda v: [just(v)], ) EvalledIntStream = strategy(streaming(int)).map(lambda x: list(x[:10]) and x) 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,
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]) TestDictionaries = strategy_test_suite(dictionary((int, int), bool)) TestOrderedDictionaries = strategy_test_suite(dictionary( int, int, OrderedDict)) 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) TestJust = strategy_test_suite(just('hi')) TestTemplates = strategy_test_suite(TemplatesFor({int})) TestEmptyString = strategy_test_suite(strings(alphabet='')) TestSingleString = strategy_test_suite(strings(alphabet='a')) TestManyString = strategy_test_suite(strings(alphabet='abcdef☃')) Stuff = namedtuple('Stuff', ('a', 'b')) TestNamedTuple = strategy_test_suite(Stuff(int, int)) TestTrees = strategy_test_suite(NAryTree(int, int, int)) TestMixedSets = strategy_test_suite({int, bool, float}) TestFrozenSets = strategy_test_suite(frozenset({bool})) TestNestedSets = strategy_test_suite(frozenset({frozenset({complex})}))
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_show_for_nasty_in_just(): assert show( specifiers.just(complex(u'inf+1.9j')) ) == u"Just(value=complex('inf+1.9j'))"
def test_strategy_warns_on_non_strategies(recwarn): strategy( just('test_strategy_warns_on_non_strategies'), Settings(strict=False)) assert recwarn.pop(DeprecationWarning) is not None
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]],
def just_strategy(self, value): return strategy(just(value))