def test_min_magnitude_respected(data, mag):
    c = data.draw(complex_numbers(min_magnitude=mag))
    assert (
        abs(c.real) >= mag
        or abs(c.imag) >= mag
        or abs(c) >= mag * (1 - sys.float_info.epsilon)
    )
def test_minmax_magnitude_equal(data, mag):
    val = data.draw(st.complex_numbers(min_magnitude=mag, max_magnitude=mag))
    try:
        assume(abs(val) < float('inf'))
        assert math.isclose(abs(val), mag)
    except OverflowError:
        reject()
    except AttributeError:
        pass  # Python 2.7.3 does not have math.isclose
def test_minmax_magnitude_equal(data, mag):
    val = data.draw(st.complex_numbers(min_magnitude=mag, max_magnitude=mag))
    try:
        # Cap magnitude at 10e300 to avoid float overflow, and imprecision
        # at very large exponents (which makes math.isclose fail)
        assert math.isclose(abs(val), mag)
    except OverflowError:
        reject()
    except AttributeError:
        pass  # Python 2.7.3 does not have math.isclose
Exemplo n.º 4
0
def from_dtype(dtype):
    # type: (np.dtype) -> st.SearchStrategy[Any]
    """Creates a strategy which can generate any value of the given dtype."""
    check_type(np.dtype, dtype, 'dtype')
    # Compound datatypes, eg 'f4,f4,f4'
    if dtype.names is not None:
        # mapping np.void.type over a strategy is nonsense, so return now.
        return st.tuples(
            *[from_dtype(dtype.fields[name][0]) for name in dtype.names])

    # Subarray datatypes, eg '(2, 3)i4'
    if dtype.subdtype is not None:
        subtype, shape = dtype.subdtype
        return arrays(subtype, shape)

    # Scalar datatypes
    if dtype.kind == u'b':
        result = st.booleans()  # type: SearchStrategy[Any]
    elif dtype.kind == u'f':
        if dtype.itemsize == 2:
            result = st.floats(width=16)
        elif dtype.itemsize == 4:
            result = st.floats(width=32)
        else:
            result = st.floats()
    elif dtype.kind == u'c':
        if dtype.itemsize == 8:
            float32 = st.floats(width=32)
            result = st.builds(complex, float32, float32)
        else:
            result = st.complex_numbers()
    elif dtype.kind in (u'S', u'a'):
        # Numpy strings are null-terminated; only allow round-trippable values.
        # `itemsize == 0` means 'fixed length determined at array creation'
        result = st.binary(max_size=dtype.itemsize or None
                           ).filter(lambda b: b[-1:] != b'\0')
    elif dtype.kind == u'u':
        result = st.integers(min_value=0,
                             max_value=2 ** (8 * dtype.itemsize) - 1)
    elif dtype.kind == u'i':
        overflow = 2 ** (8 * dtype.itemsize - 1)
        result = st.integers(min_value=-overflow, max_value=overflow - 1)
    elif dtype.kind == u'U':
        # Encoded in UTF-32 (four bytes/codepoint) and null-terminated
        result = st.text(max_size=(dtype.itemsize or 0) // 4 or None
                         ).filter(lambda b: b[-1:] != u'\0')
    elif dtype.kind in (u'm', u'M'):
        if '[' in dtype.str:
            res = st.just(dtype.str.split('[')[-1][:-1])
        else:
            res = st.sampled_from(TIME_RESOLUTIONS)
        result = st.builds(dtype.type, st.integers(-2**63, 2**63 - 1), res)
    else:
        raise InvalidArgument(u'No strategy inference for {}'.format(dtype))
    return result.map(dtype.type)
def test_nested_set_complexity():
    strat = frozensets(frozensets(complex_numbers()))

    rnd = Random(0)
    template = (
        ((float('inf'), 1.0), (-1.0325215252103651e-149, 1.0)),
        ((-1.677443578786644e-309, -1.0), (-2.2250738585072014e-308, 0.0))
    )
    simplifiers = list(strat.simplifiers(rnd, template))
    rnd.shuffle(simplifiers)
    simplifiers = simplifiers[:10]
    for simplify in simplifiers:
        for s in islice(simplify(rnd, template), 50):
            assert not strat.strictly_simpler(template, s)
Exemplo n.º 6
0
def test_flatmap_can_apply_all_inapplicable_simplifiers():
    random = Random(1)
    s = booleans().flatmap(lambda x: complex_numbers() if x else booleans())
    source_to_total = {}

    while len(source_to_total) < 2:
        t = s.draw_and_produce(random)
        source_to_total[t.source_template] = t
    u = source_to_total[False]
    v = source_to_total[True]
    s.reify(u)
    s.reify(v)

    for p in ((u, v), (v, u)):
        for simplify in s.simplifiers(random, p[0]):
            for target in simplify(random, p[1]):
                assert not s.strictly_simpler(p[1], target)
