示例#1
0
def test_several_generic_bases_functions(type_, func):
    with temp_registered(_FirstBase, st.builds(type_)), temp_registered(
            _SecondBase, st.builds(type_)):
        find_any(st.builds(func))

    with temp_registered(type_, st.builds(type_)):
        find_any(st.builds(func))
示例#2
0
def test_issue_2951_regression_two_params():
    map_strat = st.builds(SpecificDict,
                          st.dictionaries(st.integers(), st.integers()))
    expected = repr(st.from_type(Dict[int, int]))
    with temp_registered(SpecificDict, map_strat):
        assert st.from_type(SpecificDict) == map_strat
        assert expected == repr(st.from_type(Dict[int, int]))
示例#3
0
def test_generic_origin_from_type():
    with temp_registered(MyGeneric, st.builds(MyGeneric)):
        find_any(st.from_type(MyGeneric[T]))
        find_any(st.from_type(MyGeneric[int]))
        find_any(st.from_type(MyGeneric))
        find_any(st.builds(using_generic))
        find_any(st.builds(using_concrete_generic))
示例#4
0
def test_typevars_can_be_redefine_with_factory():
    """We test that one can register a custom strategy for all type vars."""
    A = typing.TypeVar("A")

    with temp_registered(typing.TypeVar,
                         lambda thing: st.just(thing.__name__)):
        assert_all_examples(st.from_type(A), lambda obj: obj == "A")
