Skip to content

Commit 4c94bf4

Browse files
committed
Warn on bool(strategy)
1 parent d85a647 commit 4c94bf4

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

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: minor
2+
3+
This release defines ``__bool__()`` on :class:`~hypothesis.strategies.SearchStrategy`.
4+
It always returns ``True``, like before, but also emits a warning to help with
5+
cases where you intended to draw a value (:issue:`3463`).

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
from hypothesis.control import _current_build_context, assume
3030
from hypothesis.errors import (
3131
HypothesisException,
32+
HypothesisWarning,
3233
InvalidArgument,
3334
NonInteractiveExampleWarning,
3435
UnsatisfiedAssumption,
@@ -396,6 +397,14 @@ def __or__(self, other: "SearchStrategy[T]") -> "SearchStrategy[Union[Ex, T]]":
396397
raise ValueError(f"Cannot | a SearchStrategy with {other!r}")
397398
return OneOfStrategy((self, other))
398399

400+
def __bool__(self) -> bool:
401+
warnings.warn(
402+
f"bool({self!r}) is always True, did you mean to draw a value?",
403+
HypothesisWarning,
404+
stacklevel=2,
405+
)
406+
return True
407+
399408
def validate(self) -> None:
400409
"""Throw an exception if the strategy is not valid.
401410

hypothesis-python/tests/cover/test_error_in_draw.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import pytest
1212

1313
from hypothesis import given, strategies as st
14+
from hypothesis.errors import HypothesisWarning
1415

1516

1617
def test_error_is_in_finally():
@@ -25,3 +26,13 @@ def test(d):
2526
test()
2627

2728
assert "[0, 1, -1]" in "\n".join(err.value.__notes__)
29+
30+
31+
@given(st.data())
32+
def test_warns_on_bool_strategy(data):
33+
with pytest.warns(
34+
HypothesisWarning,
35+
match=r"bool\(.+\) is always True, did you mean to draw a value\?",
36+
):
37+
if st.booleans(): # 'forgot' to draw from the strategy
38+
pass

0 commit comments

Comments
 (0)