Exemplo n.º 1
0
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))
Exemplo n.º 2
0
 def __init__(self, settings):
     super(DescriptorStrategy, self).__init__(strategy=strategy(
         NAryTree(branch_labels=sampled_from((tuple, dict, set, frozenset,
                                              list)),
                  branch_keys=one_of((int, str)),
                  leaf_values=sampled_from((int, float, text_type,
                                            binary_type, bool, complex,
                                            type(None)))), settings))
Exemplo n.º 3
0
 def __init__(self, settings):
     super(DescriptorStrategy, self).__init__(
         strategy=strategy(NAryTree(
             branch_labels=sampled_from((
                 tuple, dict, set, frozenset, list
             )),
             branch_keys=one_of((int, str)),
             leaf_values=sampled_from((
                 int, float, text_type, binary_type,
                 bool, complex, type(None)))
         ), settings)
     )
Exemplo n.º 4
0
class TestTextualReelHeader(unittest.TestCase):
    @given(multiline_ascii_encodable_text(0, CARDS_PER_HEADER),
           sampled_from([ASCII, EBCDIC]))
    def test_roundtrip(self, write_header_text, encoding):
        write_header_lines = write_header_text.splitlines()
        with BytesIO() as write_stream:
            write_textual_reel_header(write_stream, write_header_lines,
                                      encoding)
            written_stream = write_stream.getvalue()

        with BytesIO(written_stream) as read_stream:
            read_header_lines = read_textual_reel_header(read_stream, encoding)

        for written_line, read_line in zip_longest(
                write_header_lines[:CARDS_PER_HEADER],
                read_header_lines,
                fillvalue=""):
            self.assertEqual(
                written_line[:CARD_LENGTH].rstrip().ljust(CARD_LENGTH),
                read_line)

    @given(multiline_ascii_encodable_text(0, CARDS_PER_HEADER),
           sampled_from([ASCII, EBCDIC]))
    def test_header_num_lines(self, write_header_text, encoding):
        write_header_lines = write_header_text.splitlines()
        with BytesIO() as write_stream:
            write_textual_reel_header(write_stream, write_header_lines,
                                      encoding)
            written_stream = write_stream.getvalue()

        with BytesIO(written_stream) as read_stream:
            read_header_lines = read_textual_reel_header(read_stream, encoding)

        self.assertEqual(len(read_header_lines), CARDS_PER_HEADER)

    @given(multiline_ascii_encodable_text(0, CARDS_PER_HEADER),
           sampled_from([ASCII, EBCDIC]))
    def test_header_line_length(self, write_header_text, encoding):
        write_header_lines = write_header_text.splitlines()
        with BytesIO() as write_stream:
            write_textual_reel_header(write_stream, write_header_lines,
                                      encoding)
            written_stream = write_stream.getvalue()

        with BytesIO(written_stream) as read_stream:
            read_header_lines = read_textual_reel_header(read_stream, encoding)

        self.assertTrue(
            all(len(line) == CARD_LENGTH for line in read_header_lines))
Exemplo n.º 5
0
class TestBinaryReelHeader(unittest.TestCase):
    @given(header(BinaryReelHeader), sampled_from(['<', '>']))
    def test_roundtrip(self, write_header, endian):
        with BytesIO() as write_stream:
            write_binary_reel_header(write_stream, write_header, endian)
            written_stream = write_stream.getvalue()

        with BytesIO(written_stream) as read_stream:
            read_header = read_binary_reel_header(read_stream, endian)

        self.assertTrue(are_equal(write_header, read_header))
Exemplo n.º 6
0
def test_only_raises_if_actually_considered_all(r):
    examples = set()
    settings = Settings(min_satisfying_examples=0, max_examples=100)

    def consider_and_append(x):
        examples.add(x)
        return False
    s = sampled_from(range(100))
    with pytest.raises(NoSuchExample) as e:
        find(s, consider_and_append, settings=settings)

    assume(len(examples) < 100)
    assert not isinstance(e.value, DefinitelyNoSuchExample)
