Beispiel #1
0
def test_resolves_NewType():
    typ = typing.NewType('T', int)
    nested = typing.NewType('NestedT', typ)
    uni = typing.NewType('UnionT', typing.Optional[int])
    assert isinstance(from_type(typ).example(), integer_types)
    assert isinstance(from_type(nested).example(), integer_types)
    assert isinstance(from_type(uni).example(), integer_types + (type(None),))
Beispiel #2
0
def test_register_generic_typing_strats():
    # I don't expect anyone to do this, but good to check it works as expected
    try:
        # We register sets for the abstract sequence type, which masks subtypes
        # from supertype resolution but not direct resolution
        st.register_type_strategy(
            typing.Sequence,
            types._global_type_lookup[typing.Set]
        )

        @given(from_type(typing.Sequence[int]))
        def inner_1(ex):
            assert isinstance(ex, set)

        @given(from_type(typing.Container[int]))
        def inner_2(ex):
            assert not isinstance(ex, typing.Sequence)

        @given(from_type(typing.List[int]))
        def inner_3(ex):
            assert isinstance(ex, list)

        inner_1()
        inner_2()
        inner_3()
    finally:
        types._global_type_lookup.pop(typing.Sequence)
        st.from_type.__clear_cache()
def test_cannot_resolve_bare_forward_reference(thing):
    with pytest.raises(InvalidArgument):
        t = thing["int"]
        if type(getattr(t, "__args__", [None])[0]) != ForwardRef:
            assert sys.version_info[:2] == (3, 5)
            pytest.xfail("python 3.5 typing module is really weird")
        st.from_type(t).example()
Beispiel #4
0
def test_variable_length_tuples(n):
    type_ = typing.Tuple[int, ...]
    try:
        from_type(type_).filter(lambda ex: len(ex) == n).example()
    except NoExamples:
        if sys.version_info[:2] < (3, 6):
            pytest.skip()
        raise
def test_custom_type_resolution_with_function_non_strategy():
    try:
        st.register_type_strategy(UnknownType, lambda _: None)
        with pytest.raises(ResolutionFailed):
            st.from_type(UnknownType).example()
        with pytest.raises(ResolutionFailed):
            st.from_type(ParentUnknownType).example()
    finally:
        types._global_type_lookup.pop(UnknownType)
def test_custom_type_resolution_with_function():
    sentinel = object()
    try:
        st.register_type_strategy(UnknownType, lambda _: st.just(sentinel))
        assert st.from_type(UnknownType).example() is sentinel
        assert st.from_type(ParentUnknownType).example() is sentinel
    finally:
        types._global_type_lookup.pop(UnknownType)
        st.from_type.__clear_cache()
def test_lookup_overrides_defaults(typ):
    sentinel = object()
    try:
        strat = types._global_type_lookup[typ]
        st.register_type_strategy(typ, st.just(sentinel))
        assert st.from_type(typ).example() is sentinel
    finally:
        st.register_type_strategy(typ, strat)
        st.from_type.__clear_cache()
    assert st.from_type(typ).example() is not sentinel
def test_custom_type_resolution():
    sentinel = object()
    try:
        st.register_type_strategy(UnknownType, st.just(sentinel))
        assert st.from_type(UnknownType).example() is sentinel
        # Also covered by registration of child class
        assert st.from_type(ParentUnknownType).example() is sentinel
    finally:
        types._global_type_lookup.pop(UnknownType)
        st.from_type.__clear_cache()
        assert UnknownType not in types._global_type_lookup
def test_errors_if_generic_resolves_empty():
    try:
        st.register_type_strategy(UnknownType, lambda _: st.nothing())
        fails_1 = st.from_type(UnknownType)
        with pytest.raises(ResolutionFailed):
            fails_1.example()
        fails_2 = st.from_type(ParentUnknownType)
        with pytest.raises(ResolutionFailed):
            fails_2.example()
    finally:
        types._global_type_lookup.pop(UnknownType)
        st.from_type.__clear_cache()
