當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。