def test_can_find_nested():
    x = find(
        st.recursive(st.booleans(), lambda x: st.tuples(x, x)),
        lambda x: isinstance(x, tuple) and isinstance(x[0], tuple)
    )

    assert x == ((False, False), False)
def test_can_use_recursive_data_in_sets(rnd):
    nested_sets = st.recursive(
        st.booleans(),
        lambda js: st.frozensets(js, average_size=2.0),
        max_leaves=10
    )
    nested_sets.example(rnd)

    def flatten(x):
        if isinstance(x, bool):
            return frozenset((x,))
        else:
            result = frozenset()
            for t in x:
                result |= flatten(t)
                if len(result) == 2:
                    break
            return result
    assert rnd is not None
    x = find(
        nested_sets, lambda x: len(flatten(x)) == 2, random=rnd,
        settings=settings(database=None, max_shrinks=1000, max_examples=1000))
    assert x in (
        frozenset((False, True)),
        frozenset((False, frozenset((True,)))),
        frozenset((frozenset((False, True)),))
    )
Esempio n. 3
0
def test_can_form_sets_of_recursive_data():
    trees = st.sets(st.recursive(
        st.booleans(), lambda x: st.lists(x).map(tuple), max_leaves=4))
    xs = find(trees, lambda x: len(x) >= 10)
    assert len(xs) == 10
    assert False in xs
    assert True in xs
Esempio n. 4
0
def test_drawing_many_near_boundary():
    ls = find(
        st.lists(st.recursive(
            st.booleans(),
            lambda x: st.lists(x, min_size=8, max_size=10).map(tuple),
            max_leaves=9)),
        lambda x: len(set(x)) >= 5)
    assert len(ls) == 5
Esempio n. 5
0
def values():
    """Returns a strategy that unifies all strategies that produced valid JSON
    serializable values.
    """
    def extend(children):
        return arrays(children) | objects(children)
    simple_values = nulls() | booleans() | numbers() | strings()
    return simple_values | st.recursive(simple_values, extend)
def nested_checkboxes_list():
    def create_options_with_children(list_strategy):
        return st.lists(nested_checkboxes(options_list_strategy=list_strategy))

    return st.recursive(
        st.lists(nested_checkboxes()),
        create_options_with_children,
        max_leaves=15
    )
def test_can_form_sets_of_recursive_data():
    trees = st.sets(st.recursive(
        st.booleans(),
        lambda x: st.lists(x, min_size=5).map(tuple),
        max_leaves=20))
    xs = find(trees, lambda x: len(x) >= 10, settings=settings(
        database=None, timeout=20, max_shrinks=1000, max_examples=1000
    ))
    assert len(xs) == 10
Esempio n. 8
0
def comparison():
    """
    comparison: expr (comp_op expr)*
    """
    @st.composite
    def _comparison(draw, sub_expr):
        return _expr_builder(draw, not_test, 'and')

    return st.recursive(STRING(), _comparison)
Esempio n. 9
0
def not_test():
    """
    not_test: 'not' not_test | comparison
    """
    @st.composite
    def _not_test(draw, other_not_test):
        return 'not ' + draw(st.one_of(comparison(), other_not_test))

    return st.recursive(STRING(), _not_test)
Esempio n. 10
0
def test_can_form_sets_of_recursive_data():
    size = 3

    trees = st.sets(st.recursive(
        st.booleans(),
        lambda x: st.lists(x, min_size=size).map(tuple),
        max_leaves=20))
    xs = minimal(trees, lambda x: len(x) >= size, timeout_after=None)
    assert len(xs) == size
Esempio n. 11
0
def test_can_find_quite_broad_lists():
    def breadth(x):
        if isinstance(x, list):
            return sum(map(breadth, x))
        else:
            return 1

    broad = find(st.recursive(st.booleans(), lambda x: st.lists(x, max_size=10)), lambda x: breadth(x) >= 20)
    assert breadth(broad) == 20
Esempio n. 12
0
def test_can_find_quite_deep_lists():
    def depth(x):
        if x and isinstance(x, list):
            return 1 + max(map(depth, x))
        else:
            return 1

    deep = find(st.recursive(st.booleans(), lambda x: st.lists(x, max_size=3)), lambda x: depth(x) >= 5)
    assert deep == [[[[False]]]]
Esempio n. 13
0
def test_can_generate_some_depth_with_large_branching():
    def depth(x):
        if x and isinstance(x, list):
            return 1 + max(map(depth, x))
        else:
            return 1

    xs = find(st.recursive(st.integers(), lambda x: st.lists(x, average_size=100)), lambda x: depth(x) > 1)
    assert xs == [0]
Esempio n. 14
0
def test_drawing_many_near_boundary():
    ls = find(
        st.lists(st.recursive(
            st.booleans(),
            lambda x: st.lists(x, min_size=8, max_size=10).map(tuple),
            max_leaves=9)),
        lambda x: len(set(x)) >= 5,
        settings=settings(max_examples=10000, database=None, max_shrinks=2000)
    )
    assert len(ls) == 5
