How to use the hypothesis.strategies.builds 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 FuelRats / pipsqueak3 / tests / strategies.py View on Github external
"""

valid_words = strategies.lists(valid_word, max_size=10)
""" 
a list of valid words

Shrinks towards smaller lists and smaller words.
"""
_irc_nick_letters = strategies.characters(
    whitelist_characters=f"{string.ascii_letters}{string.digits}" + r"\`_[]{}",
    whitelist_categories=())
valid_irc_name = strategies.text(alphabet=_irc_nick_letters, min_size=3).filter(
    lambda word: not word[0].isnumeric())
platform = strategies.sampled_from([_Platforms.PS, _Platforms.PC, _Platforms.XB])
""" Some platform """
rescue = strategies.builds(
    _Rescue,
    uuid=strategies.uuids(version=4),  # generate some valid uuid4
    client=valid_irc_name,  # client should always be defined
    # irc nickname may be any valid word, or None.
    irc_nickname=strategies.one_of(valid_irc_name, strategies.none()),
    platform=platform,
    active=strategies.booleans(),
    code_red=strategies.booleans(),
    board_index=strategies.one_of(strategies.integers(min_value=1), strategies.none())
)
""" Strategy for generating a rescue. Shrinks towards smaller arguments """


def rescues(min_size: int, max_size: int):
    """ builds a list of rescues, shrinks towards smaller lists and smaller rescues """
    return strategies.lists(rescue, min_size=min_size, max_size=max_size,
github garyd203 / flying-circus / tests / core_test / common.py View on Github external
def aws_logical_name_strategy(draw):
    """A strategy that produces a valid logical name for an AWS Stack object"""
    return draw(
        st.builds(
            lambda a, b: a + b,
            st.text("ABCDEFGHIJKLMNOPQRSTUVWXYZ", min_size=1, max_size=1),
            st.text("abcdefghijklmnnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"),
        )
github HypothesisWorks / hypothesis / tests / nocover / test_pretty_repr.py View on Github external
min_size=st.integers(min_value=0, max_value=100) | st.none(),
    max_size=st.integers(min_value=0, max_value=100) | st.none(),
)


values = st.integers() | st.text()


Strategies = st.recursive(
    st.one_of(
        st.sampled_from([
            st.none(), st.booleans(), st.randoms(), st.complex_numbers(),
            st.randoms(), st.fractions(), st.decimals(),
        ]),
        st.builds(st.just, values),
        st.builds(st.sampled_from, st.lists(values, min_size=1)),
        builds_ignoring_invalid(st.floats, st.floats(), st.floats()),
    ),
    lambda x: st.one_of(
        builds_ignoring_invalid(st.lists, x, **size_strategies),
        builds_ignoring_invalid(st.sets, x, **size_strategies),
        builds_ignoring_invalid(
            lambda v: st.tuples(*v), st.lists(x)),
        builds_ignoring_invalid(
            lambda v: st.one_of(*v),
            st.lists(x, min_size=1)),
        builds_ignoring_invalid(
            st.dictionaries, x, x,
            dict_class=st.sampled_from([dict, OrderedDict]),
            **size_strategies
        ),
        st.builds(lambda s, f: s.map(f), x, st.sampled_from(fns)),
github LeastAuthority / txkube / src / txkube / testing / strategies.py View on Github external
def joins(sep, elements):
    """
    Join unicode strings built by another strategy.

    :param unicode sep: The separate to join with.

    :param elements: A strategy which builds a sequence of unicode strings to
        join.

    :return: A strategy for building the joined strings.
    """
    return builds(
        lambda values: sep.join(values),
        elements,
    )
github PromyLOPh / crocoite / crocoite / test_browser.py View on Github external
def urls ():
    """ Build http/https URL """
    scheme = st.sampled_from (['http', 'https'])
    # Path must start with a slash
    pathSt = st.builds (lambda x: '/' + x, st.text ())
    args = st.fixed_dictionaries ({
            'scheme': scheme,
            'host': domains (),
            'port': st.one_of (st.none (), st.integers (min_value=1, max_value=2**16-1)),
            'path': pathSt,
            'query_string': st.text (),
            'fragment': st.text (),
            })
    return st.builds (lambda x: URL.build (**x), args)
github jamesls / fakeredis / test_fakeredis_hypothesis.py View on Github external
@st.composite
def sample_attr(draw, name):
    """Strategy for sampling a specific attribute from a state machine"""
    machine = draw(self_strategy)
    values = getattr(machine, name)
    position = draw(st.integers(min_value=0, max_value=len(values) - 1))
    return values[position]


keys = sample_attr('keys')
fields = sample_attr('fields')
values = sample_attr('values')
scores = sample_attr('scores')

int_as_bytes = st.builds(lambda x: str(x).encode(), st.integers())
float_as_bytes = st.builds(lambda x: repr(x).encode(), st.floats(width=32))
counts = st.integers(min_value=-3, max_value=3) | st.integers()
limits = st.just(()) | st.tuples(st.just('limit'), counts, counts)
# Redis has an integer overflow bug in swapdb, so we confine the numbers to
# a limited range (https://github.com/antirez/redis/issues/5737).
dbnums = st.integers(min_value=0, max_value=3) | st.integers(min_value=-1000, max_value=1000)
# The filter is to work around https://github.com/antirez/redis/issues/5632
patterns = (st.text(alphabet=st.sampled_from('[]^$*.?-azAZ\\\r\n\t'))
            | st.binary().filter(lambda x: b'\0' not in x))
score_tests = scores | st.builds(lambda x: b'(' + repr(x).encode(), scores)
string_tests = (
    st.sampled_from([b'+', b'-'])
    | st.builds(operator.add, st.sampled_from([b'(', b'[']), fields))
# Redis has integer overflow bugs in time computations, which is why we set a maximum.
expires_seconds = st.integers(min_value=100000, max_value=10000000000)
expires_ms = st.integers(min_value=100000000, max_value=10000000000000)
github HypothesisWorks / hypothesis / tests / pandas / test_data_frame.py View on Github external
                     rows=st.builds(dict)))
def test_can_fill_in_missing_elements_from_dict(df):
    assert np.isnan(df['A']).all()
github warner / python-ecdsa / src / ecdsa / test_malformed_sigs.py View on Github external
lambda children: st.builds(
            lambda x: encode_octet_string(x), st.one_of(children)
        )
        | st.builds(lambda x: encode_bitstring(x, 0), st.one_of(children))
        | st.builds(
            lambda x: encode_sequence(*x), st.lists(children, max_size=200)
        )
        | st.builds(
            lambda tag, x: encode_constructed(tag, x),
            st.integers(min_value=0, max_value=0x3F),
            st.one_of(children),
        ),
github Yelp / fuzz-lightyear / fuzz_lightyear / fuzzer.py View on Github external
def type_cast() -> Any:
        """Use known types to cast output, if applicable."""
        output = get_user_defined_mapping()[name]()
        if output is None:
            # NOTE: We don't currently support `nullable` values, so we use `None`
            #       as a proxy to exclude the parameter from the final dictionary.
            return None
        if expected_type == 'string':
            return str(output)
        elif expected_type == 'integer':
            return int(output)

        return output

    return st.builds(type_cast)