Python源码示例:hypothesis.strategies.booleans()

示例1
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}") 
示例2
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! 
示例3
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 
示例4
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) 
示例5
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) 
示例6
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} 
示例7
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,
    ) 
示例8
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 
示例9
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 
示例10
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() 
示例11
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 
示例12
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 
示例13
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 
示例14
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) 
示例15
def test_no_hash_collisions(self, data):
        """
        Hashes of different deployments do not have hash collisions, hashes of
        the same object have the same hash.
        """
        # With 128 bits of hash, a collision here indicates a fault in the
        # algorithm.

        # Generate the first deployment.
        deployment_a = data.draw(deployment_strategy())

        # Decide if we want to generate a second deployment, or just compare
        # the first deployment to a re-serialized version of itself:
        simple_comparison = data.draw(st.booleans())
        if simple_comparison:
            deployment_b = wire_decode(wire_encode(deployment_a))
        else:
            deployment_b = data.draw(deployment_strategy())

        should_be_equal = (deployment_a == deployment_b)
        if simple_comparison:
            self.assertThat(
                should_be_equal,
                Is(True)
            )

        hash_a = generation_hash(deployment_a)
        hash_b = generation_hash(deployment_b)

        if should_be_equal:
            self.assertThat(
                hash_a,
                Equals(hash_b)
            )
        else:
            self.assertThat(
                hash_a,
                Not(Equals(hash_b))
            ) 
示例16
def _fuzz_boolean(
    parameter: Dict[str, Any],
    **kwargs: Any,
) -> SearchStrategy:
    return st.booleans() 
示例17
def test_transform_always_yields_crops_of_the_correct_size(self, data):
        crop_height = data.draw(st.integers(1, 10))
        crop_width = data.draw(st.integers(1, 10))
        duration = data.draw(st.integers(1, 10))
        fixed_crops = data.draw(st.booleans())
        if fixed_crops:
            more_fixed_crops = data.draw(st.booleans())
        else:
            more_fixed_crops = False
        height = data.draw(st.integers(crop_height, crop_height * 100))
        width = data.draw(st.integers(crop_width, crop_width * 100))

        video_shape = (duration, height, width, 3)

        scale_strategy = st.floats(
            min_value=min(crop_width, crop_height) / min(height, width), max_value=1
        )
        scales = data.draw(st.lists(scale_strategy, min_size=1, max_size=5))
        max_distortion = data.draw(st.integers(0, len(scales)))
        video = NDArrayToPILVideo()(np.ones(video_shape, dtype=np.uint8))
        transform = MultiScaleCropVideo(
            size=ImageShape(height=crop_height, width=crop_width),
            scales=scales,
            max_distortion=max_distortion,
            fixed_crops=fixed_crops,
            more_fixed_crops=more_fixed_crops,
        )
        transformed_video = list(transform(video))
        print("video_shape", video_shape)
        print("scales", scales)
        print("max_distortion", max_distortion)
        print("fixed_crops", fixed_crops)
        print("more_fixed_crops", more_fixed_crops)

        assert len(transformed_video) == duration
        for frame in transformed_video:
            print("crop_size", np.array(frame).shape)
            np.testing.assert_allclose(np.array(frame), np.ones_like(frame))
            assert frame.height == crop_height
            assert frame.width == crop_width 
示例18
def keepdims_arg(*arrs):
    """ Wrapper for passing keep-dims strategy to test factory"""
    return st.booleans() 
示例19
def bool_strat():
    """ einsum's optimize=True option has bugs prior to version 1.14.5
        (caught by these very unit tests!), thus we only test `optimize=True`
        for more recent versions."""
    return st.booleans() if np.__version__ >= "1.14.5" else st.just(False) 
示例20
def test_setitem_sanity_check(x_constant, y_constant, data):
    """ Ensure proper setitem behavior for all combinations of constant/variable Tensors"""
    x = Tensor([1.0, 2.0, 3.0, 4.0], constant=x_constant)
    w = 4 * x

    as_tensor = data.draw(st.booleans()) if y_constant else True
    y = Tensor([1.0, 0.0], constant=y_constant) if as_tensor else np.array([1.0, 0.0])

    w[::2] = np.array([-1.0, -2.0]) * y
    assert_allclose(np.array((-1.0, 8.0, 0.0, 16.0)), w.data)
    w.sum().backward()

    assert isinstance(w, Tensor)
    assert_allclose(w.data, np.array([-1.0, 8.0, 0.0, 16.0]))
    assert w.constant is (x.constant and (not as_tensor or y.constant))

    if x.constant:
        assert x.grad is None
    else:
        assert_allclose(x.grad, np.array([0.0, 4.0, 0.0, 4.0]))

    if as_tensor:
        if y.constant:
            assert y.grad is None
        else:
            assert_allclose(y.grad, np.array([-1.0, -2.0]))

    w.null_gradients()
    assert x.grad is None, "null_gradients failed"

    if as_tensor:
        assert y.grad is None, "null_gradients failed" 
示例21
def valid_shapes(
    draw, size: int, min_len: int = 1, max_len: int = 6
) -> st.SearchStrategy[Union[int, Tuple[int, ...]]]:
    """ Given an array's size, generate a compatible random shape

    Parameters
    ----------
    size : int
    min_len : int
    max_len : int

    Returns
    -------
    st.SearchStrategy[Tuple[int, ...]]
    """

    if not isinstance(size, int) or size < 0:
        raise ValueError(f"size={size} must be a non-negative integer")

    shape_length = draw(st.integers(min_len, max_len))  # type: int
    shape = []  # type: List[int]
    rem = int(size / np.prod(shape))
    while len(shape) < shape_length:
        if len(shape) == shape_length - 1:
            shape.append(-1 if draw(st.booleans()) else rem)
            break

        shape.append(draw(st.sampled_from(_factors(rem))))
        rem = int(size / np.prod(shape))

    return (
        shape[0]
        if len(shape) == 1 and draw(st.booleans())
        else tuple(int(i) for i in shape)
    ) 
