How to use the hypothesis.strategies.text function in hypothesis

To help you get started, we’ve selected a few hypothesis examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github rocky / python-decompile3 / pytest / test_fstring.py View on Github external
:return: A valid f-string.
    """
    character_strategy = st.characters(
        blacklist_characters="\r\n'\\s{}", min_codepoint=1, max_codepoint=1000
    )
    is_raw = draw(st.booleans())
    integer_strategy = st.integers(min_value=0, max_value=3)
    expression_count = draw(integer_strategy)
    content = []
    for _ in range(expression_count):
        expression = draw(expressions())
        conversion = draw(st.sampled_from(("", "!s", "!r", "!a")))
        has_specifier = draw(st.booleans())
        specifier = ":" + draw(format_specifiers()) if has_specifier else ""
        content.append("{{{}{}}}".format(expression, conversion, specifier))
        content.append(draw(st.text(character_strategy)))
    content = "".join(content)
    return "f{}'{}'".format("r" if is_raw else "", content)
github Tinche / cattrs / tests / metadata / __init__.py View on Github external
def str_typed_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields strs for that
    attribute.
    """
    default = NOTHING
    if defaults is True or (defaults is None and draw(booleans())):
        default = draw(text())
    return (attr.ib(type=unicode, default=default), text())
github OasisLMF / OasisPlatform / tests / test_exposure.py View on Github external
    @given(lists(text(alphabet=string.ascii_letters, min_size=1), unique=True, min_size=2, max_size=2))
    def test_location_is_given_on_delete___only_named_location_is_deleted(self, locations):
        first_location, second_location = locations

        with TemporaryDirectory() as inputs_dir:
            with SettingsPatcher(INPUTS_DATA_DIRECTORY=inputs_dir):
                Path(os.path.join(inputs_dir, '{}.tar'.format(first_location))).touch()
                Path(os.path.join(inputs_dir, '{}.tar'.format(second_location))).touch()

                response = self.app.delete("/exposure/{}".format(first_location))
                self.assertEqual(response._status_code, 200)

                response = self.app.get("/exposure_summary")
                exposures = json.loads(response.data.decode('utf-8'))['exposures']

                self.assertEqual(len(exposures), 1)
                self.assertEqual(second_location, exposures[0]['location'])
github davidmascharka / detection-utils / tests / test_pytorch.py View on Github external
        reduction=st.text(alphabet=string.ascii_letters).filter(
            lambda x: x not in ("sum", "mean", "none")
        )
    )
    def test_valid_args(self, reduction: str):
        """ Ensures that invalid arguments raise a value error. """
        inputs = tensor(np.random.rand(5, 5))
        targets = tensor(np.random.randint(0, 1, 5))
        with pytest.raises(ValueError):
            softmax_focal_loss(inputs, targets, reduction=reduction)
github daffidwilde / matching / tests / unit / params.py View on Github external
""" Hypothesis decorators for unit tests. """

from hypothesis import given
from hypothesis.strategies import integers, lists, text

PLAYER = given(
    name=text(),
    pref_names=lists(text(), min_size=1, unique=True),
    capacity=integers(min_value=1),
)
github HypothesisWorks / hypothesis / tests / nocover / test_descriptortests.py View on Github external
integers().flatmap(lambda i: lists(just(i)))
    )

    TestOrderedPairs = strategy_test_suite(
        strategy(integers(min_value=1, max_value=200)).flatmap(
            lambda e: tuples(integers(min_value=0, max_value=e - 1), just(e))
        )
    )

    TestMappedSampling = strategy_test_suite(
        lists(integers(), min_size=1).flatmap(sampled_from)
    )

    TestDiverseFlatmap = strategy_test_suite(
        sampled_from((
            lists(integers()), lists(text()), tuples(text(), text()),
            booleans(), sets(complex_numbers())
        )).flatmap(lambda x: x)
    )

    def integers_from(x):
        return integers(min_value=x)

    TestManyFlatmaps = strategy_test_suite(
        integers()
        .flatmap(integers_from)
        .flatmap(integers_from)
        .flatmap(integers_from)
        .flatmap(integers_from)
    )

    TestIntStreams = strategy_test_suite(streaming(integers()))
github ethereum / web3.py / tests / core / caching-utils / test_generate_cache_key.py View on Github external
@to_dict
def shuffle_dict(_dict):
    keys = list(_dict.keys())
    random.shuffle(keys)
    for key in keys:
        yield key, _dict[key]


def extend_fn(children):
    lists_st = st.lists(children)
    dicts_st = st.dictionaries(st.text(), children)
    return lists_st | dicts_st


all_st = st.recursive(
    st.none() | st.integers() | st.booleans() | st.floats() | st.text() | st.binary(),
    extend_fn,
)


def recursive_shuffle_dict(v):
    if isinstance(v, dict):
        return shuffle_dict(v)
    elif isinstance(v, (list, tuple)):
        return type(v)((recursive_shuffle_dict(_v) for _v in v))
    else:
        return v


@given(value=all_st)
def test_key_generation_is_deterministic(value):
    left = recursive_shuffle_dict(value)
github HypothesisWorks / hypothesis / tests / cover / test_regressions.py View on Github external
def strat_two(draw):
    return draw(st.builds(dict, some_text=st.text(min_size=1)))
github python-hyper / hyperlink / src / hyperlink / hypothesis.py View on Github external
        @param min_size: The minimum number of characters in the text.
            C{None} is treated as C{0}.

        @param max_size: The maximum number of characters in the text.
            Use C{None} for an unbounded size.
        """
        alphabet = idna_characters()

        assert min_size >= 1

        if max_size is not None:
            assert max_size >= 1

        result = cast(
            Text,
            draw(text(
                min_size=min_size, max_size=max_size, alphabet=alphabet
            ))
        )

        # FIXME: There should be a more efficient way to ensure we produce
        # valid IDNA text.
        try:
            idna_encode(result)
        except IDNAError:
            assume(False)

        return result