示例#5
0
def test_errors_if_generic_resolves_empty():
    with temp_registered(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()
示例#6
0
def test_issue_2951_regression():
    lines_strat = st.builds(Lines, lines=st.lists(st.text()))
    with temp_registered(Lines, lines_strat):
        assert st.from_type(Lines) == lines_strat
        # Now let's test that the strategy for ``Sequence[int]`` did not
        # change just because we registered a strategy for ``Lines``:
        expected = "one_of(binary(), lists(integers()))"
        assert repr(st.from_type(Sequence[int])) == expected
示例#7
0
def test_register_generic_typing_strats():
    # I don't expect anyone to do this, but good to check it works as expected
    with temp_registered(typing.Sequence,
                         types._global_type_lookup[typing.Set]):
        # We register sets for the abstract sequence type, which masks subtypes
        # from supertype resolution but not direct resolution
        assert_all_examples(from_type(typing.Sequence[int]),
                            lambda ex: isinstance(ex, set))
        assert_all_examples(
            from_type(typing.Container[int]),
            lambda ex: not isinstance(ex, typing.Sequence),
        )
        assert_all_examples(from_type(typing.List[int]),
                            lambda ex: isinstance(ex, list))
示例#8
0
def test_my_mappable(source: st.DataObject) -> None:
    """
    Checks that complex types with multiple inheritance levels and strings are fine.

    Regression test for https://github.com/HypothesisWorks/hypothesis/issues/3060
    """
    # In `returns` we register all types in `__mro__`
    # to be this exact type at the moment. But here, we only need `Mappable`.
    # Current `__mro__` is `MyFunctor / Kind / Mappable`:
    assert MyFunctor.__mro__[2] is MappableN
    with temp_registered(
            MyFunctor.__mro__[2],
            st.builds(MyFunctor),
    ):
        assert source.draw(st.builds(target_func)) is True
示例#9
0
def test_lookup_overrides_defaults():
    sentinel = object()
    with temp_registered(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()

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

    inner_2()
示例#10
0
def test_mutually_recursive_types_with_typevar(data):
    # The previously-failing example from the issue
    A = Dict[bool, "B"]  # noqa: F821 - an undefined name is the whole point!
    B = Union[List[bool], A]

    with pytest.raises(ResolutionFailed, match=r"Could not resolve ForwardRef\('B'\)"):
        data.draw(st.from_type(A))

    with utils.temp_registered(
        ForwardRef("B"),
        lambda _: st.deferred(lambda: b_strategy),
    ):
        b_strategy = st.from_type(B)
        data.draw(b_strategy)
        data.draw(st.from_type(A))
        data.draw(st.from_type(B))
示例#11
0
def test_mutually_recursive_types_with_typevar_alternate(data):
    # It's not particularly clear why this version passed when the previous
    # test failed, but different behaviour means we add both to the suite.
    C = Union[List[bool], "D"]  # noqa: F821 - an undefined name is the whole point!
    D = Dict[bool, C]

    with pytest.raises(ResolutionFailed, match=r"Could not resolve ForwardRef\('D'\)"):
        data.draw(st.from_type(C))

    with utils.temp_registered(
        ForwardRef("D"),
        lambda _: st.deferred(lambda: d_strategy),
    ):
        d_strategy = st.from_type(D)
        data.draw(d_strategy)
        data.draw(st.from_type(C))
        data.draw(st.from_type(D))
示例#12
0
def test_abstract_resolver_fallback():
    # We create our distinct strategies for abstract and concrete types
    gen_abstractbar = _from_type(AbstractBar)
    gen_concretebar = st.builds(ConcreteBar, x=st.none())
    assert gen_abstractbar != gen_concretebar

    # And trying to generate an instance of the abstract type fails,
    # UNLESS the concrete type is currently resolvable
    with pytest.raises(ResolutionFailed):
        gen_abstractbar.example()
    with temp_registered(ConcreteBar, gen_concretebar):
        gen = gen_abstractbar.example()
    with pytest.raises(ResolutionFailed):
        gen_abstractbar.example()

    # which in turn means we resolve to the concrete subtype.
    assert isinstance(gen, ConcreteBar)
示例#13
0
def test_lookup_overrides_defaults(typ):
    sentinel = object()
    with temp_registered(typ, st.just(sentinel)):
        assert st.from_type(typ).example() is sentinel
    assert st.from_type(typ).example() is not sentinel
示例#14
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)
示例#15
0
def test_generic_origin_from_type(strat, type_):
    with temp_registered(MyGeneric, st.builds(MyGeneric)):
        find_any(strat(type_))
示例#16
0
def test_custom_type_resolution():
    sentinel = object()
    with temp_registered(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
示例#17
0
def test_bound_type_cheking_only_forward_ref_wrong_type():
    """We should check ``ForwardRef`` parameter name correctly."""
    with utils.temp_registered(ForwardRef("WrongType"), st.just(1)):
        with pytest.raises(ResolutionFailed):
            st.builds(typechecking_only_fun).example()
示例#18
0
def test_bound_type_cheking_only_forward_ref():
    """We should fallback to registering explicit ``ForwardRef`` when we have to."""
    with utils.temp_registered(ForwardRef("ExcInfo"), st.just(1)):
        st.builds(typechecking_only_fun).example()
示例#19
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)
示例#20
0
def test_can_register_new_type_for_typeddicts():
    sentinel = object()
    with temp_registered(C, st.just(sentinel)):
        assert st.from_type(C).example() is sentinel
示例#21
0
def test_custom_type_resolution_with_function():
    sentinel = object()
    with temp_registered(UnknownType, lambda _: st.just(sentinel)):
        assert st.from_type(UnknownType).example() is sentinel
        assert st.from_type(ParentUnknownType).example() is sentinel
示例#22
0
def test_several_generic_bases_wrong_functions(func):
    with temp_registered(AllConcrete, st.builds(AllConcrete)):
        with pytest.raises(ResolutionFailed):
            st.builds(func).example()
示例#23
0
def test_custom_type_resolution_with_function_non_strategy():
    with temp_registered(UnknownType, lambda _: None):
        with pytest.raises(ResolutionFailed):
            st.from_type(UnknownType).example()
        with pytest.raises(ResolutionFailed):
            st.from_type(ParentUnknownType).example()
示例#24
0
def test_several_generic_bases(type_):
    with temp_registered(_FirstBase, st.builds(type_)):
        find_any(st.builds(_FirstBase))

    with temp_registered(_SecondBase, st.builds(type_)):
        find_any(st.builds(_SecondBase))
示例#25
0
def test_generic_origin_concrete_builds():
    with temp_registered(MyGeneric, st.builds(MyGeneric, st.integers())):
        assert_all_examples(st.builds(using_generic),
                            lambda example: isinstance(example, int))
示例#26
0
def test_generic_origin_without_type_args(generic):
    with temp_registered(generic, st.just("example")):
        pass