Exemplo n.º 7
0
def test_sample_from_empty_errors():
    with pytest.raises(ValueError):
        strategy(specifiers.sampled_from([]))
Exemplo n.º 8
0
    assume(y in xs)
    xs.remove(y)
    assert y not in xs


def test_errors_even_if_does_not_error_on_final_call():
    @given(int)
    def rude(x):
        assert not any(t[3] == 'best_satisfying_template'
                       for t in inspect.getouterframes(inspect.currentframe()))

    with pytest.raises(Flaky):
        rude()


@given(set([sampled_from(list(range(10)))]))
def test_can_test_sets_sampled_from(xs):
    assert all(isinstance(x, int) for x in xs)
    assert all(0 <= x < 10 for x in xs)


mix = one_of((sampled_from([1, 2, 3]), str))


@fails
@given(mix, mix)
def test_can_mix_sampling_with_generating(x, y):
    assert type(x) == type(y)


@fails
from collections import OrderedDict, namedtuple

from hypothesis import strategy
from hypothesis.specifiers import just, one_of, dictionary, 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))
TestGiantIntegerRange = strategy_test_suite(
    integers_in_range(-(2 ** 129), 2 ** 129)
)
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])
TestDictionaries = strategy_test_suite(dictionary((int, int), bool))
TestOrderedDictionaries = strategy_test_suite(
    dictionary(int, int, OrderedDict)
)
TestString = strategy_test_suite(text_type)
Exemplo n.º 10
0
test_can_produce_the_same_int_twice = define_test(
    ([int], int), 0.01, lambda t: len([x for x in t[0] if x == t[1]]) > 1)


def distorted_value(x):
    c = Counter(x)
    return min(c.values()) * 3 <= max(c.values())


def distorted(x):
    return distorted_value(map(type, x))


test_sampled_from_large_number_usually_mixes_some = define_test(
    [specifiers.sampled_from(range(50))],
    0.5,
    lambda x: len(set(x)) >= 25,
    condition=lambda t: len(t) >= 50,
)

test_sampled_from_usually_distorted = define_test(
    [specifiers.sampled_from(range(5))],
    0.5,
    distorted_value,
    condition=lambda x: len(x) >= 3,
)

test_non_empty_subset_of_two_is_usually_large = define_test(
    {specifiers.sampled_from((1, 2))}, 0.6, lambda t: len(t) == 2)
Exemplo n.º 11
0
    return strategy(spec.spec, settings).flatmap(
        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),
Exemplo n.º 12
0
def test_does_not_shrink_size_for_non_hashable_sample():
    s = strategy(specifiers.sampled_from(([], [])))
    assert s.size_lower_bound == 2
    assert s.size_upper_bound == 2
Exemplo n.º 13
0
def test_sampled_from_samples():
    x = strategy(s.sampled_from((1, 2, 3)))
    assert x.example() in (1, 2, 3)
from __future__ import unicode_literals

from mock import *
from nose.tools import *
from hypothesis import assume, given, strategy
from hypothesis.specifiers import one_of, sampled_from

from six import text_type, binary_type
from pymacaroons import Macaroon, Verifier
from pymacaroons.utils import convert_to_bytes


ascii_text_strategy = strategy(
    [sampled_from(map(chr, range(0, 128)))]
).map(lambda c: ''.join(c))

ascii_bin_strategy = strategy(ascii_text_strategy).map(
    lambda s: convert_to_bytes(s)
)


class TestMacaroon(object):

    def setup(self):
        pass

    @given(
        key_id=one_of((ascii_text_strategy, ascii_bin_strategy)),
        loc=one_of((ascii_text_strategy, ascii_bin_strategy)),
        key=one_of((ascii_text_strategy, ascii_bin_strategy))
    )
    ([int], int), 0.01,
    lambda t: len([x for x in t[0] if x == t[1]]) > 1
)


