Skip to content

Commit 13ccc11

Browse files
committed
be explicit in allowed types
1 parent 8aacab9 commit 13ccc11

2 files changed

Lines changed: 95 additions & 3 deletions

File tree

‎hypothesis/src/hypothesis/strategies/_internal/core.py‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,15 @@
1919
import typing
2020
import warnings
2121
from collections.abc import (
22+
AsyncGenerator,
23+
AsyncIterable,
24+
AsyncIterator,
2225
Callable,
2326
Collection,
27+
Generator,
2428
Hashable,
2529
Iterable,
30+
Iterator,
2631
Mapping,
2732
Sequence,
2833
)
@@ -2661,7 +2666,23 @@ def _functions(*, like, returns, pure):
26612666
if is_gen:
26622667
# The return annotation describes the iterator, so e.g. yield
26632668
# integers for `-> Iterator[int]` or `-> AsyncIterator[int]`.
2664-
args = get_args(hints.get("return"))
2669+
allowed = (
2670+
(AsyncIterator, AsyncIterable, AsyncGenerator)
2671+
if isasyncgenfunction(like)
2672+
else (Iterator, Iterable, Generator)
2673+
)
2674+
ret = hints.get("return")
2675+
# normalize eg Iterator[bool] to Iterator while keeping Iterator as Iterator.
2676+
kind = get_origin(ret) or ret
2677+
if ret is not None and kind not in allowed:
2678+
options = ", ".join(t.__name__ for t in allowed)
2679+
raise InvalidArgument(
2680+
f"Cannot infer the yield type of like={nicerepr(like)!r} "
2681+
f"from its return annotation {ret!r}. Expected one of "
2682+
f"{options}. Alternatively, pass returns= to specify the yield type "
2683+
"explicitly."
2684+
)
2685+
args = get_args(ret)
26652686
returns = from_type(args[0]) if args else none()
26662687
else:
26672688
# Passing `None` has never been *documented* as working, but it

‎hypothesis/tests/cover/test_functions.py‎

Lines changed: 73 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,11 @@
88
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
99
# obtain one at https://mozilla.org/MPL/2.0/.
1010

11-
from collections.abc import AsyncIterator, Generator, Iterator
11+
from collections.abc import (
12+
AsyncIterator,
13+
Generator,
14+
Iterator,
15+
)
1216
from inspect import (
1317
isasyncgenfunction,
1418
iscoroutinefunction,
@@ -24,7 +28,7 @@
2428
from hypothesis.reporting import with_reporter
2529
from hypothesis.strategies import booleans, functions, integers
2630

27-
from tests.common.debug import check_can_generate_examples
31+
from tests.common.debug import assert_all_examples, check_can_generate_examples
2832
from tests.common.utils import capture_out
2933

3034

@@ -473,3 +477,70 @@ def t(f):
473477
def test_pure_is_invalid_except_for_plain_functions(like):
474478
with pytest.raises(InvalidArgument, match="pure=True is invalid"):
475479
check_can_generate_examples(functions(like=like, pure=True))
480+
481+
482+
def make_gen_like(annotation, *, is_async=False):
483+
prefix = "async " if is_async else ""
484+
# pass our globals so we can reference things like the module-level IteratorSubclass
485+
# in test strings
486+
namespace = dict(globals())
487+
exec(
488+
f"from collections.abc import *\n{prefix}def like(a) -> {annotation}:\n yield",
489+
namespace,
490+
)
491+
return namespace["like"]
492+
493+
494+
class IteratorSubclass(Iterator[bool]):
495+
def __next__(self):
496+
raise StopIteration
497+
498+
499+
@pytest.mark.parametrize(
500+
"annotation",
501+
["Iterator[bool]", "Iterable[bool]", "Generator[bool, None, None]"],
502+
)
503+
def test_generator_functions_accept_any_iterator_like_annotation(annotation):
504+
assert_all_examples(
505+
functions(like=make_gen_like(annotation)),
506+
lambda f: all(isinstance(value, bool) for value in f(1)),
507+
)
508+
509+
510+
@pytest.mark.parametrize(
511+
"annotation",
512+
["AsyncIterator[bool]", "AsyncIterable[bool]", "AsyncGenerator[bool, None]"],
513+
)
514+
def test_async_generator_functions_accept_any_async_iterator_like_annotation(
515+
annotation,
516+
):
517+
assert_all_examples(
518+
functions(like=make_gen_like(annotation, is_async=True)),
519+
lambda f: all(isinstance(value, bool) for value in collect_async_gen(f(1))),
520+
)
521+
522+
523+
@pytest.mark.parametrize(
524+
"annotation",
525+
[
526+
"bool",
527+
"tuple[bool, str]",
528+
"list[bool]",
529+
"IteratorSubclass",
530+
"AsyncIterator[bool]",
531+
],
532+
)
533+
def test_generator_functions_reject_other_annotations(annotation):
534+
with pytest.raises(InvalidArgument, match="Cannot infer the yield type"):
535+
check_can_generate_examples(functions(like=make_gen_like(annotation)))
536+
537+
538+
@pytest.mark.parametrize(
539+
"annotation",
540+
["bool", "tuple[bool, str]", "list[bool]", "Iterator[bool]"],
541+
)
542+
def test_async_generator_functions_reject_other_annotations(annotation):
543+
with pytest.raises(InvalidArgument, match="Cannot infer the yield type"):
544+
check_can_generate_examples(
545+
functions(like=make_gen_like(annotation, is_async=True))
546+
)

0 commit comments

Comments
 (0)