Beispiel #10
0
def from_typing_type(thing):
    # We start with special-case support for Union and Tuple - the latter
    # isn't actually a generic type.  Support for Callable may be added to
    # this section later.
    # We then explicitly error on non-Generic types, which don't carry enough
    # information to sensibly resolve to strategies at runtime.
    # Finally, we run a variation of the subclass lookup in st.from_type
    # among generic types in the lookup.
    import typing
    # Under 3.6 Union is handled directly in st.from_type, as the argument is
    # not an instance of `type`. However, under Python 3.5 Union *is* a type
    # and we have to handle it here, including failing if it has no parameters.
    if hasattr(thing, '__union_params__'):  # pragma: no cover
        args = sorted(thing.__union_params__ or (), key=type_sorting_key)
        if not args:
            raise ResolutionFailed('Cannot resolve Union of no types.')
        return st.one_of([st.from_type(t) for t in args])
    if isinstance(thing, typing.TupleMeta):
        elem_types = getattr(thing, '__tuple_params__', None) or ()
        elem_types += getattr(thing, '__args__', None) or ()
        if getattr(thing, '__tuple_use_ellipsis__', False) or \
                len(elem_types) == 2 and elem_types[-1] is Ellipsis:
            return st.lists(st.from_type(elem_types[0])).map(tuple)
        return st.tuples(*map(st.from_type, elem_types))
    # Now, confirm that we're dealing with a generic type as we expected
    if not isinstance(thing, typing.GenericMeta):  # pragma: no cover
        raise ResolutionFailed('Cannot resolve %s to a strategy' % (thing,))
    # Parametrised generic types have their __origin__ attribute set to the
    # un-parametrised version, which we need to use in the subclass checks.
    # e.g.:     typing.List[int].__origin__ == typing.List
    mapping = {k: v for k, v in _global_type_lookup.items()
               if isinstance(k, typing.GenericMeta) and
               try_issubclass(k, getattr(thing, '__origin__', None) or thing)}
    if typing.Dict in mapping:
        # The subtype relationships between generic and concrete View types
        # are sometimes inconsistent under Python 3.5, so we pop them out to
        # preserve our invariant that all examples of from_type(T) are
        # instances of type T - and simplify the strategy for abstract types
        # such as Container
        for t in (typing.KeysView, typing.ValuesView, typing.ItemsView):
            mapping.pop(t, None)
    strategies = [v if isinstance(v, st.SearchStrategy) else v(thing)
                  for k, v in mapping.items()
                  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)
def everything_except(excluded_types):
    """Recipe copied from the docstring of ``from_type``"""
    return (
        st.from_type(type)
        .flatmap(st.from_type)
        .filter(lambda x: not isinstance(x, excluded_types))
    )
def test_typevar_type_is_consistent(data, var, expected):
    strat = st.from_type(var)
    v1 = data.draw(strat)
    v2 = data.draw(strat)
    assume(v1 != v2)  # Values may vary, just not types
    assert type(v1) == type(v2)
    assert isinstance(v1, expected)
Beispiel #13
0
        def wrapped_test(*arguments, **kwargs):
            # Tell pytest to omit the body of this function from tracebacks
            __tracebackhide__ = True

            settings = wrapped_test._hypothesis_internal_use_settings

            random = get_random_for_wrapped_test(test, wrapped_test)

            if infer in generator_kwargs.values():
                hints = get_type_hints(test)
            for name in [name for name, value in generator_kwargs.items()
                         if value is infer]:
                if name not in hints:
                    raise InvalidArgument(
                        'passed %s=infer for %s, but %s has no type annotation'
                        % (name, test.__name__, name))
                generator_kwargs[name] = st.from_type(hints[name])

            processed_args = process_arguments_to_given(
                wrapped_test, arguments, kwargs, generator_arguments,
                generator_kwargs, argspec, test, settings
            )
            arguments, kwargs, test_runner, search_strategy = processed_args

            execute_explicit_examples(
                test_runner, test, wrapped_test, settings, arguments, kwargs
            )

            if settings.max_examples <= 0:
                return

            if not (
                Phase.reuse in settings.phases or
                Phase.generate in settings.phases
            ):
                return

            try:
                perform_health_checks(
                    random, settings, test_runner, search_strategy)

                state = StateForActualGivenExecution(
                    test_runner, search_strategy, test, settings, random)
                state.run()
            except:
                generated_seed = \
                    wrapped_test._hypothesis_internal_use_generated_seed
                if generated_seed is not None:
                    if running_under_pytest:
                        report((
                            'You can add @seed(%(seed)d) to this test or run '
                            'pytest with --hypothesis-seed=%(seed)d to '
                            'reproduce this failure.') % {
                                'seed': generated_seed},)
                    else:
                        report((
                            'You can add @seed(%d) to this test to reproduce '
                            'this failure.') % (generated_seed,))
                raise
