当前位置: 首页>>代码示例>>Python>>正文


Python strategies.integers方法代码示例

本文整理汇总了Python中hypothesis.strategies.integers方法的典型用法代码示例。如果您正苦于以下问题:Python strategies.integers方法的具体用法?Python strategies.integers怎么用?Python strategies.integers使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在hypothesis.strategies的用法示例。


在下文中一共展示了strategies.integers方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: arguments_node

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import integers [as 别名]
def arguments_node(draw, annotated=False):
    n = draw(hs.integers(min_value=1, max_value=5))
    args = draw(hs.lists(name_node(None), min_size=n, max_size=n))
    if annotated:
        annotations = draw(hs.lists(name_node(annotation), min_size=n, max_size=n))
    else:
        annotations = None
    node = astroid.Arguments()
    node.postinit(
        args,
        None,
        None,
        None,
        annotations
    )
    return node 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:18,代码来源:custom_hypothesis_support.py

示例2: _strategy_2d_array

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import integers [as 别名]
def _strategy_2d_array(dtype, minval=0, maxval=None, **kwargs):
    if 'min_side' in kwargs:
        min_side = kwargs.pop('min_side')
    else:
        min_side = 1

    if 'max_side' in kwargs:
        max_side = kwargs.pop('max_side')
    else:
        max_side = None

    if dtype is np.int:
        elems = st.integers(minval, maxval, **kwargs)
    elif dtype is np.float:
        elems = st.floats(minval, maxval, **kwargs)
    elif dtype is np.str:
        elems = st.text(min_size=minval, max_size=maxval, **kwargs)
    else:
        raise ValueError('no elements strategy for dtype', dtype)

    return arrays(dtype, array_shapes(2, 2, min_side, max_side), elements=elems) 
开发者ID:WZBSocialScienceCenter,项目名称:tmtoolkit,代码行数:23,代码来源:_testtools.py

示例3: test_filter_odd_numbers

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import integers [as 别名]
def test_filter_odd_numbers(x):
    # If we convert any odd integer to a string, the last digit will be odd.
    assert str(x)[-1] in "13579"


# Takeaway
# --------
# While `.filter` was used here to the same effect as `.map` below,
# it should be noted that filtering should not be relied on to reject
# large populations of generated values. Hypothesis will raise if
# a strategy ends up filtering too many values in attempt to generate
# permissible ones.
#
# Suppose you want to generate all integers except 0, this is a perfect
# application of `.filter`:
#    `st.integers().filter(lambda x: x != 0)`


##############################################################################
# Practicing with the `.map(...)` method
# Same tasks as above, without using .filter(...).
# You'll need to change the value of the integer, then convert it to a string. 
开发者ID:Zac-HD,项目名称:escape-from-automanual-testing,代码行数:24,代码来源:strategies-and-tactics.py

示例4: a_composite_strategy

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import integers [as 别名]
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) 
开发者ID:Zac-HD,项目名称:escape-from-automanual-testing,代码行数:24,代码来源:strategies-and-tactics.py

示例5: bits

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import integers [as 别名]
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 
开发者ID:pymtl,项目名称:pymtl3,代码行数:27,代码来源:strategies.py

示例6: same_len_lists

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import integers [as 别名]
def same_len_lists(draw, min_value = None, max_value = None):
    """Draw random arrays of equal lengths

    One precondition of the list version of spherical() is that its inputs must
    be of equal length.
    """
    n = draw(integers(min_value = 0, max_value = 50))
    fixlen = lists(
        floats(
            min_value = min_value,
            max_value = max_value,
            allow_nan = False,
            allow_infinity = False
        ),
        min_size = n,
        max_size = n,
    )
    fixnp = fixlen.map(np.array)
    return (draw(fixnp), draw(fixnp), draw(fixnp)) 
开发者ID:Zabamund,项目名称:wellpathpy,代码行数:21,代码来源:__init__.py

示例7: chromeResponseReceived

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import integers [as 别名]
def chromeResponseReceived (reqid, url):
    mimeTypeSt = st.one_of (st.none (), st.just ('text/html'))
    remoteIpAddressSt = st.one_of (st.none (), st.just ('127.0.0.1'))
    protocolSt = st.one_of (st.none (), st.just ('h2'))
    statusCodeSt = st.integers (min_value=100, max_value=999)
    typeSt = st.sampled_from (['Document', 'Stylesheet', 'Image', 'Media',
            'Font', 'Script', 'TextTrack', 'XHR', 'Fetch', 'EventSource',
            'WebSocket', 'Manifest', 'SignedExchange', 'Ping',
            'CSPViolationReport', 'Other'])
    return st.fixed_dictionaries ({
            'requestId': reqid,
            'timestamp': timestamp,
            'type': typeSt,
            'response': st.fixed_dictionaries ({
                'url': url,
                'requestHeaders': chromeHeaders (), # XXX: make this optional
                'headers': chromeHeaders (),
                'status': statusCodeSt,
                'statusText': asciiText,
                'mimeType': mimeTypeSt,
                'remoteIPAddress': remoteIpAddressSt,
                'protocol': protocolSt,
                })
            }) 
开发者ID:PromyLOPh,项目名称:crocoite,代码行数:26,代码来源:test_browser.py