Exemplo n.º 7
0
def from_dtype(dtype):
    if dtype.kind == u'b':
        result = st.booleans()
    elif dtype.kind == u'f':
        result = st.floats()
    elif dtype.kind == u'c':
        result = st.complex_numbers()
    elif dtype.kind in (u'S', u'a', u'V'):
        result = st.binary()
    elif dtype.kind == u'u':
        result = st.integers(
            min_value=0, max_value=1 << (4 * dtype.itemsize) - 1)
    elif dtype.kind == u'i':
        min_integer = -1 << (4 * dtype.itemsize - 1)
        result = st.integers(min_value=min_integer, max_value=-min_integer - 1)
    elif dtype.kind == u'U':
        result = st.text()
    else:
        raise NotImplementedError(
            u'No strategy implementation for %r' % (dtype,)
        )
    return result.map(dtype.type)
Exemplo n.º 8
0
def from_dtype(dtype):
    # Compound datatypes, eg 'f4,f4,f4'
    if dtype.names is not None:
        # mapping np.void.type over a strategy is nonsense, so return now.
        return st.tuples(
            *[from_dtype(dtype.fields[name][0]) for name in dtype.names])

    # Subarray datatypes, eg '(2, 3)i4'
    if dtype.subdtype is not None:
        subtype, shape = dtype.subdtype
        return arrays(subtype, shape)

    # Scalar datatypes
    if dtype.kind == u'b':
        result = st.booleans()
    elif dtype.kind == u'f':
        result = st.floats()
    elif dtype.kind == u'c':
        result = st.complex_numbers()
    elif dtype.kind in (u'S', u'a'):
        result = st.binary()
    elif dtype.kind == u'u':
        result = st.integers(
            min_value=0, max_value=1 << (4 * dtype.itemsize) - 1)
    elif dtype.kind == u'i':
        min_integer = -1 << (4 * dtype.itemsize - 1)
        result = st.integers(min_value=min_integer, max_value=-min_integer - 1)
    elif dtype.kind == u'U':
        result = st.text()
    elif dtype.kind in (u'm', u'M'):
        if '[' in dtype.str:
            res = st.just(dtype.str.split('[')[-1][:-1])
        else:
            res = st.sampled_from(TIME_RESOLUTIONS)
        result = st.builds(dtype.type, st.integers(-2**63, 2**63 - 1), res)
    else:
        raise InvalidArgument(u'No strategy inference for {}'.format(dtype))
    return result.map(dtype.type)
def test_minimal_nonzero_real():
    assert minimal(complex_numbers(), lambda x: x.real != 0) == 1
def test_minimal_quadrant2():
    assert minimal(complex_numbers(), lambda x: x.imag > 0 and x.real < 0) == -1 + 1j
Exemplo n.º 11
0
    kw = {"elements": st.just(300)}
    if fill:
        kw = {"elements": st.nothing(), "fill": kw["elements"]}
    arr = data.draw(nps.arrays(dtype="int8", shape=(1, ), **kw))
    assert arr[0] == (300 % 256)


@pytest.mark.parametrize("fill", [False, True])
@pytest.mark.parametrize(
    "dtype,strat",
    [
        ("float16", st.floats(min_value=65520, allow_infinity=False)),
        ("float32", st.floats(min_value=10**40, allow_infinity=False)),
        (
            "complex64",
            st.complex_numbers(min_magnitude=10**300, allow_infinity=False),
        ),
        ("U1", st.text(min_size=2, max_size=2)),
        ("S1", st.binary(min_size=2, max_size=2)),
    ],
)
@fails_with(InvalidArgument)
@given(data=st.data())
def test_unrepresentable_elements_are_deprecated(fill, dtype, strat, data):
    if fill:
        kw = {"elements": st.nothing(), "fill": strat}
    else:
        kw = {"elements": strat}
    arr = data.draw(nps.arrays(dtype=dtype, shape=(1, ), **kw))
    try:
        # This is a float or complex number, and has overflowed to infinity,
def test_minimal_quadrant3():
    assert minimal(complex_numbers(), lambda x: x.imag < 0 and x.real < 0) == -1 - 1j


def test_minimal_quadrant4():
    assert minimal(complex_numbers(), lambda x: x.imag < 0 and x.real > 0) == 1 - 1j


@given(st.data(), st.integers(-5, 5).map(lambda x: 10 ** x))
def test_max_magnitude_respected(data, mag):
    c = data.draw(complex_numbers(max_magnitude=mag))
    assert abs(c) <= mag * (1 + sys.float_info.epsilon)


@given(complex_numbers(max_magnitude=0))
def test_max_magnitude_zero(val):
    assert val == 0


@given(st.data(), st.integers(-5, 5).map(lambda x: 10 ** x))
def test_min_magnitude_respected(data, mag):
    c = data.draw(complex_numbers(min_magnitude=mag))
    assert (
        abs(c.real) >= mag
        or abs(c.imag) >= mag
        or abs(c) >= mag * (1 - sys.float_info.epsilon)
    )


def test_minimal_min_magnitude_zero():
Exemplo n.º 13
0
_normalized_signal_parameters = {"channels": stn.arrays(dtype=numpy.float64,       # pylint: disable=no-value-for-parameter; there is a false alarm about a missing parameter for ``draw``
                                                        shape=stn.array_shapes(min_dims=2, max_dims=2),
                                                        elements=st.floats(min_value=-255.0 / 256.0, max_value=254.0 / 256.0)),     # pylint: disable=line-too-long
                                 "sampling_rate": sampling_rates,
                                 "offset": st.integers(min_value=-2 ** 24, max_value=2 ** 24),
                                 "labels": st.lists(elements=texts)}