def distorted_value(x):
    c = Counter(x)
    return min(c.values()) * 3 <= max(c.values())


def distorted(x):
    return distorted_value(map(type, x))


test_sampled_from_large_number_usually_mixes_some = define_test(
    [specifiers.sampled_from(range(50))], 0.5, lambda x: len(set(x)) >= 25,
    condition=lambda t: len(t) >= 50,
)


test_sampled_from_usually_distorted = define_test(
    [specifiers.sampled_from(range(5))], 0.5, distorted_value,
    condition=lambda x: len(x) >= 3,
)


test_non_empty_subset_of_two_is_usually_large = define_test(
    {specifiers.sampled_from((1, 2))}, 0.6,
    lambda t: len(t) == 2
)
Exemplo n.º 16
0
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,
Exemplo n.º 17
0
def test_does_not_shrink_size_for_non_hashable_sample():
    s = strategy(specifiers.sampled_from(([], [])))
    assert s.size_lower_bound == 2
    assert s.size_upper_bound == 2
test_can_produce_long_lists = define_test(
    [int], 0.5, long_list
)

test_can_produce_short_lists = define_test(
    [int], 0.2, lambda x: len(x) <= 10
)

test_can_produce_lists_bunched_near_left = define_test(
    [specifiers.floats_in_range(0, 1)], 0.1,
    lambda ts: all(t < 0.2 for t in ts),
    condition=long_list,
)

test_can_produce_lists_bunched_near_right = define_test(
    [specifiers.floats_in_range(0, 1)], 0.1,
    lambda ts: all(t > 0.8 for t in ts),
    condition=long_list,
)

test_can_produce_the_same_int_twice = define_test(
    ([int], int), 0.05,
    lambda t: len([x for x in t[0] if x == t[1]]) > 1
)

test_non_empty_subset_of_two_is_usually_large = define_test(
    {specifiers.sampled_from((1, 2))}, 0.6,
    lambda t: len(t) == 2
)
Exemplo n.º 19
0
def test_sampled_from_one():
    assert strategy(s.sampled_from((1, ))).example() == 1
Exemplo n.º 20
0
def test_sampled_from_validates():
    with pytest.raises(InvalidArgument):
        strategy(s.sampled_from([]))
Exemplo n.º 21
0
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])
TestDictionaries = strategy_test_suite(dictionary((int, int), bool))
TestOrderedDictionaries = strategy_test_suite(dictionary(
    int, int, OrderedDict))
TestString = strategy_test_suite(text_type)
    assert y not in xs


def test_errors_even_if_does_not_error_on_final_call():
    @given(int)
    def rude(x):
        assert not any(
            t[3] == 'falsify'
            for t in inspect.getouterframes(inspect.currentframe())
        )

    with pytest.raises(Flaky):
        rude()


@given(set([sampled_from(list(range(10)))]))
def test_can_test_sets_sampled_from(xs):
    assert all(isinstance(x, int) for x in xs)
    assert all(0 <= x < 10 for x in xs)


mix = one_of((sampled_from([1, 2, 3]), str))


@fails
@given(mix, mix)
def test_can_mix_sampling_with_generating(x, y):
    assert type(x) == type(y)


@fails
Exemplo n.º 23
0
def test_sampled_from_validates():
    with pytest.raises(InvalidArgument):
        strategy(s.sampled_from([]))
Exemplo n.º 24
0
    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])