示例8: test_padding

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import integers [as 别名]
def test_padding(ndim: int, data: st.DataObject):
    """Ensure that convolving a padding-only image with a commensurate kernel yields the single entry: 0"""
    padding = data.draw(
        st.integers(1, 3) | st.tuples(*[st.integers(1, 3)] * ndim), label="padding"
    )
    x = Tensor(
        data.draw(
            hnp.arrays(shape=(1, 1) + (0,) * ndim, dtype=float, elements=st.floats()),
            label="x",
        )
    )
    pad_tuple = padding if isinstance(padding, tuple) else (padding,) * ndim
    kernel = data.draw(
        hnp.arrays(
            shape=(1, 1) + tuple(2 * p for p in pad_tuple),
            dtype=float,
            elements=st.floats(allow_nan=False, allow_infinity=False),
        )
    )
    out = conv_nd(x, kernel, padding=padding, stride=1)
    assert out.shape == (1,) * x.ndim
    assert out.item() == 0.0

    out.sum().backward()
    assert x.grad.shape == x.shape 
开发者ID:rsokl,项目名称:MyGrad,代码行数:27,代码来源:test_conv.py

示例9: test_negative_log_likelihood

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import integers [as 别名]
def test_negative_log_likelihood(data: st.DataObject, labels_as_tensor: bool):
    s = data.draw(
        hnp.arrays(
            shape=hnp.array_shapes(max_side=10, min_dims=2, max_dims=2),
            dtype=float,
            elements=st.floats(-100, 100),
        )
    )
    y_true = data.draw(
        hnp.arrays(
            shape=(s.shape[0],),
            dtype=hnp.integer_dtypes(),
            elements=st.integers(min_value=0, max_value=s.shape[1] - 1),
        ).map(Tensor if labels_as_tensor else lambda x: x)
    )
    scores = Tensor(s)
    nll = negative_log_likelihood(mg.log(mg.nnet.softmax(scores)), y_true)
    nll.backward()

    cross_entropy_scores = Tensor(s)
    ce = softmax_crossentropy(cross_entropy_scores, y_true)
    ce.backward()

    assert_allclose(nll.data, ce.data, atol=1e-5, rtol=1e-5)
    assert_allclose(scores.grad, cross_entropy_scores.grad, atol=1e-5, rtol=1e-5) 
开发者ID:rsokl,项目名称:MyGrad,代码行数:27,代码来源:test_negative_log_likelihood.py

示例10: gen_roll_args

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import integers [as 别名]
def gen_roll_args(draw, arr):
    shift = draw(st.integers() | st.tuples(*(st.integers() for i in arr.shape)))

    if arr.ndim:
        ax_strat = hnp.valid_tuple_axes(
            arr.ndim,
            **(
                dict(min_size=len(shift), max_size=len(shift))
                if isinstance(shift, tuple)
                else {}
            )
        )
        axis = draw(st.none() | st.integers(-arr.ndim, arr.ndim - 1) | ax_strat)
    else:
        axis = None
    return dict(shift=shift, axis=axis) 
开发者ID:rsokl,项目名称:MyGrad,代码行数:18,代码来源:test_tensor_manip.py

示例11: test_prefix_complex

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import integers [as 别名]
def test_prefix_complex(data, stuff):
    pattern, statements = stuff
    quantity = data.draw(integers(min_value=0, max_value=max(0, len(statements) - 1)))
    statements = statements[:quantity]

    works, unhandled = matches(statements, pattern)
    assert works in [partial, success] 
开发者ID:adlnet,项目名称:xapi-profiles,代码行数:9,代码来源:test_matching.py

示例12: string_and_substring

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import integers [as 别名]
def string_and_substring(draw):
    x = draw(text(min_size=2, alphabet=string.printable))
    i = draw(integers(min_value=0, max_value=len(x)-2))
    j = draw(integers(min_value=i+1, max_value=len(x)-1))
    return (x, x[i:j]) 
开发者ID:ptrus,项目名称:suffix-trees,代码行数:7,代码来源:test_gen.py

示例13: string_and_not_substring

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import integers [as 别名]
def string_and_not_substring(draw):
    x = draw(text(min_size=2, alphabet=string.printable))
    i = draw(integers(min_value=1, max_value=len(x)-1))
    y = ''.join(sample(x, i))
    assume(x.find(y) == -1)
    return (x, y) 
开发者ID:ptrus,项目名称:suffix-trees,代码行数:8,代码来源:test_gen.py

示例14: bipartite_graph

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import integers [as 别名]
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 
开发者ID:HPAC,项目名称:matchpy,代码行数:14,代码来源:test_bipartite.py

示例15: sequence_vars

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import integers [as 别名]
def sequence_vars(draw):
    num_vars = draw(st.integers(min_value=1, max_value=4))

    variables = []
    for i in range(num_vars):
        name = 'var{:d}'.format(i)
        count = draw(st.integers(min_value=1, max_value=4))
        minimum = draw(st.integers(min_value=0, max_value=2))

        variables.append(VariableWithCount(name, count, minimum, None))

    return variables 
开发者ID:HPAC,项目名称:matchpy,代码行数:14,代码来源:test_utils.py


注:本文中的hypothesis.strategies.integers方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。