Esempio n. 15
0
def test_can_form_sets_of_recursive_data():
    trees = st.sets(st.recursive(
        st.booleans(),
        lambda x: st.lists(x, min_size=5).map(tuple),
        max_leaves=10))
    xs = find(trees, lambda x: len(x) >= 10, settings=settings(
        database=None
    ))
    print(xs)
    assert len(xs) == 10
    assert False in xs
    assert True in xs
Esempio n. 16
0
def test_can_generate_some_depth_with_large_branching():
    def depth(x):
        if x and isinstance(x, list):
            return 1 + max(map(depth, x))
        else:
            return 1
    xs = minimal(
        st.recursive(st.integers(), st.lists),
        lambda x: depth(x) > 1,
        timeout_after=None,
    )
    assert xs in ([0], [[]])
Esempio n. 17
0
def test_broad_recursive_data_will_fail_a_health_check():
    r = st.recursive(
        st.integers(), lambda s: st.tuples(*((s,) * 10)),
        max_leaves=10,
    )

    @given(st.tuples(r, r, r, r, r, r, r))
    def test(x):
        pass

    with raises(FailedHealthCheck):
        test()
def mutated_commands(commands):
    args = st.sampled_from([b'withscores', b'xx', b'nx', b'ex', b'px', b'weights', b'aggregate',
                            b'', b'0', b'-1', b'nan', b'inf', b'-inf']) | command_args(commands)
    affixes = st.sampled_from([b'\0', b'-', b'+', b'\t', b'\n', b'0000']) | st.binary()
    return st.recursive(
        commands,
        lambda x:
            delete_arg(x)
            | replace_arg(x, args)
            | uppercase_arg(x)
            | prefix_arg(x, affixes)
            | suffix_arg(x, affixes)
            | add_arg(x, args)
            | swap_args(x))
Esempio n. 19
0
def test_drawing_many_near_boundary():
    target = 4

    ls = minimal(
        st.lists(st.recursive(
            st.booleans(),
            lambda x: st.lists(
                x, min_size=2 * (target - 1), max_size=2 * target
            ).map(tuple),
            max_leaves=2 * target - 1)),
        lambda x: len(set(x)) >= target,
        timeout_after=None
    )
    assert len(ls) == target
def monoids():
    base = many_one_of(
        strat.integers(),
        strat.lists(strat.integers()),
        strat.lists(strat.integers()).map(tuple),
        strat.text(),
        strat.integers().map(MonoidProduct),
        strat.dictionaries(strat.integers(), strat.integers()),
    )

    def recurse(substrat):
        return stream_apply_strat(maybes(), substrat)

    return strat.recursive(base, recurse)
Esempio n. 21
0
def test_can_generate_with_large_branching():
    def flatten(x):
        if isinstance(x, list):
            return sum(map(flatten, x), [])
        else:
            return [x]

    xs = find(
        st.recursive(
            st.integers(), lambda x: st.lists(x, average_size=50),
            max_leaves=100),
        lambda x: isinstance(x, list) and len(flatten(x)) >= 50
    )
    assert flatten(xs) == [0] * 50
Esempio n. 22
0
def nested_dtypes(subtype_strategy=scalar_dtypes(),
                  max_leaves=10, max_itemsize=None):
    """Return the most-general dtype strategy.

    Elements drawn from this strategy may be simple (from the
    subtype_strategy), or several such values drawn from
    :func:`array_dtypes` with ``allow_subarrays=True``. Subdtypes in an
    array dtype may be nested to any depth, subject to the max_leaves
    argument.

    """
    return st.recursive(subtype_strategy,
                        lambda x: array_dtypes(x, allow_subarrays=True),
                        max_leaves).filter(
        lambda d: max_itemsize is None or d.itemsize <= max_itemsize)
