def test_minimize_one_of_distinct_types():
    x = minimal(
        (one_of((bool, binary_type)), one_of((bool, binary_type))),
        lambda x: type(x[0]) != type(x[1])
    )
    assert x in (
        (False, b''),
        (b'', False)
    )
Пример #2
0
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
Пример #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))
Пример #4
0
def test_can_apply_simplifiers_to_other_types():
    r = Random(0)
    s = strategy(one_of((bool, [bool])))
    template1 = s.draw_and_produce_from_random(r)
    while True:
        template2 = s.draw_and_produce_from_random(r)
        if template2[0] != template1[0]:
            break
    for simplify in s.simplifiers(r, template1):
        assert list(simplify(r, template2)) == []
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))
    )
    def test_serializing_deserializing_macaroon(self, key_id, loc, key):
        assume(key_id and loc and key)
        macaroon = Macaroon(
            location=loc,
            identifier=key_id,
            key=key
        )
        deserialized = Macaroon.deserialize(macaroon.serialize())
        assert_equal(macaroon.identifier, deserialized.identifier)
        assert_equal(macaroon.location, deserialized.location)
        assert_equal(macaroon.signature, deserialized.signature)
Пример #6
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)
     )
Пример #7
0
def model_to_base_specifier(model):
    result = {}
    for f in model._meta.concrete_fields:
        if isinstance(f, dm.AutoField):
            continue
        try:
            mapped = FIELD_MAPPINGS[type(f)]
        except KeyError:
            if 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
Пример #8
0
def model_to_base_specifier(model):
    result = {}
    for f in model._meta.concrete_fields:
        if isinstance(f, dm.AutoField):
            continue
        try:
            mapped = FIELD_MAPPINGS[type(f)]
        except KeyError:
            if 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
Пример #9
0
def test_minimize_one_of():
    for _ in hrange(100):
        assert minimal(one_of((int, str, bool))) in (
            0, '', False
        )
def test_slow_failing_test_3(x):
    time.sleep(0.05)
    assert not calls[2]
    calls[2] = 1


@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

Пример #11
0
from hypothesis.strategytests import strategy_test_suite
from hypothesis.extra.datetime import naive_datetime, \
    timezone_aware_datetime
from hypothesis.searchstrategy import strategy
from hypothesis.internal.compat import hrange
from hypothesis.internal.verifier import Verifier

hs.Settings.default.max_examples = 1000


TestStandardDescriptorFeatures1 = strategy_test_suite(datetime)
TestStandardDescriptorFeatures2 = strategy_test_suite(
    timezone_aware_datetime)
TestStandardDescriptorFeatures3 = strategy_test_suite(naive_datetime)
TestStandardDescriptorFeatures4 = strategy_test_suite(one_of((
    naive_datetime,
    timezone_aware_datetime,
)))


falsify = Verifier().falsify


def test_can_find_after_the_year_2000():
    falsify(lambda x: x.year > 2000, datetime)


def test_can_find_before_the_year_2000():
    falsify(lambda x: x.year < 2000, datetime)


def test_can_find_each_month():
Пример #12
0
def test_slow_failing_test_3(x):
    time.sleep(0.05)
    assert not calls[2]
    calls[2] = 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

Пример #13
0
def test_one_of():
    assert isinstance(strategy(s.one_of((bool, ()))).example(), (bool, tuple))
Пример #14
0
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)
BinaryString = strategy_test_suite(binary_type)
TestIntBool = strategy_test_suite((int, bool))
TestFloats = strategy_test_suite(float)
TestComplex = strategy_test_suite(complex)
Пример #15
0
def test_slow_failing_test_3(x):
    time.sleep(0.05)
    assert not calls[2]
    calls[2] = 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

Пример #16
0
def test_errors_on_empty_one_of():
    with pytest.raises(ValueError):
        specifiers.one_of([])
Пример #17
0
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)
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}))
Пример #18
0
def alternating(*args):
    return strategy(specifiers.one_of(args))