def test_cannot_register_empty():
    # Cannot register and did not register
    with pytest.raises(InvalidArgument):
        st.register_type_strategy(UnknownType, st.nothing())
    fails = st.from_type(UnknownType)
    with pytest.raises(ResolutionFailed):
        fails.example()
    assert UnknownType not in types._global_type_lookup
def test_resolve_core_strategies(typ):
    @given(st.from_type(typ))
    def inner(ex):
        if PY2 and issubclass(typ, integer_types):
            assert isinstance(ex, integer_types)
        else:
            assert isinstance(ex, typ)

    inner()
 def resolve_Callable(thing):
     # Generated functions either accept no arguments, or arbitrary arguments.
     # This is looser than ideal, but anything tighter would generally break
     # use of keyword arguments and we'd rather not force positional-only.
     if not thing.__args__:  # pragma: no cover  # varies by minor version
         return st.functions()
     return st.functions(
         like=(lambda: None) if len(thing.__args__) == 1 else (lambda *a, **k: None),
         returns=st.from_type(thing.__args__[-1]),
     )
Beispiel #17
0
def test_36_specialised_collection_types():
    @given(from_type(typing.DefaultDict[int, int]))
    def inner(ex):
        if sys.version_info[:2] >= (3, 6):
            assume(ex)
        assert isinstance(ex, collections.defaultdict)
        assert all(isinstance(elem, int) for elem in ex)
        assert all(isinstance(elem, int) for elem in ex.values())

    inner()
Beispiel #18
0
def test_lookup_overrides_defaults():
    sentinel = object()
    try:
        st.register_type_strategy(int, st.just(sentinel))

        @given(from_type(typing.List[int]))
        def inner_1(ex):
            assert all(elem is sentinel for elem in ex)

        inner_1()
    finally:
        st.register_type_strategy(int, st.integers())
        st.from_type.__clear_cache()

    @given(from_type(typing.List[int]))
    def inner_2(ex):
        assert all(isinstance(elem, int) for elem in ex)

    inner_2()
Beispiel #19
0
def test_ItemsView():
    @given(from_type(typing.ItemsView[int, int]))
    def inner(ex):
        # See https://github.com/python/typing/issues/177
        if sys.version_info[:2] >= (3, 6):
            assume(ex)
        assert isinstance(ex, type({}.items()))
        assert all(isinstance(elem, tuple) and len(elem) == 2 for elem in ex)
        assert all(all(isinstance(e, int) for e in elem) for elem in ex)

    inner()
def types_to_strategy(attrib, types):
    """Find all the type metadata for this attribute, reconcile it, and infer a
    strategy from the mess."""
    # If we know types from the validator(s), that's sufficient.
    if len(types) == 1:
        typ, = types
        if isinstance(typ, tuple):
            return st.one_of(*map(st.from_type, typ))
        return st.from_type(typ)
    elif types:
        # We have a list of tuples of types, and want to find a type
        # (or tuple of types) that is a subclass of all of of them.
        type_tuples = [k if isinstance(k, tuple) else (k,) for k in types]
        # Flatten the list, filter types that would fail validation, and
        # sort so that ordering is stable between runs and shrinks well.
        allowed = [
            t
            for t in set(sum(type_tuples, ()))
            if all(issubclass(t, tup) for tup in type_tuples)
        ]
        allowed.sort(key=type_sorting_key)
        return st.one_of([st.from_type(t) for t in allowed])

    # Otherwise, try the `type` attribute as a fallback, and finally try
    # the type hints on a converter (desperate!) before giving up.
    if isinstance(getattr(attrib, "type", None), type):
        # The convoluted test is because variable annotations may be stored
        # in string form; attrs doesn't evaluate them and we don't handle them.
        # See PEP 526, PEP 563, and Hypothesis issue #1004 for details.
        return st.from_type(attrib.type)

    converter = getattr(attrib, "converter", None)
    if isinstance(converter, type):
        return st.from_type(converter)
    elif callable(converter):
        hints = get_type_hints(converter)
        if "return" in hints:
            return st.from_type(hints["return"])

    return st.nothing()
