Python hypothesis.strategies.booleans() Examples

The following are 30 code examples of hypothesis.strategies.booleans(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module hypothesis.strategies , or try the search function .
Example #1
Source File: test_task.py    From transformer with MIT License 6 votes vote down vote up
def har_post_dicts(draw, format=None):
    format = format or draw(_formats)
    if format == "json":
        d = {"mimeType": "application/json", "text": """{"a":"b", "c": "d"}"""}
        if draw(booleans()):
            d["params"] = []
        if draw(booleans()):
            d["comment"] = ""
        return d

    d = {"mimeType": "application/x-www-form-urlencoded"}
    kind = draw(_kinds_of_dicts)
    if kind & _KindOfDict.Text:
        d["text"] = "a=b&c=d"
        if draw(booleans()):
            d.setdefault("params", [])
    if kind & _KindOfDict.Params:
        d["params"] = [{"name": "a", "value": "b"}, {"name": "c", "value": "d"}]
        if draw(booleans()):
            d.setdefault("text", "")
    return d 
Example #2
Source File: test_output_mask.py    From telepresence with Apache License 2.0 6 votes vote down vote up
def generate_dictionary_with_fixed_tokens(draw):
    """
    Builds random nested dictionary structure which is then used as JSON to
    mask two fixed "token" keys.

    Structure is based on TEST_JSON sample fixture defined above.
    """
    base = draw(
        st.fixed_dictionaries({'token': st.text(printable, min_size=10)})
    )

    optional = draw(
        st.nothing() | st.dictionaries(
            st.text(ascii_letters, min_size=1),
            st.floats() | st.integers() | st.text(printable) | st.booleans()
            | st.nothing(),
            min_size=10,
            max_size=50
        )
    )

    return {**base, **optional} 
Example #3
Source File: test_parse.py    From eliot with Apache License 2.0 6 votes vote down vote up
def action_structures(draw):
    """
    A Hypothesis strategy that creates a tree of L{ActionStructure} and
    L{unicode}.
    """
    tree = draw(st.recursive(labels, st.lists, max_leaves=20))

    def to_structure(tree_or_message):
        if isinstance(tree_or_message, list):
            return ActionStructure(
                type=draw(labels),
                failed=draw(st.booleans()),
                children=[to_structure(o) for o in tree_or_message],
            )
        else:
            return tree_or_message

    return to_structure(tree) 
Example #4
Source File: test_prettyprinter.py    From prettyprinter with MIT License 6 votes vote down vote up
def possibly_commented(strategy):
    @st.composite
    def _strategy(draw):
        value = draw(strategy)

        add_trailing_comment = False
        if isinstance(value, (list, tuple, set)):
            add_trailing_comment = draw(st.booleans())

        add_comment = draw(st.booleans())

        if add_trailing_comment:
            comment_text = draw(st.text(alphabet='abcdefghijklmnopqrstuvwxyz #\\\'"'))
            value = trailing_comment(value, comment_text)

        if add_comment:
            comment_text = draw(st.text(alphabet='abcdefghijklmnopqrstuvwxyz #\\\'"'))
            value = comment(value, comment_text)

        return value

    return _strategy() 
Example #5
Source File: hypothesis_helper.py    From pyranges with MIT License 6 votes vote down vote up
def dfs_no_min(draw):  # nosec
    df = draw(better_dfs_no_min)
    # strand = draw(use_strand)
    df.loc[:, "End"] += df.Start

    df.insert(3, "Name", "a")
    df.insert(4, "Score", 0)

    # stranded = draw(st.booleans())
    # if not strand:
    #     df = df.drop("Strand", axis=1)

    gr = PyRanges(df, int64=True)
    # gr = PyRanges(df)

    # do not sort like this, use pyranges sort
    # np.random.seed(draw(st.integers(min_value=0, max_value=int(1e6))))
    # gr.df = df.reindex(np.random.permutation(df.index.values))

    return gr 
Example #6
Source File: test_browser.py    From crocoite with MIT License 6 votes vote down vote up
def requestResponsePair ():
    def f (creq, cresp, hasPostData, reqBody, respBody):
        i = RequestResponsePair ()
        i.fromRequestWillBeSent (creq)
        i.request.hasPostData = hasPostData
        if hasPostData:
            i.request.body = reqBody

        if cresp is not None:
            i.fromResponseReceived (cresp)
            if respBody is not None:
                i.response.body = respBody
        return i

    bodySt = st.one_of (
            st.none (),
            st.builds (UnicodeBody, st.text ()),
            st.builds (Base64Body.fromBytes, st.binary ())
            )
    return st.builds (lambda reqresp, hasPostData, reqBody, respBody:
            f (reqresp[0], reqresp[1], hasPostData, reqBody, respBody),
            chromeReqResp (), st.booleans (), bodySt, bodySt) 
Example #7
Source File: hypothesis_helper.py    From pyranges with MIT License 6 votes vote down vote up
def dfs_min(draw):  # nosec
    df = draw(better_dfs_min)
    # strand = draw(use_strand)
    df.loc[:, "End"] += df.Start

    df.insert(3, "Name", "a")
    df.insert(4, "Score", 0)

    # df.Start = df.Start.astype(np.int32)
    # df.End = df.End.astype(np.int32)
    # print(df.dtypes)
    # stranded = draw(st.booleans())
    # if not strand:
    #     df = df.drop("Strand", axis=1)

    gr = PyRanges(df, int64=True)
    # print(gr)
    # raise
    # gr = PyRanges(df)

    # do not sort like this, use pyranges sort
    # np.random.seed(draw(st.integers(min_value=0, max_value=int(1e6))))
    # gr.df = df.reindex(np.random.permutation(df.index.values))

    return gr 
Example #8
Source File: strategies.py    From pymtl3 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def bits( nbits, signed=False, min_value=None, max_value=None ):
  BitsN = mk_bits( nbits )

  if (min_value is not None or max_value is not None) and signed:
    raise ValueError("bits strategy currently doesn't support setting "
                     "signedness and min/max value at the same time")

  if min_value is None:
    min_value = (-(2**(nbits-1))) if signed else 0
  if max_value is None:
    max_value = (2**(nbits-1)-1)  if signed else (2**nbits - 1)

  strat = st.booleans() if nbits == 1 else st.integers( min_value, max_value )

  @st.composite
  def strategy_bits( draw ):
    return BitsN( draw( strat ) )

  return strategy_bits() # RETURN A STRATEGY INSTEAD OF FUNCTION

#-------------------------------------------------------------------------
# strategies.bitslists
#-------------------------------------------------------------------------
# Return the SearchStrategy for a list of Bits with the support of
# dictionary based min/max value limit 
Example #9
Source File: strategies.py    From attrs with MIT License 6 votes vote down vote up
def simple_attrs_with_metadata(draw):
    """
    Create a simple attribute with arbitrary metadata.
    """
    c_attr = draw(simple_attrs)
    keys = st.booleans() | st.binary() | st.integers() | st.text()
    vals = st.booleans() | st.binary() | st.integers() | st.text()
    metadata = draw(
        st.dictionaries(keys=keys, values=vals, min_size=1, max_size=3)
    )

    return attr.ib(
        default=c_attr._default,
        validator=c_attr._validator,
        repr=c_attr.repr,
        eq=c_attr.eq,
        order=c_attr.order,
        hash=c_attr.hash,
        init=c_attr.init,
        metadata=metadata,
        type=None,
        converter=c_attr.converter,
    ) 
Example #10
Source File: tough-bonus-problems.py    From escape-from-automanual-testing with GNU Affero General Public License v3.0 6 votes vote down vote up
def from_schema(schema):
    """Returns a strategy for objects that match the given schema."""
    check_schema(schema)
    # TODO: actually handle constraints on number/string/array schemas
    return dict(
        null=st.none(),
        bool=st.booleans(),
        number=st.floats(allow_nan=False),
        string=st.text(),
        array=st.lists(st.nothing()),
    )[schema["type"]]


# `@st.composite` is one way to write this - another would be to define a
# bare function, and `return st.one_of(st.none(), st.booleans(), ...)` so
# each strategy can be defined individually.  Use whichever seems more
# natural to you - the important thing in tests is usually readability! 
Example #11
Source File: strategies.py    From brownie with MIT License 6 votes vote down vote up
def strategy(type_str: str, **kwargs: Any) -> SearchStrategy:
    type_str = TYPE_STR_TRANSLATIONS.get(type_str, type_str)
    if type_str == "fixed168x10":
        return _decimal_strategy(**kwargs)
    if type_str == "address":
        return _address_strategy(**kwargs)
    if type_str == "bool":
        return st.booleans(**kwargs)  # type: ignore
    if type_str == "string":
        return _string_strategy(**kwargs)

    abi_type = parse(type_str)
    if abi_type.is_array:
        return _array_strategy(abi_type, **kwargs)
    if isinstance(abi_type, TupleType):
        return _tuple_strategy(abi_type, **kwargs)  # type: ignore

    base = abi_type.base
    if base in ("int", "uint"):
        return _integer_strategy(type_str, **kwargs)
    if base == "bytes":
        return _bytes_strategy(abi_type, **kwargs)

    raise ValueError(f"No strategy available for type: {type_str}") 
Example #12
Source File: test_pencode.py    From chopsticks with Apache License 2.0 5 votes vote down vote up
def test_roundtrip_bool(b):
    """We can round-trip booleans and preserve their types."""
    res = assert_roundtrip(b)
    assert isinstance(res, bool) 
Example #13
Source File: hypothesis_helper.py    From pyranges with MIT License 5 votes vote down vote up
def dfs_min_with_id(draw):  # nosec
    df = draw(better_dfs_min)
    ids = df.Start
    # strand = draw(use_strand)
    df.loc[:, "End"] += df.Start

    df.insert(3, "Name", "a")
    df.insert(4, "Score", 0)
    df.insert(5, "ID", ids)

    # df.Start = df.Start.astype(np.int32)
    # df.End = df.End.astype(np.int32)
    # print(df.dtypes)
    # stranded = draw(st.booleans())
    # if not strand:
    #     df = df.drop("Strand", axis=1)

    gr = PyRanges(df)
    # print(gr)
    # raise
    # gr = PyRanges(df)

    # do not sort like this, use pyranges sort
    # np.random.seed(draw(st.integers(min_value=0, max_value=int(1e6))))
    # gr.df = df.reindex(np.random.permutation(df.index.values))

    return gr 
Example #14
Source File: hypothesis_helper.py    From pyranges with MIT License 5 votes vote down vote up
def dfs_min_with_gene_id(draw):  # nosec
    df = draw(better_dfs_min)
    ids = df.Start
    # strand = draw(use_strand)
    df.loc[:, "End"] += df.Start

    df.insert(3, "Name", "a")
    df.insert(4, "Score", 0)
    df.insert(5, "gene_id", ids)
    df.insert(6, "exon_id", list(range(len(df))))

    # df.Start = df.Start.astype(np.int32)
    # df.End = df.End.astype(np.int32)
    # print(df.dtypes)
    # stranded = draw(st.booleans())
    # if not strand:
    #     df = df.drop("Strand", axis=1)

    gr = PyRanges(df)
    # print(gr)
    # raise
    # gr = PyRanges(df)

    # do not sort like this, use pyranges sort
    # np.random.seed(draw(st.integers(min_value=0, max_value=int(1e6))))
    # gr.df = df.reindex(np.random.permutation(df.index.values))

    return gr 
Example #15
Source File: hypothesis_helper.py    From pyranges with MIT License 5 votes vote down vote up
def selector(draw):

    df = draw(better_dfs_min)
    h = df.head(1)
    chromosome = h["Chromosome"].iloc[0]
    start = h["Start"].iloc[0]
    end = h["End"].iloc[0]
    strand = h["Strand"].iloc[0]

    chromosome_bool = draw(st.booleans())
    strand_bool = draw(st.booleans())
    start_bool = draw(st.booleans())
    end_bool = draw(st.booleans())

    _slice = {
        (True, True): slice(start, end),
        (True, False): slice(start, None),
        (False, True): slice(None, end),
        (False, False): slice(None, None)
    }[start_bool, end_bool]

    to_return = []
    if chromosome_bool:
        to_return.append(chromosome)
    if strand_bool:
        to_return.append(strand)
    if start_bool or end_bool:
        to_return.append(_slice)

    return to_return 
Example #16
Source File: gen_schemas.py    From hypothesis-jsonschema with Mozilla Public License 2.0 5 votes vote down vote up
def gen_array(draw: Any) -> Schema:
    """Draw an array schema."""
    min_size = draw(st.none() | st.integers(0, 5))
    max_size = draw(st.none() | st.integers(2, 5))
    if min_size is not None and max_size is not None and min_size > max_size:
        min_size, max_size = max_size, min_size
    items = draw(
        st.builds(dict)
        | _json_schemata(recur=False)
        | st.lists(_json_schemata(recur=False), min_size=1, max_size=10)
    )
    out = {"type": "array", "items": items}
    if isinstance(items, list):
        increment = len(items)
        additional = draw(st.none() | _json_schemata(recur=False))
        if additional is not None:
            out["additionalItems"] = additional
        elif draw(st.booleans()):
            out["contains"] = draw(_json_schemata(recur=False).filter(bool))
            increment += 1
        if min_size is not None:
            min_size += increment
        if max_size is not None:
            max_size += increment
    else:
        if draw(st.booleans()):
            out["uniqueItems"] = True
        if items == {}:
            out["contains"] = draw(_json_schemata(recur=False))
    if min_size is not None:
        out["minItems"] = min_size
    if max_size is not None:
        out["maxItems"] = max_size
    return out 
Example #17
Source File: test_prettyprinter.py    From prettyprinter with MIT License 5 votes vote down vote up
def primitives():
    return (
        st.integers() |
        st.floats(allow_nan=False) |
        st.text() |
        st.binary() |
        st.datetimes(timezones=timezones() | st.none()) |
        st.dates() |
        st.times(timezones=timezones() | st.none()) |
        st.timedeltas() |
        st.booleans() |
        st.none()
    ) 
Example #18
Source File: basestrategies.py    From swagger-conformance with MIT License 5 votes vote down vote up
def json(value_limit=5):
    """Hypothesis strategy for generating values that can be passed to
    `json.dumps` to produce valid JSON data.

    :param value_limit: A limit on the number of values in the JSON data -
                        setting this too high can cause value generation to
                        time out.
    :type value_limit: int
    """
    return hy_st.recursive(
        hy_st.floats() | hy_st.booleans() | hy_st.text() | hy_st.none(),
        lambda children: hy_st.dictionaries(hy_st.text(), children),
        max_leaves=value_limit) 
Example #19
Source File: primitivestrategies.py    From swagger-conformance with MIT License 5 votes vote down vote up
def strategy(self):
        return hy_st.booleans() 
Example #20
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def bare_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields values
    appropriate for that attribute.
    """
    default = NOTHING
    if defaults is True or (defaults is None and draw(st.booleans())):
        default = None
    return (attr.ib(default=default), st.just(None)) 
Example #21
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def int_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields ints for that
    attribute.
    """
    default = NOTHING
    if defaults is True or (defaults is None and draw(st.booleans())):
        default = draw(st.integers())
    return (attr.ib(default=default), st.integers()) 
Example #22
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def str_attrs(draw, defaults=None, type_annotations=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(st.booleans())):
        default = draw(st.text())
    if (type_annotations is None and draw(st.booleans())) or type_annotations:
        type = unicode
    else:
        type = None
    return (attr.ib(default=default, type=type), st.text()) 
Example #23
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def float_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields floats for that
    attribute.
    """
    default = NOTHING
    if defaults is True or (defaults is None and draw(st.booleans())):
        default = draw(st.floats())
    return (attr.ib(default=default), st.floats()) 
Example #24
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def dict_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields dictionaries
    for that attribute. The dictionaries map strings to integers.
    """
    default = NOTHING
    val_strat = st.dictionaries(keys=st.text(), values=st.integers())
    if defaults is True or (defaults is None and draw(st.booleans())):
        default_val = draw(val_strat)
        default = attr.Factory(lambda: default_val)
    return (attr.ib(default=default), val_strat) 
Example #25
Source File: gen_schemas.py    From hypothesis-jsonschema with Mozilla Public License 2.0 5 votes vote down vote up
def _json_schemata(draw: Any, recur: bool = True) -> Any:
    # Current version of jsonschema does not support boolean schemata,
    # but 3.0 will.  See https://github.com/Julian/jsonschema/issues/337
    options = [
        st.builds(dict),
        st.just({"type": "null"}),
        st.just({"type": "boolean"}),
        gen_number("integer"),
        gen_number("number"),
        gen_string(),
        st.builds(dict, const=JSON_STRATEGY),
        gen_enum(),
        st.booleans(),
    ]
    if recur:
        options += [
            gen_array(),
            gen_object(),
            # Conditional subschemata
            gen_if_then_else(),
            json_schemata().map(lambda v: assume(v and v is not True) and {"not": v}),
            st.builds(dict, anyOf=st.lists(json_schemata(), min_size=1)),
            st.builds(dict, oneOf=st.lists(json_schemata(), min_size=1, max_size=2)),
            st.builds(dict, allOf=st.lists(json_schemata(), min_size=1, max_size=2)),
        ]

    return draw(st.one_of(options)) 
Example #26
Source File: gen_schemas.py    From hypothesis-jsonschema with Mozilla Public License 2.0 5 votes vote down vote up
def gen_number(draw: Any, kind: str) -> Dict[str, Union[str, float]]:
    """Draw a numeric schema."""
    max_int_float = 2 ** 53
    lower = draw(st.none() | st.integers(-max_int_float, max_int_float))
    upper = draw(st.none() | st.integers(-max_int_float, max_int_float))
    if lower is not None and upper is not None and lower > upper:
        lower, upper = upper, lower
    multiple_of = draw(
        st.none() | st.integers(2, 100) | st.floats(1 / 1024, 100, exclude_min=True)
    )
    assume(None in (multiple_of, lower, upper) or multiple_of <= (upper - lower))
    assert kind in ("integer", "number")
    out: Dict[str, Union[str, float]] = {"type": kind}
    # Generate the latest draft supported by jsonschema.
    assert hasattr(jsonschema, "Draft7Validator")
    if lower is not None:
        if draw(st.booleans(), label="exclusiveMinimum"):
            out["exclusiveMinimum"] = lower - 1
        else:
            out["minimum"] = lower
    if upper is not None:
        if draw(st.booleans(), label="exclusiveMaximum"):
            out["exclusiveMaximum"] = upper + 1
        else:
            out["maximum"] = upper
    if multiple_of is not None:
        out["multipleOf"] = multiple_of
    return out 
Example #27
Source File: test_bipartite.py    From matchpy with MIT License 5 votes vote down vote up
def bipartite_graph(draw):
    m = draw(st.integers(min_value=1, max_value=4))
    n = draw(st.integers(min_value=m, max_value=5))

    graph = BipartiteGraph()
    for i in range(n):
        for j in range(m):
            b = draw(st.booleans())
            if b:
                graph[i, j] = b

    return graph 
Example #28
Source File: test.py    From lkpy with MIT License 5 votes vote down vote up
def csrs(draw, nrows=None, ncols=None, nnz=None, values=None):
    if ncols is None:
        ncols = draw(st.integers(5, 100))
    elif not isinstance(ncols, int):
        ncols = draw(ncols)

    if nrows is None:
        nrows = draw(st.integers(5, 100))
    elif not isinstance(nrows, int):
        nrows = draw(nrows)

    if nnz is None:
        nnz = draw(st.integers(10, nrows * ncols // 2))
    elif not isinstance(nnz, int):
        nnz = draw(nnz)

    coords = draw(nph.arrays(np.int32, nnz, elements=st.integers(0, nrows*ncols - 1), unique=True))
    rows = np.mod(coords, nrows, dtype=np.int32)
    cols = np.floor_divide(coords, nrows, dtype=np.int32)
    if values is None:
        values = draw(st.booleans())
    if values:
        rng = draw(st.randoms())
        vals = np.array([rng.normalvariate(0, 1) for i in range(nnz)])
    else:
        vals = None
    return matrix.CSR.from_coo(rows, cols, vals, (nrows, ncols)) 
Example #29
Source File: custom_hypothesis_support.py    From pyta with GNU General Public License v3.0 5 votes vote down vote up
def ifexp_node(draw, test=const_node(hs.booleans()),
               expr=const_node(), orelse=const_node()):
    # TODO: Add an option for whether expr and orelse strategies produce the same type.
    test = draw(test)
    expr = draw(expr)
    node = astroid.IfExp()
    node.postinit(test, expr, expr)
    return node 
Example #30
Source File: strategies-and-tactics.py    From escape-from-automanual-testing with GNU Affero General Public License v3.0 5 votes vote down vote up
def a_composite_strategy(draw):
    """Generates a (List[int], index) pair.  The index points to a random positive
    element (>= 1); if there are no positive elements index is None.

    `draw` is used within a composite strategy as, e.g.::

        >>> draw(st.booleans()) # can draw True or False
        True

    Note that `draw` is a reserved parameter that will be used by the
    `st.composite` decorator to interactively draw values from the
    strategies that you invoke within this function. That is, you need
    not pass a value to `draw` when calling this strategy::

       >>> a_composite_strategy().example()
       ([-1, -2, -3, 4], 3)
    """
    # TODO: draw a list, determine the allowed indices, and choose one to return
    lst = []  # TODO: draw a list of integers here
    index = None
    # TODO: determine the list of allowed indices, and choose one if non-empty
    return (lst, index)