def test_can_find_quite_broad_lists():
    def breadth(x):
        if isinstance(x, list):
            return sum(map(breadth, x))
        else:
            return 1

    target = 10

    broad = minimal(
        st.recursive(st.booleans(), lambda x: st.lists(x, max_size=target // 2)),
        lambda x: breadth(x) >= target,
        settings=settings(max_examples=10000),
        timeout_after=None,
    )
    assert breadth(broad) == target
Esempio n. 24
0
def action_structures(draw):
    """
    A Hypothesis strategy that creates a tree of L{ActionStructure} and
    L{unicode}.
    """
    tree = draw(st.recursive(labels, st.lists, max_leaves=50))

    def to_structure(tree_or_message):
        if isinstance(tree_or_message, list):
            return ActionStructure(
                type=draw(labels),
                failed=draw(st.booleans()),
                children=[to_structure(o) for o in tree_or_message])
        else:
            return tree_or_message
    return to_structure(tree)
Esempio n. 25
0
def test_can_use_recursive_data_in_sets(rnd):
    nested_sets = st.recursive(st.booleans(), lambda js: st.frozensets(js), max_leaves=10)
    nested_sets.example()

    def flatten(x):
        if isinstance(x, bool):
            return frozenset((x,))
        else:
            result = frozenset()
            for t in x:
                result |= flatten(t)
                if len(result) == 2:
                    break
            return result

    x = find(nested_sets, lambda x: len(flatten(x)) == 2, random=rnd, settings=Settings(database=None))
    assert x == frozenset((False, True))
Esempio n. 26
0
def test_can_generate_with_large_branching():
    def flatten(x):
        if isinstance(x, list):
            return sum(map(flatten, x), [])
        else:
            return [x]

    size = 20

    xs = minimal(
        st.recursive(
            st.integers(), lambda x: st.lists(x, min_size=size // 2),
            max_leaves=size * 2),
        lambda x: isinstance(x, list) and len(flatten(x)) >= size,
        timeout_after=None,
    )
    assert flatten(xs) == [0] * size
Esempio n. 27
0
def factor():
    """
    factor: ('+'|'-'|'~') factor | atom trailer*
    """
    @st.composite
    def _multi_atom_trailer(draw):
        result = [draw(atom())]
        iter_count = range(draw(st.integers(1, 5)))
        result += [draw(trailer()) for _ in iter_count]
        return ' '.join(result)

    @st.composite
    def _factor(draw, other_factor):
        unary = st.sampled_from('+-~ ')
        strategy = st.one_of(other_factor, _multi_atom_trailer())
        return unary + draw(strategy)

    return st.recursive(st.just(''), _factor)
Esempio n. 28
0
def test_can_flatmap_to_recursive_data(rnd):
    stuff = st.lists(st.integers(), min_size=1).flatmap(
        lambda elts: st.recursive(st.sampled_from(elts), lambda x: st.lists(x, average_size=25), max_leaves=25)
    )

    def flatten(x):
        if isinstance(x, integer_types):
            return [x]
        else:
            return sum(map(flatten, x), [])

    tree = find(
        stuff,
        lambda x: sum(flatten(x)) >= 100,
        settings=Settings(database=None, max_shrinks=1000, max_examples=1000),
        random=rnd,
    )
    flat = flatten(tree)
    assert (sum(flat) == 1000) or (len(set(flat)) == 1)
def test_can_use_recursive_data_in_sets(rnd):
    nested_sets = st.recursive(st.booleans(), st.frozensets, max_leaves=3)
    find_any(nested_sets, random=rnd)

    def flatten(x):
        if isinstance(x, bool):
            return frozenset((x,))
        else:
            result = frozenset()
            for t in x:
                result |= flatten(t)
                if len(result) == 2:
                    break
            return result

    assert rnd is not None
    x = minimal(nested_sets, lambda x: len(flatten(x)) == 2, random=rnd)
    assert x in (
        frozenset((False, True)),
        frozenset((False, frozenset((True,)))),
        frozenset((frozenset((False, True)),)),
    )
Esempio n. 30
0
from hypothesis.strategies import (
    booleans,
    dictionaries,
    floats,
    lists,
    none,
    recursive,
    text,
    composite,
)
from hypothesis import assume
from string import printable
import json


printable_without_slash = "".join(c for c in printable if c != "/")
_json_strategy = recursive(
    none() | booleans() | floats() | text(printable_without_slash),
    lambda children: lists(children, 1)
    | dictionaries(text(printable_without_slash), children, min_size=1),
)


@composite
def json_strategy(draw):
    example = draw(_json_strategy)
    s = json.dumps(example)
    # assume("/" not in s)
    return s
Esempio n. 31
0
def test_recursive_call_validates_expand_returns_strategies():
    with pytest.raises(InvalidArgument):
        st.recursive(st.booleans(), lambda x: 1).example()
Esempio n. 32
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(
            st.dictionaries,
            x,
            x,
            dict_class=st.sampled_from([dict, OrderedDict]),
            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(
            )),
        st.builds(lambda s, f: s.map(f), x, st.sampled_from(fns)),
    ))
Esempio n. 33
0
    # Then convert the newly created to the dictionary format
    lst = lst.map(lambda v: {'type': 'VertaList', 'name': '', 'value': v})

    # Create printable text for the keys
    name = st.text(printable)
    # Create a list of (name, subtree) where the names are unique
    dikt = st.lists(st.tuples(name, children), 1, 10, unique_by=lambda v: v[0])
    # Then iterate over them replacing the given name (which is empty) with the given name
    dikt = dikt.map(lambda lst: [dict_replace(el, 'name', n) for n, el in lst])
    # Then convert the newly created to the dictionary format
    dikt = dikt.map(lambda d: {'type': 'VertaJson', 'name': '', 'value': d})

    # Return either the list or the dictionary
    return lst | dikt


# Create a model api by doing this recursively
model_api = st.recursive(modelapi_base, recursive)

# pandas-specific types
name = st.text(printable)
model_api_series = st.tuples(
    name, modelapi_base).map(lambda arg: dict_replace(arg[1], 'name', arg[0]))
model_api_dataframe = st.lists(model_api_series,
                               1,
                               unique_by=lambda x: x['name']).map(lambda v: {
                                   'type': 'VertaJson',
                                   'name': '',
                                   'value': v
                               })
Esempio n. 34
0
import hypothesis.strategies as st

from jmespath import lexer
from jmespath import parser
from jmespath import exceptions
from jmespath.functions import Functions

if sys.version_info[:2] == (2, 6):
    raise RuntimeError("Hypothesis tests are not supported on python2.6. "
                       "Use python2.7, or python3.3 and greater.")

JSON_NUMBERS = (st.integers()
                | st.floats(allow_nan=False, allow_infinity=False))

RANDOM_JSON = st.recursive(
    JSON_NUMBERS | st.booleans() | st.text() | st.none(),
    lambda children: st.lists(children) | st.dictionaries(st.text(), children))

MAX_EXAMPLES = int(os.environ.get('JP_MAX_EXAMPLES', 1000))
BASE_SETTINGS = {
    'max_examples': MAX_EXAMPLES,
    'suppress_health_check': [HealthCheck.too_slow],
}


# For all of these tests they verify these proprties:
# either the operation succeeds or it raises a JMESPathError.
# If any other exception is raised then we error out.
@settings(**BASE_SETTINGS)
@given(st.text())
def test_lexer_api(expr):
Esempio n. 35
0
def test_can_find_nested():
    x = find(st.recursive(st.booleans(), lambda x: st.tuples(x, x)),
             lambda x: isinstance(x, tuple) and isinstance(x[0], tuple))

    assert x == ((False, False), False)
Esempio n. 36
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()),
        recursive(
            base=booleans(), extend=lambda x: lists(x, max_size=3),
            max_leaves=10,
        )
    ]