Beispiel #21
0
def test_specialised_collection_types(typ, coll_type, instance_of):
    @given(from_type(typ))
    def inner(ex):
        if sys.version_info[:2] >= (3, 6):
            assume(ex)
        assert isinstance(ex, coll_type)
        assert all(isinstance(elem, instance_of) for elem in ex)

    try:
        inner()
    except (ResolutionFailed, AssertionError):
        if sys.version_info[:2] < (3, 6):
            pytest.skip('Hard-to-reproduce bug (early version of typing?)')
        raise
Beispiel #22
0
def test_resolve_typing_module(typ):
    @given(from_type(typ))
    def inner(ex):
        if typ in (typing.BinaryIO, typing.TextIO):
            assert isinstance(ex, io.IOBase)
        elif typ is typing.Tuple:
            # isinstance is incompatible with Tuple on early 3.5
            assert ex == ()
        elif isinstance(typ, typing._ProtocolMeta):
            pass
        else:
            try:
                assert isinstance(ex, typ)
            except TypeError:
                if sys.version_info[:2] < (3, 6):
                    pytest.skip()
                raise

    inner()
def test_resolve_typing_module(typ):
    @settings(suppress_health_check=[HealthCheck.too_slow, HealthCheck.filter_too_much])
    @given(from_type(typ))
    def inner(ex):
        if typ in (typing.BinaryIO, typing.TextIO):
            assert isinstance(ex, io.IOBase)
        elif typ is typing.Tuple:
            # isinstance is incompatible with Tuple on early 3.5
            assert ex == ()
        elif isinstance(typ, typing._ProtocolMeta):
            pass
        elif typ is typing.Type and not isinstance(typing.Type, type):
            assert isinstance(ex, typing.TypeVar)
        else:
            try:
                assert isinstance(ex, typ)
            except TypeError:
                if sys.version_info[:2] < (3, 6):
                    pytest.skip()
                raise

    inner()
Beispiel #24
0
def _from_hashable_type(type_):
    if type_ in ALWAYS_HASHABLE_TYPES:
        return st.from_type(type_)
    else:
        return st.from_type(type_).filter(_can_hash)
Beispiel #25
0
def resolve_Dict(thing):
    # If thing is a Collection instance, we need to fill in the values
    keys_vals = thing.__args__ * 2
    return st.dictionaries(
        _from_hashable_type(keys_vals[0]), st.from_type(keys_vals[1])
    )
Beispiel #26
0
def test_resolves_forwardrefs_to_builtin_types(t):
    v = st.from_type(typing.ForwardRef(t.__name__)).example()
    assert isinstance(v, t)
Beispiel #27
0
def resolve_List(thing):
    return st.lists(st.from_type(thing.__args__[0]))
Beispiel #28
0
def test_repr_passthrough(typ, repr_):
    assert repr(st.from_type(typ)) == repr_
Beispiel #29
0
def test_typevars_can_be_redefined():
    """We test that one can register a custom strategy for all type vars."""
    A = typing.TypeVar("A")

    with temp_registered(typing.TypeVar, st.just(1)):
        assert_all_examples(st.from_type(A), lambda obj: obj == 1)
Beispiel #30
0
def test_can_register_NewType():
    Name = typing.NewType("Name", str)
    st.register_type_strategy(Name, st.just("Eric Idle"))
    assert st.from_type(Name).example() == "Eric Idle"
