Skip to content

Commit

Permalink
recommend st.text(st.characters(codec)) for st.text(codec)
Browse files Browse the repository at this point in the history
  • Loading branch information
tybug committed Dec 7, 2024
1 parent f45fab4 commit 90dad4b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
13 changes: 13 additions & 0 deletions hypothesis-python/src/hypothesis/strategies/_internal/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -793,6 +793,19 @@ def text(
"The following elements in alphabet are not of length one, "
f"which leads to violation of size constraints: {not_one_char!r}"
)
if alphabet in {"ascii", "utf-8"}:
warnings.warn(
f"st.text({alphabet!r}): it seems like you are trying to use the "
f"codec {alphabet!r}. st.text({alphabet!r}) instead generates "
f"strings using the literal characters {list(alphabet)!r}. To specify "
f"the {alphabet} codec, use st.text(st.characters({alphabet!r})). "
"If you intended to use character literals, you can silence this "
"warning by reordering the characters.",
HypothesisWarning,
# this stacklevel is of course incorrect, but breaking out of the
# levels of LazyStrategy and validation isn't worthwhile.
stacklevel=1,
)
char_strategy = (
characters(categories=(), include_characters=alphabet)
if alphabet
Expand Down
29 changes: 27 additions & 2 deletions hypothesis-python/tests/cover/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@
# obtain one at https://mozilla.org/MPL/2.0/.

import functools
import warnings

import pytest

from hypothesis import find, given
from hypothesis.errors import InvalidArgument
from hypothesis import find, given, strategies as st
from hypothesis.errors import HypothesisWarning, InvalidArgument
from hypothesis.internal.validation import check_type
from hypothesis.strategies import (
SearchStrategy as ActualSearchStrategy,
Expand Down Expand Up @@ -275,3 +276,27 @@ def test_check_strategy_might_suggest_sampled_from():
with pytest.raises(InvalidArgument, match="such as st.sampled_from"):
check_strategy_((1, 2, 3))
check_strategy_(integers(), "passes for our custom coverage check")


@pytest.mark.parametrize("codec", ["ascii", "utf-8"])
def test_warn_on_strings_matching_common_codecs(codec):
with pytest.warns(
HypothesisWarning,
match=f"it seems like you are trying to use the codec {codec!r}",
):

@given(st.text(codec))
def f(s):
pass

f()

# if we reorder, it doesn't warn anymore
with warnings.catch_warnings():
warnings.simplefilter("error")

@given(st.text(codec[1:] + codec[:1]))
def f(s):
pass

f()

0 comments on commit 90dad4b

Please sign in to comment.