normalized_signal_parameters = st.fixed_dictionaries(_normalized_signal_parameters)
normalized_signals = st.builds(sumpf.Signal, **_normalized_signal_parameters)

############
# Spectrum #
############

_spectrum_parameters = {"channels": stn.arrays(dtype=numpy.complex128,  # pylint: disable=no-value-for-parameter; there is a false alarm about a missing parameter for ``draw``
                                               shape=stn.array_shapes(min_dims=2, max_dims=2),
                                               elements=st.complex_numbers(max_magnitude=1e100, allow_nan=False, allow_infinity=False)),    # pylint: disable=line-too-long
                        "resolution": resolutions,
                        "labels": st.lists(elements=texts)}
spectrum_parameters = st.fixed_dictionaries(_spectrum_parameters)
spectrums = st.builds(sumpf.Spectrum, **_spectrum_parameters)

###############
# Spectrogram #
###############

_spectrogram_parameters = {"channels": stn.arrays(dtype=numpy.complex128,  # pylint: disable=no-value-for-parameter; there is a false alarm about a missing parameter for ``draw``
                                                  shape=stn.array_shapes(min_dims=3, max_dims=3),
                                                  elements=st.complex_numbers(max_magnitude=1e100, allow_nan=False, allow_infinity=False)),    # pylint: disable=line-too-long
                           "resolution": resolutions,
                           "sampling_rate": sampling_rates,
                           "offset": st.integers(min_value=-2 ** 24, max_value=2 ** 24),
Exemplo n.º 14
0
# END HEADER

from __future__ import division, print_function, absolute_import, \
    unicode_literals

import pytest
from hypothesis.strategies import just, sets, text, lists, binary, \
    floats, one_of, tuples, randoms, booleans, integers, frozensets, \
    sampled_from, complex_numbers, fixed_dictionaries
from hypothesis.searchstrategy.narytree import n_ary_tree
from hypothesis.searchstrategy.strategies import BadData, strategy


@pytest.mark.parametrize(('specifier', 'data'), [
    (sets(text()), 0j),
    (complex_numbers(), set('hi')),
    (lists(sets(booleans())), 0),
    (just(1), 'hi'),
    (binary(), 0.0),
    (binary(), frozenset()),
    (fixed_dictionaries({True: sets(integers())}), []),
    (randoms(), []),
    (integers(), ''),
    (integers(), [0, '']),
    (text(), 'kittens'),
    (tuples(integers(), integers(), integers()), (1, 2)),
    (sampled_from((1, 2, 3)), 'fish'),
    (sampled_from((1, 2, 3)), 5),
    (sampled_from((1, 2, 3)), -2),
    (one_of(integers(), floats()), 1),
    (one_of(integers(), floats()), 'tv'),
def test_minimal_nonzero_imaginary():
    assert minimal(complex_numbers(), lambda x: x.imag != 0) == 1j
Exemplo n.º 16
0
def test_repr_has_specifier_in_it():
    suite = TestComplex(
        u'test_can_round_trip_through_the_database')
    assert repr(suite) == u'strategy_test_suite(%r)' % (complex_numbers(),)
def test_minimal():
    assert minimal(complex_numbers(), lambda x: True) == 0
def test_minimal_nonzero_real():
    assert minimal(complex_numbers(), lambda x: x.real != 0) == 1
    assert minimal(complex_numbers(),
                   lambda x: x.imag < 0 and x.real < 0) == -1 - 1j


def test_minimal_quadrant4():
    assert minimal(complex_numbers(),
                   lambda x: x.imag < 0 and x.real > 0) == 1 - 1j


@given(st.data(), st.integers(-5, 5).map(lambda x: 10**x))
def test_max_magnitude_respected(data, mag):
    c = data.draw(complex_numbers(max_magnitude=mag))
    assert abs(c) <= mag * (1 + sys.float_info.epsilon)


@given(complex_numbers(max_magnitude=0))
def test_max_magnitude_zero(val):
    assert val == 0


@given(st.data(), st.integers(-5, 5).map(lambda x: 10**x))
def test_min_magnitude_respected(data, mag):
    c = data.draw(complex_numbers(min_magnitude=mag))
    assert (abs(c.real) >= mag or abs(c.imag) >= mag
            or abs(c) >= mag * (1 - sys.float_info.epsilon))


def test_minimal_min_magnitude_zero():
    assert minimal(complex_numbers(min_magnitude=0), lambda x: True) == 0

Exemplo n.º 20
0
        (-1.0, False),
        (True, False),
        (False, False),
        (dict(), False),
        ([], False),
        (tuple(), False),
        (object(), False),
    ],
)
def test_is_integer(obj, expected):
    assert is_integer(obj) is expected


@pytest.mark.skipif(
    PY2, reason="This hypothesis test hangs occasionally on Python 2")
@given(obj=st.one_of(
    st.none(),
    st.booleans(),
    st.text(),
    st.complex_numbers(),
    st.dates(),
    st.integers(),
    st.decimals(),
    st.lists(st.text()),
    st.dictionaries(st.text(), st.text()),
))
@settings(max_examples=100)
def test_maybe_stringify(obj):
    assert type(maybe_stringify(obj)) is (obj is not None and six.text_type
                                          or type(None))
def test_can_find_standard_complex_numbers():
    find(complex_numbers(), lambda x: x.imag != 0) == 0j
    find(complex_numbers(), lambda x: x.real != 0) == 1
def test_max_magnitude_respected(data, mag):
    c = data.draw(complex_numbers(max_magnitude=mag))
    assert abs(c) <= mag * (1 + sys.float_info.epsilon)
def test_minimal_quadrant1():
    assert minimal(complex_numbers(),
                   lambda x: x.imag > 0 and x.real > 0) == 1 + 1j
Exemplo n.º 24
0
def test_repr_has_specifier_in_it():
    suite = TestComplex(
        u'test_can_round_trip_through_the_database')
    assert repr(suite) == u'strategy_test_suite(%r)' % (complex_numbers(),)
Exemplo n.º 25
0
@given(st.data())
def test_overflowing_integers_are_deprecated(fill, data):
    kw = dict(elements=st.just(300))
    if fill:
        kw = dict(elements=st.nothing(), fill=kw["elements"])
    arr = data.draw(nps.arrays(dtype="int8", shape=(1,), **kw))
    assert arr[0] == (300 % 256)


@pytest.mark.parametrize("fill", [False, True])
@pytest.mark.parametrize(
    "dtype,strat",
    [
        ("float16", st.floats(min_value=65520, allow_infinity=False)),
        ("float32", st.floats(min_value=10 ** 40, allow_infinity=False)),
        ("complex64", st.complex_numbers(10 ** 300, allow_infinity=False)),
        ("U1", st.text(min_size=2, max_size=2)),
        ("S1", st.binary(min_size=2, max_size=2)),
    ],
)
@checks_deprecated_behaviour
@given(data=st.data())
def test_unrepresentable_elements_are_deprecated(fill, dtype, strat, data):
    if fill:
        kw = dict(elements=st.nothing(), fill=strat)
    else:
        kw = dict(elements=strat)
    arr = data.draw(nps.arrays(dtype=dtype, shape=(1,), **kw))
    try:
        # This is a float or complex number, and has overflowed to infinity,
        # triggering our deprecation for overflow.
Exemplo n.º 26
0
                  if sum(try_issubclass(k, T) for T in mapping) == 1]
    empty = ', '.join(repr(s) for s in strategies if s.is_empty)
    if empty or not strategies:  # pragma: no cover
        raise ResolutionFailed(
            'Could not resolve %s to a strategy; consider using '
            'register_type_strategy' % (empty or thing,))
    return st.one_of(strategies)