TestDictionaries = strategy_test_suite(dictionary((int, int), bool))
TestOrderedDictionaries = strategy_test_suite(
    dictionary(int, int, OrderedDict)
Exemplo n.º 25
0
def define_text_type_from_alphabet(specifier, settings):
    if not specifier.alphabet:
        return StringStrategy(strategy([], settings))
    return StringStrategy(strategy(
        [specifiers.sampled_from(specifier.alphabet)], settings))
Exemplo n.º 26
0
def test_sampled_from_one():
    assert strategy(s.sampled_from((1,))).example() == 1
Exemplo n.º 27
0
from collections import namedtuple

import pytest
from doubles import InstanceDouble
from doubles import allow
from doubles import expect
from hypothesis import assume
from hypothesis import given
from hypothesis import specifiers

from tchannel import rw
from tchannel.errors import ReadError
from tchannel.io import BytesIO

number_width = specifiers.sampled_from([1, 2, 4, 8])


def bio(bs):
    return BytesIO(bytearray(bs))


def roundtrip(value, v_rw):
    return v_rw.read(bio(v_rw.write(value, BytesIO()).getvalue()))


@given(int, number_width)
def test_number_roundtrip(num, width):
    num = num % (2 ** width - 1)
    assert roundtrip(num, rw.number(width)) == num
Exemplo n.º 28
0
def test_sampled_from_samples():
    x = strategy(s.sampled_from((1, 2, 3)))
    assert x.example() in (1, 2, 3)
test_can_produce_floats_near_right = define_test(
    specifiers.floats_in_range(0, 1), 0.1, lambda t: t > 0.8)

test_can_produce_floats_in_middle = define_test(
    specifiers.floats_in_range(0, 1), 0.3, lambda t: 0.2 <= t <= 0.8)

test_can_produce_long_lists = define_test([int], 0.5, long_list)

test_can_produce_short_lists = define_test([int], 0.2, lambda x: len(x) <= 10)

test_can_produce_lists_bunched_near_left = define_test(
    [specifiers.floats_in_range(0, 1)],
    0.1,
    lambda ts: all(t < 0.2 for t in ts),
    condition=long_list,
)

test_can_produce_lists_bunched_near_right = define_test(
    [specifiers.floats_in_range(0, 1)],
    0.1,
    lambda ts: all(t > 0.8 for t in ts),
    condition=long_list,
)

test_can_produce_the_same_int_twice = define_test(
    ([int], int), 0.05, lambda t: len([x for x in t[0] if x == t[1]]) > 1)

test_non_empty_subset_of_two_is_usually_large = define_test(
    {specifiers.sampled_from((1, 2))}, 0.6, lambda t: len(t) == 2)
Exemplo n.º 30
0
def test_py3_safe_with_use_locale_inserts_null_string_between_two_numbers_example():
    assert _py3_safe([5, 9], True, isint) == [5, null_string, 9]


@given([py23_str, int])
def test_py3_safe_inserts_empty_string_between_two_numbers(x):
    assume(bool(x))
    assert _py3_safe(x, False, isint) == sep_inserter(x, (int, long), '')


def test_path_splitter_splits_path_string_by_separator_example():
    z = '/this/is/a/path'
    assert _path_splitter(z) == list(pathlib.Path(z).parts)


@given([sampled_from(string.ascii_letters)])
def test_path_splitter_splits_path_string_by_separator(x):
    assume(len(x) > 1)
    assume(all(x))
    z = py23_str(pathlib.Path(*x))
    assert _path_splitter(z) == list(pathlib.Path(z).parts)


def test_path_splitter_splits_path_string_by_separator_and_removes_extension_example():
    z = '/this/is/a/path/file.exe'
    y = list(pathlib.Path(z).parts)
    assert _path_splitter(z) == y[:-1] + [pathlib.Path(z).stem] + [pathlib.Path(z).suffix]


@given([sampled_from(string.ascii_letters)])
def test_path_splitter_splits_path_string_by_separator_and_removes_extension(x):
Exemplo n.º 31
0
from fractions import Fraction
from collections import OrderedDict, namedtuple

from hypothesis import strategy
from hypothesis.specifiers import just, one_of, dictionary, 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))
TestGiantIntegerRange = strategy_test_suite(
    integers_in_range(-(2**129), 2**129))
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])
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))