Beispiel #31
0
def test_cannot_resolve_bare_forward_reference(thing):
    with pytest.raises(InvalidArgument):
        t = thing["ConcreteFoo"]
        st.from_type(t).example()
Beispiel #32
0
 def resolve_KeysView(thing):
     return st.dictionaries(st.from_type(thing.__args__[0]), st.none()
                            ).map(dict.keys)
Beispiel #33
0
 def resolve_Iterator(thing):
     return st.iterables(st.from_type(thing.__args__[0]))
Beispiel #34
0
 def resolve_FrozenSet(thing):
     return st.frozensets(st.from_type(thing.__args__[0]))
Beispiel #35
0
def test_bytestring_is_valid_sequence_of_int_and_parent_classes(type_):
    find_any(
        st.from_type(typing.Sequence[type_]),
        lambda val: isinstance(val, typing.ByteString),
    )
Beispiel #36
0
def test_resolves_type_of_builtin_types(t):
    v = st.from_type(typing.Type[t.__name__]).example()
    assert v is t
Beispiel #37
0
def resolve_ValuesView(thing):
    return st.dictionaries(st.integers(), st.from_type(thing.__args__[0])).map(
        dict.values
    )
Beispiel #38
0
def test_resolves_weird_types(typ):
    from_type(typ).example()
Beispiel #39
0
def test_resolving_recursive_type_with_registered_constraint():
    with temp_registered(SomeClass,
                         st.builds(SomeClass, value=st.integers(min_value=1))):
        find_any(st.from_type(SomeClass), lambda s: s.next_node is None)
        find_any(st.from_type(SomeClass), lambda s: s.next_node is not None)
Beispiel #40
0
def test_from_type_can_be_default_or_annotation():
    find_any(st.from_type(AnnotatedAndDefault), lambda x: x.foo is None)
    find_any(st.from_type(AnnotatedAndDefault),
             lambda x: isinstance(x.foo, bool))
Beispiel #41
0
def test_specialised_scalar_types(data, typ, instance_of):
    ex = data.draw(from_type(typ))
    assert isinstance(ex, instance_of)
Beispiel #42
0
def test_typing_Type_int():
    assert from_type(typing.Type[int]).example() is int
Beispiel #43
0
def test_generic_collections_only_use_hashable_elements(typ, data):
    data.draw(from_type(typ))
Beispiel #44
0
def test_timezone_lookup(type_):
    assert issubclass(type_, datetime.tzinfo)
    assert_all_examples(st.from_type(type_), lambda t: isinstance(t, type_))
Beispiel #45
0
def everything_except(
        excluded_types: Union[type, Tuple[type,
                                          ...]]) -> st.SearchStrategy[Any]:
    return (st.from_type(type).flatmap(
        st.from_type).filter(lambda x: not isinstance(x, excluded_types)))
Beispiel #46
0
def test_resolves_builtin_types(t):
    v = st.from_type(t).example()
    assert isinstance(v, t)
Beispiel #47
0
def test_variable_length_tuples(n):
    type_ = typing.Tuple[int, ...]
    from_type(type_).filter(lambda ex: len(ex) == n).example()
Beispiel #48
0
import decimal
import typing as t

from hypothesis import given, strategies as st
import pytest

from genbu import Param, InvalidOption
from genbu.params import default_aggregator


@pytest.mark.parametrize("dest,optargs", [
    ("foo", ["--foo=bar"]),
    ("bar", ["--bar baz"]),
])
def test_param_with_invalid_option(dest: str, optargs: t.List[str]) -> None:
    """Param should raise InvalidOption if option dest has = or whitespace."""
    with pytest.raises(InvalidOption):
        Param(dest=dest, optargs=optargs)
    assert Param(dest=dest)


@given(
    st.lists(
        st.from_type(object).filter(
            lambda x: type(x) not in (complex, float, decimal.Decimal), ),
        min_size=1,
    ), )
def test_default_aggregator(lst: t.List[t.Any]) -> None:
    """default_aggregator should return last element."""
    assert default_aggregator(lst) == lst[-1]
Beispiel #49
0
@attr.s
class Required(object):
    a = attr.ib()


