Skip to content

Commit 7b92def

Browse files
authored
Merge pull request #3052 from Zac-HD/recur-dataclass
Improve error message for recursive forward references with PEP585 builtin generics
2 parents 9d4da6c + f934f63 commit 7b92def

3 files changed

Lines changed: 29 additions & 1 deletion

File tree

‎hypothesis-python/RELEASE.rst‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
RELEASE_TYPE: patch
2+
3+
This patch improves the error message for :issue:`3016`, where :pep:`585`
4+
builtin generics with self-referential forward-reference strings cannot be
5+
resolved to a strategy by :func:`~hypothesis.strategies.from_type`.

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1007,7 +1007,15 @@ def as_strategy(strat_or_callable, thing, final=True):
10071007
else:
10081008
literals.append(arg)
10091009
return sampled_from(literals)
1010-
raise InvalidArgument(f"thing={thing} must be a type")
1010+
if isinstance(thing, str):
1011+
# See https://github.com/HypothesisWorks/hypothesis/issues/3016
1012+
raise InvalidArgument(
1013+
f"Got {thing!r} as a type annotation, but the forward-reference "
1014+
"could not be resolved from a string to a type. Consider using "
1015+
"`from __future__ import annotations` instead of forward-reference "
1016+
"strings."
1017+
)
1018+
raise InvalidArgument(f"thing={thing!r} must be a type") # pragma: no cover
10111019
# Now that we know `thing` is a type, the first step is to check for an
10121020
# explicitly registered strategy. This is the best (and hopefully most
10131021
# common) way to resolve a type to a strategy. Note that the value in the

‎hypothesis-python/tests/cover/test_lookup_py39.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,13 @@
1313
#
1414
# END HEADER
1515

16+
import dataclasses
1617
import typing
1718

1819
import pytest
1920

2021
from hypothesis import strategies as st
22+
from hypothesis.errors import InvalidArgument
2123

2224

2325
@pytest.mark.parametrize(
@@ -36,3 +38,16 @@
3638
)
3739
def test_typing_Annotated(annotated_type, expected_strategy_repr):
3840
assert repr(st.from_type(annotated_type)) == expected_strategy_repr
41+
42+
43+
@dataclasses.dataclass
44+
class User:
45+
id: int
46+
following: list["User"] # works with typing.List
47+
48+
49+
def test_string_forward_ref_message():
50+
# See https://github.com/HypothesisWorks/hypothesis/issues/3016
51+
s = st.builds(User)
52+
with pytest.raises(InvalidArgument, match="`from __future__ import annotations`"):
53+
s.example()

0 commit comments

Comments
 (0)