def parametrize(args, values):
    return pytest.mark.parametrize(args, values, ids=list(map(show, values)))
Esempio n. 37
0
import pytest
from cove.input.models import SuppliedData
from django.core.files.base import ContentFile
from hypothesis import HealthCheck, assume, example, given, settings
from hypothesis import strategies as st
from libcoveocds.lib.common_checks import get_releases_aggregates
"""
## Suggested testing patterns (from CamPUG talk)
* simple fuzzing
* round trip
* invariants and idempotents
* test oracle
"""

general_json = st.recursive(
    st.floats() | st.integers() | st.booleans() | st.text() | st.none(),
    lambda children: st.lists(children) | st.dictionaries(st.text(), children),
)


@given(general_json)
def test_get_releases_aggregates(json_data):
    get_releases_aggregates(json_data)


@given(general_json)
@settings(suppress_health_check=[HealthCheck.too_slow])
def test_get_releases_aggregates_dict(json_data):
    assume(type(json_data) is dict)
    get_releases_aggregates(json_data)

Esempio n. 38
0
def nested_complex_types(inner_strategy=primitive_types):
    return st.recursive(inner_strategy, complex_types)
Esempio n. 39
0
import superintendent.prioritisation
from superintendent.distributed import MultiLabeller
from superintendent.controls import MulticlassSubmitter

primitive_strategy = text() | integers() | floats(allow_nan=False) | booleans()

guaranteed_dtypes = (boolean_dtypes()
                     | integer_dtypes()
                     | floating_dtypes()
                     | unicode_string_dtypes())

container_strategy = dictionaries(
    text(), primitive_strategy) | lists(primitive_strategy)

nested_strategy = recursive(
    container_strategy,
    lambda children: lists(children) | dictionaries(text(), children),
)

container_strategy = dictionaries(
    text(), primitive_strategy) | lists(primitive_strategy)

nested_strategy = recursive(
    container_strategy,
    lambda children: lists(children) | dictionaries(text(), children),
)

numpy_strategy = arrays(guaranteed_dtypes, array_shapes())

pandas_series = series(dtype=int) | series(dtype=float) | series(dtype=str)

