本文整理汇总了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
示例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)
示例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.
示例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)
示例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
示例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))
示例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,
})
})
示例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
示例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)
示例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)
示例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]
示例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])
示例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)
示例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
示例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