@attr.s
class UnhelpfulConverter(object):
    a = attr.ib(converter=lambda x: x)


@given(st.builds(Inferrables, has_default=infer, has_default_factory=infer))
def test_attrs_inference_builds(c):
    pass


@given(st.from_type(Inferrables))
def test_attrs_inference_from_type(c):
    pass


@pytest.mark.parametrize("c", [Required, UnhelpfulConverter])
def test_cannot_infer(c):
    with pytest.raises(ResolutionFailed):
        st.builds(c).example()


def test_cannot_infer_takes_self():
    with pytest.raises(ResolutionFailed):
        st.builds(Inferrables, has_default_factory_takes_self=infer).example()
Beispiel #50
0
def from_typing_type(thing):
    # We start with special-case support for Union and Tuple - the latter
    # isn't actually a generic type. Then we handle Literal since it doesn't
    # support `isinstance`.
    #
    # We then explicitly error on non-Generic types, which don't carry enough
    # information to sensibly resolve to strategies at runtime.
    # Finally, we run a variation of the subclass lookup in `st.from_type`
    # among generic types in the lookup.
    if getattr(thing, "__origin__", None) == tuple or isinstance(
        thing, getattr(typing, "TupleMeta", ())
    ):
        elem_types = getattr(thing, "__tuple_params__", None) or ()
        elem_types += getattr(thing, "__args__", None) or ()
        if (
            getattr(thing, "__tuple_use_ellipsis__", False)
            or len(elem_types) == 2
            and elem_types[-1] is Ellipsis
        ):
            return st.lists(st.from_type(elem_types[0])).map(tuple)
        elif len(elem_types) == 1 and elem_types[0] == ():
            return st.tuples()  # Empty tuple; see issue #1583
        return st.tuples(*map(st.from_type, elem_types))
    if hasattr(typing, "Final") and getattr(thing, "__origin__", None) == typing.Final:
        return st.one_of([st.from_type(t) for t in thing.__args__])
    if is_typing_literal(thing):
        args_dfs_stack = list(thing.__args__)
        literals = []
        while args_dfs_stack:
            arg = args_dfs_stack.pop()
            if is_typing_literal(arg):
                args_dfs_stack.extend(reversed(arg.__args__))
            else:
                literals.append(arg)
        return st.sampled_from(literals)
    # Now, confirm that we're dealing with a generic type as we expected
    if not isinstance(thing, typing_root_type):  # pragma: no cover
        raise ResolutionFailed("Cannot resolve %s to a strategy" % (thing,))

    # Some "generic" classes are not generic *in* anything - for example both
    # Hashable and Sized have `__args__ == ()` on Python 3.7 or later.
    # (In 3.6 they're just aliases for the collections.abc classes)
    origin = getattr(thing, "__origin__", thing)
    if (
        typing.Hashable is not collections.abc.Hashable
        and origin in vars(collections.abc).values()
        and len(getattr(thing, "__args__", None) or []) == 0
    ):
        return st.from_type(origin)

    # Parametrised generic types have their __origin__ attribute set to the
    # un-parametrised version, which we need to use in the subclass checks.
    # e.g.:     typing.List[int].__origin__ == typing.List
    mapping = {
        k: v
        for k, v in _global_type_lookup.items()
        if is_generic_type(k) and try_issubclass(k, thing)
    }
    if typing.Dict in mapping:
        # ItemsView can cause test_lookup.py::test_specialised_collection_types
        # to fail, due to weird isinstance behaviour around the elements.
        mapping.pop(typing.ItemsView, None)
        if sys.version_info[:2] == (3, 6):  # pragma: no cover
            # `isinstance(dict().values(), Container) is False` on py36 only -_-
            mapping.pop(typing.ValuesView, None)
    if len(mapping) > 1:
        # issubclass treats bytestring as a kind of sequence, which it is,
        # but treating it as such breaks everything else when it is presumed
        # to be a generic sequence or container that could hold any item.
        # Except for sequences of integers, or unions which include integer!
        # See https://github.com/HypothesisWorks/hypothesis/issues/2257
        #
        # This block drops ByteString from the types that can be generated
        # if there is more than one allowed type, and the element type is
        # not either `int` or a Union with `int` as one of its elements.
        elem_type = (getattr(thing, "__args__", None) or ["not int"])[0]
        if getattr(elem_type, "__origin__", None) is typing.Union:
            union_elems = elem_type.__args__
        else:
            union_elems = ()
        if not any(
            isinstance(T, type) and issubclass(int, T)
            for T in list(union_elems) + [elem_type]
        ):
            mapping.pop(typing.ByteString, None)
    strategies = [
        v if isinstance(v, st.SearchStrategy) else v(thing)
        for k, v in mapping.items()
        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:
        raise ResolutionFailed(
            "Could not resolve %s to a strategy; consider using "
            "register_type_strategy" % (empty or thing,)
        )
    return st.one_of(strategies)
Beispiel #51
0
                  st.just("reason")),
        enumerate:
        st.builds(enumerate, st.just(())),
        filter:
        st.builds(filter, st.just(lambda _: None), st.just(
            ())),  # type: ignore
        map:
        st.builds(map, st.just(lambda _: None), st.just(())),  # type: ignore
        reversed:
        st.builds(reversed, st.just(())),  # type: ignore
        classmethod:
        st.builds(classmethod, st.just(lambda self: self)),
        staticmethod:
        st.builds(staticmethod, st.just(lambda self: self)),
        super:
        st.builds(super, st.from_type(type)),
        # Pull requests with more types welcome!
    }