pandas_dfs = (data_frames(columns(3, dtype=int))
Esempio n. 40
0

# map()
@given(integers(min_value=0).map(lambda i: i * 2))
def test_even3(value):
    print(value)


# flatmap()
@given(
    integers(min_value=2, max_value=3).flatmap(
        lambda n: lists(integers(min_value=0).filter(lambda i: i % n == 0))))
def test_all_mod_same(values):
    print(values)


# Recursion()
@given(
    recursive(
        none() | booleans() | floats() | text(printable),
        lambda children: lists(children, 1) | dictionaries(
            text(printable), children, min_size=1)))
def test_recursive(x):
    print(x)


# Strategies inferred from annotations
@given(bla=infer, foo=infer)
def test_foo(bla: int, foo: str):
    print(bla, foo)
Esempio n. 41
0
    a = pikepdf.Array(array)
    assert a == array


@given(
    lists(lists(integers(1, 10), min_size=1, max_size=5),
          min_size=1,
          max_size=5))
def test_nested_list(array):
    a = pikepdf.Array(array)
    assert a == array


@given(
    recursive(integers(1, 10) | booleans(),
              lambda children: lists(children),
              max_leaves=20))
def test_nested_list2(array):
    assume(isinstance(array, list))
    a = pikepdf.Array(array)
    assert a == array


def test_list_apis():
    a = pikepdf.Array([1, 2, 3])
    a[1] = None
    assert a[1] is None
    assert len(a) == 3
    del a[1]
    assert len(a) == 2
    a[-1] = Name('/Foo')
Esempio n. 42
0
import numpy as np
import hypothesis.strategies as st
primitive_data = st.floats(allow_nan=False) | st.booleans() | st.text() | st.none() \
                 | st.fractions() | st.integers() | st.characters()
#| st.complex_numbers() \ nanj is annoying to deal with
#| st.decimals() can add back in once a new version of joblib is released with bug fix

hashable_data = primitive_data | st.tuples(primitive_data)
sets = st.sets(hashable_data)
builtin_data = st.recursive(
    primitive_data | sets, lambda children: st.lists(children) | st.
    dictionaries(st.text(), children) | st.tuples(children))


def rand_nparray(seed, w=3, h=3):
    rnd = np.random.RandomState(seed)
    return rnd.random_sample((w, h))


np_random_states = st.integers(0, 4294967295).map(np.random.RandomState)
fixed_numpy_arrays = st.integers(0, 4294967295).map(rand_nparray)
numpy_data = fixed_numpy_arrays
data = st.recursive(
    primitive_data | sets | fixed_numpy_arrays, lambda children: st.lists(
        children) | st.dictionaries(st.text(), children) | st.tuples(children))
Esempio n. 43
0
    @mark.parametrize("arguments,expected", parameters_default)
    def test_parameters_default(self, arguments, expected):
        """Test that the default parameters from f_transform work as expected."""
        result = f_transform(**arguments)
        assert result == expected

    @mark.parametrize("arguments,expected", parameters_moving)
    def test_parameters_moving(self, arguments, expected):
        """Test that different parameters for f_transform work as expected."""
        result = f_transform(**arguments)
        assert result == expected


@given(recursive(booleans() | floats() | none() | text() | integers(),
                 lambda children: lists(children,
                                        min_size=1) | tuples(children,
                                                             children),
                 max_leaves=3))
@settings(verbosity=Verbosity.verbose)
def test_gen_arg(arg):
    """Test the generator in svgjoin"""
    gen = gen_arg(arg)
    assert isinstance(gen, Generator)
    size = randint(10, 40)
    if isinstance(arg, str) or not isinstance(arg, iter_type):
        assert [next(gen) for _ in range(size)] == [arg for _ in range(size)]
    else:
        arg = list(arg)  # be subscriptable
        assert ([next(gen) for _ in range(size)] ==
                arg + [arg[-1] for _ in range(size - len(arg))])
Esempio n. 44
0

def duration_millis_ignore_warn(delta):
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        return duration_millis(delta)


millis_timedelta_strategy = st.timedeltas(min_value=timedelta(milliseconds=1))

millis_uint64_strategy = millis_timedelta_strategy.map(duration_millis_ignore_warn)

# from https://hypothesis.readthedocs.io/en/latest/data.html#recursive-data
json_strategy = st.recursive(
    st.none() | st.booleans() | st.floats() | st.text(string.printable),
    lambda children: st.lists(children)
    | st.dictionaries(st.text(string.printable), children),
    max_leaves=500,
)


@st.composite
def filepath(draw):
    """A valid filepath. Does **not** create the file.

    Returns
    -------
    str

    """
    # https://stackoverflow.com/q/4814040#comment38006480_4814088
    # TODO: add more characters; macOS and Windows allow swaths of Unicode
Esempio n. 45
0
def single_type_lists(draw, types=s.integers()):
    """Create lists drawn from only one of the types generated by the argument
    strategy.

    """
    v = draw(types)
    if isinstance(v, list) and len(v) > 0:
        es = s.lists(s.from_type(type(v[0])))
    else:
        es = s.from_type(type(v))
    vl = draw(s.lists(es))
    return vl

toml_vals = s.recursive(
    s.text() | s.integers() | s.floats() | s.booleans() |
    s.datetimes(timezones=s.none() | timezones()) |
    s.dates() | s.times(),
    lambda leaves: (single_type_lists(leaves) |
                    s.dictionaries(s.text(), leaves)))

# Top-level TOML element must be a dict
toml_data = s.dictionaries(s.text(), toml_vals)

@given(toml_data)
def test_circular_encode(data):
    assert patch_floats(qtoml.loads(qtoml.dumps(data))) == patch_floats(data)

@given(s.text())
def test_string_encode(data):
    obj = {'key': data}
    assert qtoml.loads(qtoml.dumps(obj)) == obj
Esempio n. 46
0
def shuffle_dict(_dict):
    keys = list(_dict.keys())
    random.shuffle(keys)
    for key in keys:
        yield key, _dict[key]


def extend_fn(children):
    lists_st = st.lists(children)
    dicts_st = st.dictionaries(st.text(), children)
    return lists_st | dicts_st


all_st = st.recursive(
    st.none() | st.integers() | st.booleans() | st.floats() | st.text()
    | st.binary(),
    extend_fn,
)


def recursive_shuffle_dict(v):
    if isinstance(v, dict):
        return shuffle_dict(v)
    elif isinstance(v, (list, tuple)):
        return type(v)((recursive_shuffle_dict(_v) for _v in v))
    else:
        return v


@given(value=all_st)
def test_key_generation_is_deterministic(value):
Esempio n. 47
0
# obtain one at http://mozilla.org/MPL/2.0/.
#
# END HEADER

from __future__ import division, print_function, absolute_import

import pytest

import hypothesis.strategies as st
from hypothesis import find, given
from hypothesis.errors import InvalidArgument


@given(
    st.recursive(st.booleans(),
                 lambda x: st.lists(x, average_size=20),
                 max_leaves=10))
def test_respects_leaf_limit(xs):
    def flatten(x):
        if isinstance(x, list):
            return sum(map(flatten, x), [])
        else:
            return [x]

    assert len(flatten(xs)) <= 10


def test_can_find_nested():
    x = find(st.recursive(st.booleans(), lambda x: st.tuples(x, x)),
             lambda x: isinstance(x, tuple) and isinstance(x[0], tuple))
Esempio n. 48
0
array_type_strs = st.tuples(non_array_type_strs, array_list_strs).map(join)

non_tuple_type_strs = st.one_of(non_array_type_strs, array_type_strs)


def join_tuple(xs):
    if not isinstance(xs, list):
        return xs

    return '({})'.format(','.join(join_tuple(x) for x in xs))


tuple_type_strs = st.recursive(
    st.lists(non_tuple_type_strs, min_size=0, max_size=10),
    lambda this_strategy: st.lists(
        st.one_of(non_tuple_type_strs, this_strategy),
        min_size=0,
        max_size=10,
    ),
).map(join_tuple)

type_strs = st.one_of(non_tuple_type_strs, tuple_type_strs)


def guaranteed_permute(xs):
    len_xs = len(xs)
    indices = tuple(range(len_xs))

    shuffled_indices = indices
    while indices == shuffled_indices:
        shuffled_indices = tuple(random.sample(indices, k=len_xs))
Esempio n. 49
0
def effects(value_strategy: SearchStrategy[A],
            include_errors: bool = False,
            max_size: int = 10,
            max_leaves: int = 10) -> SearchStrategy[TestEffect[A]]:
    """
    Create a search strategy that produces `pfun.effect.Effect` instances

    Args:
        value_strategy: search strategy used to draw success values
        include_errors: whether to include effects that fail
        max_size: max size of effects that produces iterables \
            (such as `pfun.effect.sequence`)
        max_leaves: max number of leaf effects \
            (`pfun.effect.success`, `pfun.effect.from_callable` etc) \
            to be drawn
    Example:
        >>> e = effects(integers()).example()
        >>> e
        success(0)
        >>> e.run(None)
        0
    Return:
        search strategy that produces `pfun.effect.Effect` instances
    """
    def extend(
        children: SearchStrategy[TestEffect[A]]
    ) -> SearchStrategy[TestEffect[A]]:
        maps: SearchStrategy[TestEffect[A]] = children.flatmap(
            lambda e: unaries(value_strategy).map(lambda f: e.map(f)))
        and_then = children.flatmap(
            lambda e: unaries(children).map(lambda f: e.and_then(f)))
        discard_and_then = children.flatmap(
            lambda e: children.map(lambda e2: e.discard_and_then(e2)))
        either = children.map(lambda e: e.either())
        recover = children.flatmap(
            lambda e: children.map(lambda e2: e.recover(lambda _: e2)))
        memoize = children.map(lambda e: e.memoize())
        ensure = children.flatmap(
            lambda e: children.map(lambda e2: e.ensure(e2)))
        with_repr = children.flatmap(
            lambda e: text(printable).map(lambda s: e.with_repr(s)))
        sequence: SearchStrategy[TestEffect[Iterable[A]]] = lists_(
            children, max_size=10).map(effect.sequence)
        sequence_async: SearchStrategy[TestEffect[Iterable[A]]] = lists_(
            children, max_size=max_size).map(effect.sequence_async)
        lift = unaries(value_strategy).flatmap(
            lambda f: children.map(lambda e: effect.lift(f)(e)))
        lift_io_bound = unaries(value_strategy).flatmap(
            lambda f: children.map(lambda e: effect.lift_io_bound(f)(e)))
        lift_cpu_bound = unaries(value_strategy).flatmap(
            lambda f: children.map(lambda e: effect.lift_cpu_bound(f)(e)))
        combine = unaries(value_strategy).flatmap(
            lambda f: children.map(lambda e: effect.combine(e)(f)))
        combine_io_bound = unaries(value_strategy).flatmap(
            lambda f: children.map(lambda e: effect.combine_io_bound(e)(f)))
        combine_cpu_bound = unaries(value_strategy).flatmap(
            lambda f: children.map(lambda e: effect.combine_cpu_bound(e)(f)))

        return one_of(maps, and_then, discard_and_then, either, recover,
                      memoize, ensure, with_repr, sequence, sequence_async,
                      lift, lift_io_bound, lift_cpu_bound, combine,
                      combine_io_bound, combine_cpu_bound)

    success = builds(effect.success, value_strategy)
    depends: SearchStrategy[effect.Effect[Any, NoReturn,
                                          Any]] = builds(effect.depend)
    from_callable: SearchStrategy[TestEffect[A]] = unaries(
        rights(value_strategy)).map(effect.from_callable)
    from_io_bound_callable: SearchStrategy[TestEffect[A]] = unaries(
        rights(value_strategy)).map(effect.from_io_bound_callable)
    from_cpu_bound_callable: SearchStrategy[TestEffect[A]] = unaries(
        rights(value_strategy)).map(effect.from_cpu_bound_callable)
    catch: SearchStrategy[TestEffect[A]] = unaries(value_strategy).flatmap(
        lambda f: value_strategy.map(lambda a: effect.catch(Exception)(f)(a)))
    catch_io_bound: SearchStrategy[TestEffect[A]] = unaries(
        value_strategy).flatmap(lambda f: value_strategy.map(
            lambda a: effect.catch_io_bound(Exception)(f)(a)))
    catch_cpu_bound: SearchStrategy[TestEffect[A]] = unaries(
        value_strategy).flatmap(lambda f: value_strategy.map(
            lambda a: effect.catch_cpu_bound(Exception)(f)(a)))

    base = (success
            | from_callable
            | from_io_bound_callable
            | from_cpu_bound_callable
            | depends
            | catch
            | catch_io_bound
            | catch_cpu_bound)

    if include_errors:
        errors = builds(effect.error, value_strategy)
        base = base | errors

    return recursive(base, extend, max_leaves=10)
        h, s, v = colorsys.rgb_to_hsv(r, g, b)
        r2, g2, b2 = colorsys.hsv_to_rgb(h, s, v)
        self.assertColorsValid(r=(r, r2), g=(g, g2), b=(b, b2))

        h2, s2, v2 = colorsys.rgb_to_hls(r2, g2, b2)
        self.assertColorsValid(h=(h, h2), s=(s, s2), v=(v, v2))


text_strategy = st.text(alphabet=st.characters(
    blacklist_categories=["Cc", "Cs"]))

plistlib_data = st.recursive(
    st.booleans()
    | st.binary()
    | st.datetimes().map(lambda d: d.replace(microsecond=0))
    | st.integers(min_value=-1 << 63, max_value=1 << 64 - 1)
    | st.floats(allow_nan=False)
    | text_strategy,
    lambda sub_strategy: st.lists(sub_strategy)
    | st.dictionaries(text_strategy, sub_strategy),
)


class TestPlistlib(unittest.TestCase):
    @settings(suppress_health_check=HealthCheck.all())
    @given(
        payload=plistlib_data,
        fmt=st.sampled_from([plistlib.FMT_XML, plistlib.FMT_BINARY]),
        pass_format_arg=st.booleans(),
    )
    def test_dumps_loads(self, payload, fmt, pass_format_arg):
        plist_dump = plistlib.dumps(payload, fmt=fmt)
Esempio n. 51
0
    return (attr.ib(default=default), val_strat)


def simple_attrs(defaults=None):
    return (bare_attrs(defaults)
            | int_attrs(defaults)
            | str_attrs(defaults)
            | float_attrs(defaults)
            | dict_attrs(defaults))


def lists_of_attrs(defaults=None):
    # Python functions support up to 255 arguments.
    return st.lists(simple_attrs(defaults), max_size=10).map(
        lambda l: sorted(l, key=lambda t: t[0]._default is not NOTHING))


def simple_classes(defaults=None):
    """
    Return a strategy that yields tuples of simple classes and values to
    instantiate them.
    """
    return lists_of_attrs(defaults).flatmap(_create_hyp_class)


# Ok, so st.recursive works by taking a base strategy (in this case,
# simple_classes) and a special function. This function receives a strategy,
# and returns another strategy (building on top of the base strategy).
nested_classes = st.recursive(simple_classes(defaults=True),
                              _create_hyp_nested_strategy)
Esempio n. 52
0
from tests.strategies.factories import to_nested_expressions

MAX_EXPONENT = 10
MIN_EXPONENT = -MAX_EXPONENT
exponents = strategies.integers(MIN_EXPONENT, MAX_EXPONENT)
negative_exponents = strategies.integers(MIN_EXPONENT, -1)
non_negative_exponents = strategies.integers(0, MAX_EXPONENT)
positive_exponents = strategies.integers(1, MAX_EXPONENT)
digits_counts = strategies.none() | strategies.integers(-100, 100)
zero_expressions = strategies.just(Zero)
unary_expressions = strategies.just(One)
unary_reals_or_expressions = unary_reals | unary_expressions
zero_reals_or_expressions = zero_reals | zero_expressions
finite_square_roots = strategies.builds(sqrt, finite_non_negative_reals)
finite_expressions = strategies.recursive(finite_square_roots,
                                          to_nested_expressions,
                                          max_leaves=3)
finite_reals_or_expressions = finite_reals | finite_expressions
finite_non_zero_expressions = finite_expressions.filter(bool)
finite_non_zero_reals_or_expressions = (finite_non_zero_reals
                                        | finite_non_zero_expressions)
positive_infinite_expressions = strategies.builds(sqrt,
                                                  positive_infinite_reals)
negative_infinite_expressions = positive_infinite_expressions.map(neg)
infinite_expressions = (negative_infinite_expressions
                        | positive_infinite_expressions)
definite_expressions = finite_expressions | infinite_expressions
definite_reals_or_expressions = definite_reals | definite_expressions
definite_non_zero_expressions = definite_expressions.filter(bool)
definite_non_zero_reals_or_expressions = (definite_non_zero_reals
                                          | definite_non_zero_expressions)
Esempio n. 53
0
    slots_flag = draw(st.booleans()) if slots is None else slots

    if private_attrs is None:
        attr_names = maybe_underscore_prefix(gen_attr_names())
    elif private_attrs is True:
        attr_names = ("_" + n for n in gen_attr_names())
    elif private_attrs is False:
        attr_names = gen_attr_names()

    cls_dict = dict(zip(attr_names, attrs))
    post_init_flag = draw(st.booleans())
    if post_init_flag:

        def post_init(self):
            pass

        cls_dict["__attrs_post_init__"] = post_init

    return make_class("HypClass",
                      cls_dict,
                      slots=slots_flag,
                      frozen=frozen_flag)


# st.recursive works by taking a base strategy (in this case, simple_classes)
# and a special function.  This function receives a strategy, and returns
# another strategy (building on top of the base strategy).
nested_classes = st.recursive(simple_classes(),
                              _create_hyp_nested_strategy,
                              max_leaves=10)
Esempio n. 54
0
                    TASK_UUID_FIELD:
                    task_uuid,
                    TASK_LEVEL_FIELD:
                    sibling_task_level(start_message, 2 + len(children)),
                }))
    else:
        end_message = None

    return WrittenAction.from_messages(start_message, children, end_message)