_global_type_lookup = {
    # Types with core Hypothesis strategies
    type(None): st.none(),
    bool: st.booleans(),
    int: st.integers(),
    float: st.floats(),
    complex: st.complex_numbers(),
    fractions.Fraction: st.fractions(),
    decimal.Decimal: st.decimals(),
    text_type: st.text(),
    bytes: st.binary(),
    datetime.datetime: st.datetimes(),
    datetime.date: st.dates(),
    datetime.time: st.times(),
    datetime.timedelta: st.timedeltas(),
    uuid.UUID: st.uuids(),
    tuple: st.builds(tuple),
    list: st.builds(list),
    set: st.builds(set),
    frozenset: st.builds(frozenset),
    dict: st.builds(dict),
    # Built-in types
Exemplo n.º 27
0
def complex_numbers(min_magnitude=0.,
                    max_magnitude=1e16,
                    allow_nan=ALLOW_NAN,
                    allow_infinity=ALLOW_INFINITY):
    return hps.complex_numbers(min_magnitude, max_magnitude, allow_nan,
                               allow_infinity)
Exemplo n.º 28
0
 floats(),
 floats(min_value=-2.0, max_value=3.0),
 floats(),
 floats(min_value=-2.0),
 floats(),
 floats(max_value=-0.0),
 floats(),
 floats(min_value=0.0),
 floats(min_value=3.14, max_value=3.14),
 text(),
 binary(),
 booleans(),
 tuples(booleans(), booleans()),
 frozensets(integers()),
 sets(frozensets(booleans())),
 complex_numbers(),
 fractions(),
 decimals(),
 lists(lists(booleans())),
 lists(lists(booleans(), average_size=100)),
 lists(floats(0.0, 0.0), average_size=1.0),
 ordered_pair,
 constant_list(integers()),
 streaming(integers()).map(lambda x: list(x[:2]) and x),
 integers().filter(lambda x: abs(x) > 100),
 floats(min_value=-sys.float_info.max, max_value=sys.float_info.max),
 none(),
 randoms(),
 tuples().flatmap(lambda x: EvalledIntStream),
 templates_for(integers(min_value=0, max_value=0).flatmap(lambda x: integers(min_value=0, max_value=0))),
 booleans().flatmap(lambda x: booleans() if x else complex_numbers()),
Exemplo n.º 29
0
    st.dates,
    st.datetimes,
    partial(st.characters, **ST_CODEPOINT_LIMIT),
    partial(st.text, st.characters(**ST_CODEPOINT_LIMIT))  # type: ignore
)