示例22
def provide_require_st(draw, filter_=True):  # pragma: no cover
    commands = draw(range_intagers_st)
    provides = draw(
        st.lists(
            st.lists(range_intagers_st, max_size=10),
            min_size = commands,
            max_size = commands
        ),
    )
    is_func = draw(
        st.lists(
            st.booleans(),
            min_size = commands,
            max_size = commands
        )
    )
    provides_set = set()
    for command in provides:
        provides_set.update(command)
    requires = []
    if provides_set:
        for command in provides:
            if command:
                max_prov = max(command)
            else:
                max_prov = 0
            if filter_:
                provides_filter = [x for x in provides_set if x > max_prov]
            else:
                provides_filter = provides_set
            if provides_filter:
                sample = st.sampled_from(provides_filter)
                requires.append(draw(st.lists(sample, max_size=10)))
            else:
                requires.append([])
    else:
        requires = [[]] * commands
    return (provides, requires, is_func) 
示例23
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)) 
示例24
def test_data(draw):
    can_overlap = draw(booleans())
    all_tasks = draw(task_lists)
    if all_tasks:
        i = draw(integers(min_value=0,max_value=len(all_tasks)))
        user_tasks = all_tasks[:i]
        more_tasks = all_tasks[i:]
    else:
        user_tasks = []
        more_tasks = []
    index_lists = lists(
        one_of(
            index_id_alias(len(all_tasks)),
            integer_range(0, len(all_tasks) - 1)),
        min_size=1)
    arguments = draw(lists(index_lists, min_size=1))
    arguments_strings = []
    task_ids = []
    for indexes in arguments:
        arg = ''
        for index in indexes:
            comma = ',' if arg else ''
            if isinstance(index, tuple):
                task_ids.extend(map(lambda x: all_tasks[x]['_id'], range(index[0],index[1]+1)))
                arg += '{comma}{0}-{1}'.format(index[0] + 1, index[1] + 1, comma=comma)
            elif isinstance(index, dict):
                task_ids.append(all_tasks[index['i']]['_id'])
                if index['type'] == 'index':
                    arg += '{comma}{i}'.format(i=index['i'] + 1, comma=comma)
                elif index['type'] == 'id':
                    arg += '{comma}{i}'.format(i=all_tasks[index['i']]['_id'], comma=comma)
                elif index['type'] == 'alias':
                    arg += '{comma}{i}'.format(i=all_tasks[index['i']]['alias'], comma=comma)
        arguments_strings.append(arg)
    if not can_overlap:
        task_ids = list(set(task_ids))
    return (can_overlap, user_tasks, more_tasks, all_tasks, arguments_strings, task_ids, arguments) 
示例25
def test_encode_broadcast_bool():
    broadcast_tester(
        sp.encode,
        "(),(n),(),(),()->(n)",
        otype=bool,
        excluded=(1, 2, 3, 4),
        dtype=[np.int_, CAT_DTYPE, np.bool_, object, np.bool_],
        elements=[integers(0, INT_MAX), from_dtype(np.dtype(CAT_DTYPE)), booleans(), just("bool"), booleans()],
        unique=[False, True, False, False, False],
        min_side={"n": 1},
        map_=encoder_gen,
    ) 
示例26
def test_encode_broadcast_int():
    broadcast_tester(
        sp.encode,
        "(),(n),(),(),()->(n)",
        otype=int,
        excluded=(1, 2, 3, 4),
        dtype=[np.int_, CAT_DTYPE, np.bool_, object, np.bool_],
        elements=[integers(0, INT_MAX), from_dtype(np.dtype(CAT_DTYPE)), booleans(), just("int"), booleans()],
        unique=[False, True, False, False, False],
        min_side={"n": 1},
        map_=encoder_gen,
    ) 
示例27
def test_encode_broadcast_float():
    broadcast_tester(
        sp.encode,
        "(),(n),(),(),()->(n)",
        otype=float,
        excluded=(1, 2, 3, 4),
        dtype=[np.int_, CAT_DTYPE, np.bool_, object, np.bool_],
        elements=[integers(0, INT_MAX), from_dtype(np.dtype(CAT_DTYPE)), booleans(), just("float"), booleans()],
        unique=[False, True, False, False, False],
        min_side={"n": 1},
        map_=encoder_gen,
    ) 
示例28
def test_decode_broadcast_bool():
    broadcast_tester(
        sp.decode,
        "(m,n),(n),()->(m)",
        otype=CAT_DTYPE,
        excluded=(1, 2),
        dtype=[np.bool_, CAT_DTYPE, np.bool_],
        elements=[booleans(), from_dtype(np.dtype(CAT_DTYPE)), booleans()],
        unique=[False, True, False],
        min_side={"n": 1},
        map_=decoder_gen_broadcast,
    ) 
示例29
def test_decode_broadcast_int():
    broadcast_tester(
        sp.decode,
        "(m,n),(n),()->(m)",
        otype=CAT_DTYPE,
        excluded=(1, 2),
        dtype=[np.int_, CAT_DTYPE, np.bool_],
        elements=[integers(INT_MIN, INT_MAX), from_dtype(np.dtype(CAT_DTYPE)), booleans()],
        unique=[False, True, False],
        min_side={"n": 1},
        map_=decoder_gen_broadcast,
    ) 
示例30
def bool_value_st():
    return st.booleans()