written_actions = recursive(
    written_messages,
    lambda children: builds(
        _make_written_action,
        start_message=start_action_messages,
        child_messages=lists(children, max_size=5),
        end_message_dict=builds(union, message_dicts, _end_action_fields) |
        none(),
    ),
)


def _map_messages(f, written_action):
    """
    Map C{f} across all of the messages that make up C{written_action}.

    This is a structure-preserving map operation. C{f} will be applied to all
    messages that make up C{written_action}: the start message, end message,
    and children. If any of the children are themselves L{WrittenAction}s, we
    recurse down into them.
Esempio n. 55
0
# contribution.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.
#
# END HEADER

import pytest

from hypothesis import given, strategies as st
from hypothesis.errors import InvalidArgument
from tests.common.debug import find_any, minimal


@given(st.recursive(st.booleans(), st.lists, max_leaves=10))
def test_respects_leaf_limit(xs):
    def flatten(x):
        if isinstance(x, list):
            return sum(map(flatten, x), [])
        else:
            return [x]

    assert len(flatten(xs)) <= 10


def test_can_find_nested():
    x = minimal(
        st.recursive(st.booleans(), lambda x: st.tuples(x, x)),
        lambda x: isinstance(x, tuple) and isinstance(x[0], tuple),
    )
                  lists(text(), average_size=5.0), tuples(text(), text()),
                  booleans(), lists(complex_numbers()))).flatmap(lambda x: x))


def integers_from(x):
    return integers(min_value=x)


TestManyFlatmaps = strategy_test_suite(
    integers().flatmap(integers_from).flatmap(integers_from).flatmap(
        integers_from).flatmap(integers_from))

TestRecursiveLowLeaves = strategy_test_suite(
    recursive(
        booleans(),
        lambda x: tuples(x, x),
        max_leaves=3,
    ))

TestRecursiveHighLeaves = strategy_test_suite(
    recursive(
        booleans(),
        lambda x: lists(x, min_size=2, max_size=10),
        max_leaves=200,
    ))

TestJSON = strategy_test_suite(
    recursive(floats().filter(lambda f: not math.isnan(f) or math.isinf(f))
              | text() | booleans() | none(),
              lambda js: lists(js, average_size=2) | dictionaries(
                  text(), js, average_size=2),
Esempio n. 57
0
def test_recursive_call_validates_base_is_strategy():
    x = st.recursive(1, lambda x: st.none())
    with pytest.raises(InvalidArgument):
        x.example()
Esempio n. 58
0
    assert a == array


@given(
    lists(lists(integers(1, 10), min_size=1, max_size=5),
          min_size=1,
          max_size=5))
def test_nested_list(array):
    a = pikepdf.Array(array)
    assert a == array


@given(
    recursive(
        integers(1, 10) | booleans(),
        lambda children: lists(children),  # pylint: disable=unnecessary-lambda
        max_leaves=20,
    ))
def test_nested_list2(array):
    assume(isinstance(array, list))
    a = pikepdf.Array(array)
    assert a == array


def test_list_apis():
    a = pikepdf.Array([1, 2, 3])
    a[1] = None
    assert a[1] is None
    assert len(a) == 3
    del a[1]
    assert len(a) == 2
Esempio n. 59
0
    assert headers_to_scrapy([('Content-Type', 'text/html')]) == html_headers
    assert headers_to_scrapy([{'name': 'Content-Type', 'value': 'text/html'}]) == html_headers


_primitive = (
    st.floats(allow_infinity=False, allow_nan=False) |
    st.booleans() |
    st.text() |
    st.none() |
    st.integers()
)
_data = st.recursive(_primitive,
    lambda children: (
        children |
        st.lists(children) |
        st.tuples(children) |
        st.dictionaries(st.text(), children) |
        st.tuples(st.just('h'), children)
    ),
    max_leaves=5,
)
_data_notuples = st.recursive(_primitive,
    lambda children: (
        children |
        st.lists(children) |
        st.dictionaries(st.text(), children)
    ),
    max_leaves=5,
)


@given(_data, _data)
Esempio n. 60
0
def nested_struct_types(item_strategy=primitive_types):
    return st.recursive(item_strategy, struct_types)