ST_TYPES_FLOAT_NAN: tp.Tuple[st.SearchStrategy, ...] = (
    st.floats,
    st.complex_numbers,
)

filter_nan = lambda x: not np.isnan(x)

ST_TYPES_FLOAT_NO_NAN: tp.Tuple[tp.Callable[[], st.SearchStrategy], ...] = (
    lambda: st.floats().filter(filter_nan),
    lambda: st.complex_numbers().filter(filter_nan))

ST_TYPES_UNARY_BINARY = (st.booleans, st.none)

# common collections

ST_TYPES_FOR_UNIQUE = ST_TYPES_FLOAT_NO_NAN + ST_TYPES_COMMON
ST_TYPES_FOR_UNIQUE_MIXED = ST_TYPES_FLOAT_NO_NAN + ST_TYPES_COMMON + ST_TYPES_UNARY_BINARY
ST_VALUE = ST_TYPES_FLOAT_NAN + ST_TYPES_COMMON + ST_TYPES_UNARY_BINARY


def get_value() -> st.SearchStrategy:
    '''
    Any plausible value.
    '''
    return st.one_of(strat() for strat in ST_VALUE)
Exemplo n.º 30
0
"""

from __future__ import print_function
from functools import wraps
import logging
from hypothesis import given, strategies as st, settings, Verbosity
from gc import collect as gc
import traceback
import sys
from time import time
from stricttuple import stricttuple

__all__ = 'battle_tested', 'fuzz', 'disable_traceback', 'enable_traceback', 'garbage', 'crash_map', 'success_map', 'results', 'stats', 'print_stats'

garbage = (st.binary(), st.booleans(), st.characters(), st.complex_numbers(),
           st.decimals(), st.floats(), st.fractions(), st.integers(),
           st.none(), st.random_module(), st.randoms(), st.text(), st.tuples(),
           st.uuids(), st.dictionaries(keys=st.text(), values=st.text()))
garbage += (
    # iterables
    st.lists(elements=st.one_of(*garbage)),
    st.iterables(elements=st.one_of(*garbage)),
    st.dictionaries(keys=st.text(), values=st.one_of(*garbage)))
garbage = st.one_of(*garbage)


def is_py3():
    return sys.version_info >= (3, 0)

def test_minimal_min_magnitude_zero():
    assert minimal(complex_numbers(min_magnitude=0), lambda x: True) == 0
Exemplo n.º 32
0

size_strategies = dict(
    min_size=st.integers(min_value=0, max_value=100) | st.none(),
    max_size=st.integers(min_value=0, max_value=100) | st.none(),
    average_size=st.floats(min_value=0.0, max_value=100.0) | st.none()
)


values = st.integers() | st.text(average_size=2.0)


Strategies = st.recursive(
    st.one_of(
        st.sampled_from([
            st.none(), st.booleans(), st.randoms(), st.complex_numbers(),
            st.randoms(), st.fractions(), st.decimals(),
        ]),
        st.builds(st.just, values),
        st.builds(st.sampled_from, st.lists(values, min_size=1)),
        builds_ignoring_invalid(st.floats, st.floats(), st.floats()),
    ),
    lambda x: st.one_of(
        builds_ignoring_invalid(st.lists, x, **size_strategies),
        builds_ignoring_invalid(st.sets, x, **size_strategies),
        builds_ignoring_invalid(
            lambda v: st.tuples(*v), st.lists(x, average_size=2.0)),
        builds_ignoring_invalid(
            lambda v: st.one_of(*v),
            st.lists(x, average_size=2.0, min_size=1)),
        builds_ignoring_invalid(
def test_minimal_min_magnitude_positive():
    assert minimal(complex_numbers(min_magnitude=0.5), lambda x: True) in (0.5, 1)
def test_minimal():
    assert minimal(complex_numbers(), lambda x: True) == 0
Exemplo n.º 35
0
            try_issubclass(k, T) for T in mapping) == 1
    ]
    empty = ', '.join(repr(s) for s in strategies if s.is_empty)
    if empty or not strategies:  # pragma: no cover
        raise ResolutionFailed(
            'Could not resolve %s to a strategy; consider using '
            'register_type_strategy' % (empty or thing, ))
    return st.one_of(strategies)


_global_type_lookup = {
    # Types with core Hypothesis strategies
    type(None): st.none(),
    bool: st.booleans(),
    float: st.floats(),
    complex: st.complex_numbers(),
    fractions.Fraction: st.fractions(),
    decimal.Decimal: st.decimals(),
    text_type: st.text(),
    bytes: st.binary(),
    datetime.datetime: st.datetimes(),
    datetime.date: st.dates(),
    datetime.time: st.times(),
    datetime.timedelta: st.timedeltas(),
    uuid.UUID: st.uuids(),
    tuple: st.builds(tuple),
    list: st.builds(list),
    set: st.builds(set),
    frozenset: st.builds(frozenset),
    dict: st.builds(dict),
    # Built-in types
def test_minimal_nonzero_imaginary():
    assert minimal(complex_numbers(), lambda x: x.imag != 0) == 1j
Exemplo n.º 37
0
    integers(min_value=(-(2 ** 32)), max_value=(2 ** 64)),
    floats(),
    floats(min_value=-2.0, max_value=3.0),
    floats(),
    floats(min_value=-2.0),
    floats(),
    floats(max_value=-0.0),
    floats(),
    floats(min_value=0.0),
    floats(min_value=3.14, max_value=3.14),
    text(),
    binary(),
    booleans(),
    tuples(booleans(), booleans()),
    frozensets(integers()),
    sets(frozensets(booleans())),
    complex_numbers(),
    fractions(),
    decimals(),
    lists(lists(booleans())),
    lists(floats(0.0, 0.0)),
    ordered_pair,
    constant_list(integers()),
    integers().filter(lambda x: abs(x) > 100),
    floats(min_value=-sys.float_info.max, max_value=sys.float_info.max),
    none(),
    randoms(),
    booleans().flatmap(lambda x: booleans() if x else complex_numbers()),
    recursive(base=booleans(), extend=lambda x: lists(x, max_size=3), max_leaves=10),
]
def test_minimal_quadrant4():
    assert minimal(complex_numbers(), lambda x: x.imag < 0 and x.real > 0) == 1 - 1j
Exemplo n.º 39
0
    )
)

TestRandom = strategy_test_suite(randoms())
TestInts = strategy_test_suite(integers())
TestBoolLists = strategy_test_suite(lists(booleans(), average_size=5.0))
TestDictionaries = strategy_test_suite(
    dictionaries(keys=tuples(integers(), integers()), values=booleans()))
TestOrderedDictionaries = strategy_test_suite(
    dictionaries(
        keys=integers(), values=integers(), dict_class=OrderedDict))
TestString = strategy_test_suite(text())
BinaryString = strategy_test_suite(binary())
TestIntBool = strategy_test_suite(tuples(integers(), booleans()))
TestFloats = strategy_test_suite(floats())
TestComplex = strategy_test_suite(complex_numbers())
TestJust = strategy_test_suite(just(u'hi'))
TestTemplates = strategy_test_suite(templates_for(sets(integers())))

TestEmptyString = strategy_test_suite(text(alphabet=u''))
TestSingleString = strategy_test_suite(
    text(alphabet=u'a', average_size=10.0))
TestManyString = strategy_test_suite(text(alphabet=u'abcdef☃'))

Stuff = namedtuple(u'Stuff', (u'a', u'b'))
TestNamedTuple = strategy_test_suite(
    builds(Stuff, integers(), integers()))

TestMixedSets = strategy_test_suite(sets(
    one_of(integers(), booleans(), floats())))
TestFrozenSets = strategy_test_suite(frozensets(booleans()))
def test_repr_has_specifier_in_it():
    suite = TestComplex(
        u'test_will_find_a_constant_failure')
    assert repr(suite) == u'strategy_test_suite(%r)' % (complex_numbers(),)
Exemplo n.º 41
0
            integers(min_value=8, max_value=15),
        )
    )
    TestRandom = strategy_test_suite(randoms())
    TestInts = strategy_test_suite(integers())
    TestBoolLists = strategy_test_suite(lists(booleans()))
    TestDictionaries = strategy_test_suite(
        dictionaries(keys=tuples(integers(), integers()), values=booleans()))
    TestOrderedDictionaries = strategy_test_suite(
        dictionaries(
            keys=integers(), values=integers(), dict_class=OrderedDict))
    TestString = strategy_test_suite(text())
    BinaryString = strategy_test_suite(binary())
    TestIntBool = strategy_test_suite(tuples(integers(), booleans()))
    TestFloats = strategy_test_suite(floats())
    TestComplex = strategy_test_suite(complex_numbers())
    TestJust = strategy_test_suite(just(u'hi'))
    TestTemplates = strategy_test_suite(templates_for(sets(integers())))

    TestEmptyString = strategy_test_suite(text(alphabet=u''))
    TestSingleString = strategy_test_suite(strategy(
        text(alphabet=u'a'), Settings(average_list_length=10.0)))
    TestManyString = strategy_test_suite(text(alphabet=u'abcdef☃'))

    Stuff = namedtuple(u'Stuff', (u'a', u'b'))
    TestNamedTuple = strategy_test_suite(
        builds(Stuff, integers(), integers()))

    TestTrees = strategy_test_suite(
        n_ary_tree(integers(), integers(), integers()))
def test_minimal_min_magnitude_none():
    assert minimal(complex_numbers(min_magnitude=None), lambda x: True) == 0
Exemplo n.º 43
0
 def define_complex_strategy(specifier, settings):
     return st.complex_numbers()
def test_minimal_minmax_magnitude():
    assert minimal(
        complex_numbers(min_magnitude=0.5, max_magnitude=1.5), lambda x: True
    ) in (0.5, 1)
Exemplo n.º 45
0
# END HEADER

from __future__ import division, print_function, absolute_import, \
    unicode_literals

import pytest
from hypothesis.strategies import just, sets, text, lists, binary, \
    floats, one_of, tuples, randoms, booleans, integers, frozensets, \
    sampled_from, complex_numbers, fixed_dictionaries
from hypothesis.searchstrategy.narytree import n_ary_tree
from hypothesis.searchstrategy.strategies import BadData, strategy


@pytest.mark.parametrize(('specifier', 'data'), [
    (sets(text()), 0j),
    (complex_numbers(), {'hi'}),
    (lists(sets(booleans())), 0),
    (just(1), 'hi'),
    (binary(), 0.0),
    (binary(), frozenset()),
    (fixed_dictionaries({True: sets(integers())}), []),
    (randoms(), []),
    (integers(), ''),
    (integers(), [0, '']),
    (text(), 'kittens'),
    (tuples(integers(), integers(), integers()), (1, 2)),
    (sampled_from((1, 2, 3)), 'fish'),
    (sampled_from((1, 2, 3)), 5),
    (sampled_from((1, 2, 3)), -2),
    (one_of(integers(), floats()), 1),
    (one_of(integers(), floats()), 'tv'),
def test_can_find_standard_complex_numbers():
    find(complex_numbers(), lambda x: x.imag != 0) == 0j
    find(complex_numbers(), lambda x: x.real != 0) == 1
Exemplo n.º 47
0
class HypothesisSpec(RuleBasedStateMachine):
    def __init__(self):
        super(HypothesisSpec, self).__init__()
        self.database = None

    strategies = Bundle('strategy')
    strategy_tuples = Bundle('tuples')
    objects = Bundle('objects')
    streaming_strategies = Bundle('streams')
    basic_data = Bundle('basic')
    varied_floats = Bundle('varied_floats')

    strats_with_parameters = Bundle('strats_with_parameters')
    strats_with_templates = Bundle('strats_with_templates')
    strats_with_2_templates = Bundle('strats_with_2_templates')

    def teardown(self):
        self.clear_database()

    @rule(target=basic_data, st=strats_with_templates)
    def to_basic(self, st):
        return st[0].to_basic(st[1])

    @rule(data=basic_data, strat=strategies)
    def from_basic(self, data, strat):
        try:
            template = strat.from_basic(data)
        except BadData:
            return
        strat.reify(template)

    @rule(target=basic_data, data=basic_data, r=randoms())
    def mess_with_basic(self, data, r):
        return mutate_basic(data, r)

    @rule()
    def clear_database(self):
        if self.database is not None:
            self.database.close()
            self.database = None

    @rule()
    def set_database(self):
        self.teardown()
        self.database = ExampleDatabase()

    @rule(st=strats_with_templates)
    def reify(self, st):
        strat, temp = st
        strat.reify(temp)

    @rule(target=strats_with_templates, st=strats_with_templates)
    def via_basic(self, st):
        strat, temp = st
        temp = strat.from_basic(strat.to_basic(temp))
        return (strat, temp)

    @rule(targets=(strategies, streaming_strategies), strat=strategies)
    def build_stream(self, strat):
        return strategy(streaming(strat))

    @rule(targets=(strategies, streaming_strategies),
          strat=strategies,
          i=integers(1, 10))
    def evalled_stream(self, strat, i):
        return strategy(streaming(strat)).map(lambda x: list(x[:i]) and x)

    @rule(stream_strat=streaming_strategies, index=integers(0, 50))
    def eval_stream(self, stream_strat, index):
        try:
            stream = stream_strat.example()
            list(stream[:index])
        except NoExamples:
            pass

    @rule(target=strats_with_templates, st=strats_with_templates, r=randoms())
    def simplify(self, st, r):
        strat, temp = st
        for temp in strat.full_simplify(r, temp):
            break
        return (strat, temp)

    @rule(strat=strategies, r=randoms(), mshr=integers(0, 100))
    def find_constant_failure(self, strat, r, mshr):
        with Settings(
                verbosity=Verbosity.quiet,
                max_examples=1,
                min_satisfying_examples=0,
                database=self.database,
                max_shrinks=mshr,
        ):

            @given(
                strat,
                random=r,
            )
            def test(x):
                assert False

            try:
                test()
            except AssertionError:
                pass

    @rule(strat=strategies,
          r=randoms(),
          p=floats(0, 1),
          mex=integers(1, 10),
          mshr=integers(1, 100))
    def find_weird_failure(self, strat, r, mex, p, mshr):
        with Settings(
                verbosity=Verbosity.quiet,
                max_examples=mex,
                min_satisfying_examples=0,
                database=self.database,
                max_shrinks=mshr,
        ):

            @given(
                strat,
                random=r,
            )
            def test(x):
                assert Random(hashlib.md5(
                    show(x).encode('utf-8')).digest()).random() <= p

            try:
                test()
            except AssertionError:
                pass

    @rule(target=strats_with_parameters, strat=strategies, r=randoms())
    def draw_parameter(self, strat, r):
        return (strat, strat.draw_parameter(r))

    @rule(target=strats_with_templates, sp=strats_with_parameters, r=randoms())
    def draw_template(self, sp, r):
        strat, param = sp
        return (strat, strat.draw_template(r, param))

    @rule(target=strats_with_2_templates,
          sp=strats_with_parameters,
          r=randoms())
    def draw_templates(self, sp, r):
        strat, param = sp
        return (
            strat,
            strat.draw_template(r, param),
            strat.draw_template(r, param),
        )

    @rule(st=strats_with_templates)
    def check_serialization(self, st):
        strat, template = st
        as_basic = strat.to_basic(template)
        assert show(strat.reify(template)) == show(
            strat.reify(strat.from_basic(as_basic)))
        assert as_basic == strat.to_basic(strat.from_basic(as_basic))

    @rule(target=strategies,
          spec=sampled_from((
              integers(),
              booleans(),
              floats(),
              complex_numbers(),
              fractions(),
              decimals(),
              text(),
              binary(),
              none(),
              StateMachineSearchStrategy(),
              tuples(),
          )))
    def strategy(self, spec):
        return spec

    @rule(target=strategies, values=lists(integers() | text(), min_size=1))
    def sampled_from_strategy(self, values):
        return sampled_from(values)

    @rule(target=strategies, spec=strategy_tuples)
    def strategy_for_tupes(self, spec):
        return tuples(*spec)

    @rule(target=strategies,
          source=strategies,
          level=integers(1, 10),
          mixer=text())
    def filtered_strategy(s, source, level, mixer):
        def is_good(x):
            return bool(
                Random(
                    hashlib.md5(
                        (mixer + show(x)).encode('utf-8')).digest()).randint(
                            0, level))

        return source.filter(is_good)

    @rule(target=strategies, elements=strategies)
    def list_strategy(self, elements):
        return lists(elements, average_size=AVERAGE_LIST_LENGTH)

    @rule(target=strategies, l=strategies, r=strategies)
    def or_strategy(self, l, r):
        return l | r

    @rule(target=strategies,
          source=strategies,
          result=strategies,
          mixer=text())
    def mapped_strategy(self, source, result, mixer):
        cache = {}

        def do_map(value):
            rep = show(value)
            try:
                return deepcopy(cache[rep])
            except KeyError:
                pass
            random = Random(
                hashlib.md5((mixer + rep).encode('utf-8')).digest())
            outcome_template = result.draw_and_produce(random)
            cache[rep] = result.reify(outcome_template)
            return deepcopy(cache[rep])

        return source.map(do_map)

    @rule(target=varied_floats, source=floats())
    def float(self, source):
        return source

    @rule(target=varied_floats,
          source=varied_floats,
          offset=integers(-100, 100))
    def adjust_float(self, source, offset):
        return int_to_float(clamp(0, float_to_int(source) + offset, 2**64 - 1))

    @rule(target=strategies, left=varied_floats, right=varied_floats)
    def float_range(self, left, right):
        for f in (math.isnan, math.isinf):
            for x in (left, right):
                assume(not f(x))
        left, right = sorted((left, right))
        assert left <= right
        return strategy(floats(left, right))

    @rule(target=strategies,
          source=strategies,
          result1=strategies,
          result2=strategies,
          mixer=text(),
          p=floats(0, 1))
    def flatmapped_strategy(self, source, result1, result2, mixer, p):
        assume(result1 is not result2)

        def do_map(value):
            rep = show(value)
            random = Random(
                hashlib.md5((mixer + rep).encode('utf-8')).digest())
            if random.random() <= p:
                return result1
            else:
                return result2

        return source.flatmap(do_map)

    @rule(target=strategies, value=objects)
    def just_strategy(self, value):
        return strategy(just(value))

    @rule(target=strategy_tuples, source=strategies)
    def single_tuple(self, source):
        return (source, )

    @rule(target=strategy_tuples, l=strategy_tuples, r=strategy_tuples)
    def cat_tuples(self, l, r):
        return l + r

    @rule(target=objects, strat=strategies)
    def get_example(self, strat):
        try:
            strat.example()
        except NoExamples:
            # Because of filtering some strategies we look for don't actually
            # have any examples.
            pass

    @rule(target=strategies, left=integers(), right=integers())
    def integer_range(self, left, right):
        left, right = sorted((left, right))
        return strategy(integers(left, right))

    @rule(strat=strategies)
    def repr_is_good(self, strat):
        assert ' at 0x' not in repr(strat)

    @rule(strat=strategies)
    def template_upper_bound_is_valid(self, strat):
        ub = strat.template_upper_bound
        assert ub >= 0
        if isinstance(ub, float):
            assert math.isinf(ub)
        else:
            assert isinstance(ub, int)

    @rule(strat=strategies, r=randoms())
    def can_find_as_many_templates_as_size(self, strat, r):
        tempstrat = templates_for(strat)
        n = min(10, strat.template_upper_bound)
        found = []
        with Settings(verbosity=Verbosity.quiet, timeout=2.0):
            for i in range(n):
                try:
                    x = find(
                        tempstrat,
                        lambda t: t not in found,
                        random=r,
                    )
                except:
                    print('Exception at %d/%d. template_upper_bound=%r' %
                          (i, n, strat.template_upper_bound))
                    raise
                found.append(x)