Пример #19
0
from hypothesis.specifiers import one_of
from hypothesis.extra.datetime import timezone_aware_datetime
from hypothesis.internal.compat import text_type, binary_type
from hypothesis.searchstrategy.strategies import MappedSearchStrategy, \
    strategy

FIELD_MAPPINGS = {
    dm.BigIntegerField: int,
    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.IntegerField: int,
    dm.NullBooleanField: one_of((None, bool)),
}


class ModelNotSupported(Exception):
    pass


def model_to_base_specifier(model):
    result = {}
    for f in model._meta.concrete_fields:
        if isinstance(f, dm.AutoField):
            continue
        try:
            mapped = FIELD_MAPPINGS[type(f)]
        except KeyError:
Пример #20
0
def test_slow_failing_test_3(x):
    time.sleep(0.05)
    assert not calls[2]
    calls[2] = 1


@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

Пример #21
0
def constant_list_strategy(spec, settings):
    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),
Пример #22
0
def test_tuples_do_not_block_cloning():
    assert minimal(
        [(one_of((bool, (int,))),)],
        lambda x: len(x) >= 50 and any(isinstance(t[0], bool) for t in x)
    ) == [(False,)] * 50
Пример #23
0
def test_tuples_do_not_block_cloning():
    assert minimal(
        [(one_of((bool, (int,))),)],
        lambda x: len(x) >= 50 and any(isinstance(t[0], bool) for t in x)
    ) == [(False,)] * 50
Пример #24
0
def test_minimize_one_of_distinct_types():
    x = minimal((one_of((bool, binary_type)), one_of((bool, binary_type))),
                lambda x: type(x[0]) != type(x[1]))
    assert x in ((False, b''), (b'', False))
Пример #25
0
        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,
Пример #26
0
def test_minimize_one_of():
    for _ in hrange(100):
        assert minimal(one_of((int, str, bool))) in (
            0, '', False
        )
Пример #27
0
from hypothesis.specifiers import one_of
from hypothesis.strategytests import strategy_test_suite
from hypothesis.extra.datetime import naive_datetime, \
    timezone_aware_datetime
from hypothesis.internal.debug import minimal
from hypothesis.internal.compat import hrange

hs.Settings.default.max_examples = 1000


TestStandardDescriptorFeatures1 = strategy_test_suite(datetime)
TestStandardDescriptorFeatures2 = strategy_test_suite(
    timezone_aware_datetime)
TestStandardDescriptorFeatures3 = strategy_test_suite(naive_datetime)
TestStandardDescriptorFeatures4 = strategy_test_suite(one_of((
    naive_datetime,
    timezone_aware_datetime,
)))


def test_can_find_after_the_year_2000():
    assert minimal(datetime, lambda x: x.year > 2000).year == 2001


def test_can_find_before_the_year_2000():
    assert minimal(datetime, lambda x: x.year < 2000).year == 1999


def test_can_find_each_month():
    for i in hrange(1, 12):
        minimal(datetime, lambda x: x.month == i)
Пример #28
0
def alternating(*args):
    return strategy(specifiers.one_of(args))
Пример #29
0
def test_returns_just_a_single_element():
    assert specifiers.one_of([1]) == 1
Пример #30
0
from hypothesis.specifiers import one_of
from hypothesis.extra.datetime import timezone_aware_datetime
from hypothesis.internal.compat import text_type, binary_type
from hypothesis.searchstrategy.strategies import MappedSearchStrategy, \
    strategy

FIELD_MAPPINGS = {
    dm.BigIntegerField: int,
    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.IntegerField: int,
    dm.NullBooleanField: one_of((None, bool)),
}


class ModelNotSupported(Exception):
    pass


def model_to_base_specifier(model):
    result = {}
    for f in model._meta.concrete_fields:
        if isinstance(f, dm.AutoField):
            continue
        try:
            mapped = FIELD_MAPPINGS[type(f)]
        except KeyError:
Пример #31
0
def test_one_of():
    assert isinstance(strategy(s.one_of((bool, ()))).example(), (bool, tuple))
Пример #32
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,