if zoneinfo is not None:  # pragma: no branch
    _global_type_lookup[zoneinfo.ZoneInfo] = st.timezones()
if PYPY:
    _global_type_lookup[builtins.sequenceiterator] = st.builds(
        iter, st.tuples())  # type: ignore

_global_type_lookup[type] = st.sampled_from(
    [type(None)] + sorted(_global_type_lookup, key=str))

if sys.version_info[:2] >= (3, 7):  # pragma: no branch
    _global_type_lookup[re.Match] = (st.text().map(
        lambda c: re.match(".", c, flags=re.DOTALL)).filter(bool))
    _global_type_lookup[re.Pattern] = st.builds(re.compile,
Beispiel #52
0
def test_does_not_resolve_special_cases(typ):
    with pytest.raises(InvalidArgument):
        from_type(typ).example()
Beispiel #53
0
 def resolve_List(thing):
     return st.lists(st.from_type(thing.__args__[0]))
Beispiel #54
0
def resolve_Iterator(thing):
    return st.iterables(st.from_type(thing.__args__[0]))
Beispiel #55
0
 def resolve_Dict(thing):
     # If thing is a Collection instance, we need to fill in the values
     keys_vals = [st.from_type(t) for t in thing.__args__] * 2
     return st.dictionaries(keys_vals[0], keys_vals[1])
Beispiel #56
0
def resolve_Counter(thing):
    return st.dictionaries(
        keys=st.from_type(thing.__args__[0]),
        values=st.integers(),
    ).map(collections.Counter)
Beispiel #57
0
 def resolve_ValuesView(thing):
     return st.dictionaries(st.integers(), st.from_type(thing.__args__[0])
                            ).map(dict.values)
Beispiel #58
0
def resolve_deque(thing):
    return st.lists(st.from_type(thing.__args__[0])).map(collections.deque)
Beispiel #59
0
        def wrapped_test(*arguments, **kwargs):
            # Tell pytest to omit the body of this function from tracebacks
            __tracebackhide__ = True

            test = wrapped_test.hypothesis.inner_test

            if getattr(test, 'is_hypothesis_test', False):
                note_deprecation((
                    'You have applied @given to test: %s more than once. In '
                    'future this will be an error. Applying @given twice '
                    'wraps the test twice, which can be extremely slow. A '
                    'similar effect can be gained by combining the arguments '
                    'of the two calls to given. For example, instead of '
                    '@given(booleans()) @given(integers()), you could write '
                    '@given(booleans(), integers())') % (test.__name__, )
                )

            settings = wrapped_test._hypothesis_internal_use_settings

            random = get_random_for_wrapped_test(test, wrapped_test)

            if infer in generator_kwargs.values():
                hints = get_type_hints(test)
            for name in [name for name, value in generator_kwargs.items()
                         if value is infer]:
                if name not in hints:
                    raise InvalidArgument(
                        'passed %s=infer for %s, but %s has no type annotation'
                        % (name, test.__name__, name))
                generator_kwargs[name] = st.from_type(hints[name])

            processed_args = process_arguments_to_given(
                wrapped_test, arguments, kwargs, generator_arguments,
                generator_kwargs, argspec, test, settings
            )
            arguments, kwargs, test_runner, search_strategy = processed_args

            runner = getattr(search_strategy, 'runner', None)
            if isinstance(runner, TestCase) and test.__name__ in dir(TestCase):
                msg = ('You have applied @given to the method %s, which is '
                       'used by the unittest runner but is not itself a test.'
                       '  This is not useful in any way.' % test.__name__)
                fail_health_check(settings, msg, HealthCheck.not_a_test_method)
            if bad_django_TestCase(runner):  # pragma: no cover
                # Covered by the Django tests, but not the pytest coverage task
                raise InvalidArgument(
                    'You have applied @given to a method on %s, but this '
                    'class does not inherit from the supported versions in '
                    '`hypothesis.extra.django`.  Use the Hypothesis variants '
                    'to ensure that each example is run in a separate '
                    'database transaction.' % qualname(type(runner))
                )

            state = StateForActualGivenExecution(
                test_runner, search_strategy, test, settings, random,
                had_seed=wrapped_test._hypothesis_internal_use_seed
            )

            reproduce_failure = \
                wrapped_test._hypothesis_internal_use_reproduce_failure

            if reproduce_failure is not None:
                expected_version, failure = reproduce_failure
                if expected_version != __version__:
                    raise InvalidArgument((
                        'Attempting to reproduce a failure from a different '
                        'version of Hypothesis. This failure is from %s, but '
                        'you are currently running %r. Please change your '
                        'Hypothesis version to a matching one.'
                    ) % (expected_version, __version__))
                try:
                    state.execute(ConjectureData.for_buffer(
                        decode_failure(failure)),
                        print_example=True, is_final=True,
                    )
                    raise DidNotReproduce(
                        'Expected the test to raise an error, but it '
                        'completed successfully.'
                    )
                except StopTest:
                    raise DidNotReproduce(
                        'The shape of the test data has changed in some way '
                        'from where this blob was defined. Are you sure '
                        "you're running the same test?"
                    )
                except UnsatisfiedAssumption:
                    raise DidNotReproduce(
                        'The test data failed to satisfy an assumption in the '
                        'test. Have you added it since this blob was '
                        'generated?'
                    )

            execute_explicit_examples(
                test_runner, test, wrapped_test, settings, arguments, kwargs
            )

            if settings.max_examples <= 0:
                return

            if not (
                Phase.reuse in settings.phases or
                Phase.generate in settings.phases
            ):
                return

            try:
                if isinstance(runner, TestCase) and hasattr(runner, 'subTest'):
                    subTest = runner.subTest
                    try:
                        setattr(runner, 'subTest', fake_subTest)
                        state.run()
                    finally:
                        setattr(runner, 'subTest', subTest)
                else:
                    state.run()
            except BaseException:
                generated_seed = \
                    wrapped_test._hypothesis_internal_use_generated_seed
                if generated_seed is not None and not state.failed_normally:
                    with local_settings(settings):
                        if running_under_pytest:
                            report(
                                'You can add @seed(%(seed)d) to this test or '
                                'run pytest with --hypothesis-seed=%(seed)d '
                                'to reproduce this failure.' % {
                                    'seed': generated_seed})
                        else:
                            report(
                                'You can add @seed(%d) to this test to '
                                'reproduce this failure.' % (generated_seed,))
                raise
Beispiel #60
0
def resolve_Generator(thing):
    yields, _, returns = thing.__args__
    return GeneratorStrategy(st.from_type(yields), st.from_type(returns))