本文整理汇总了Python中hypothesis.strategies.just方法的典型用法代码示例。如果您正苦于以下问题:Python strategies.just方法的具体用法?Python strategies.just怎么用?Python strategies.just使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类hypothesis.strategies
的用法示例。
在下文中一共展示了strategies.just方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: pattern_to_statements
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import just [as 别名]
def pattern_to_statements(pattern):
if isinstance(pattern, template):
return lists(just(pattern), min_size=1, max_size=1)
rule, value = pattern
if rule == 'sequence':
return tuples(*map(pattern_to_statements, value)).map(unpack_list).map(list)
elif rule == 'alternates':
return one_of(*map(pattern_to_statements, value))
elif rule == 'zeroOrMore':
return lists(pattern_to_statements(value)).map(unpack_list).map(list)
elif rule == 'oneOrMore':
return lists(pattern_to_statements(value), min_size=1).map(unpack_list).map(list)
elif rule == 'optional':
return lists(pattern_to_statements(value), min_size=0, max_size=1).map(unpack_list).map(list)
else:
raise Exception("impossible!", rule)
# this replicates the current scorm pattern, a realistic example of medium
# complexity. Note it has repeated elements, just not in ambiguous ways.
示例2: ibm_compatible_floats
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import just [as 别名]
def ibm_compatible_floats(draw, min_value=None, max_value=None):
if min_value is None:
min_value = MIN_IBM_FLOAT
if max_value is None:
max_value = MAX_IBM_FLOAT
truncated_min_f = max(min_value, MIN_IBM_FLOAT)
truncated_max_f = min(max_value, MAX_IBM_FLOAT)
strategies = []
if truncated_min_f <= LARGEST_NEGATIVE_NORMAL_IBM_FLOAT <= truncated_max_f:
strategies.append(floats(truncated_min_f, LARGEST_NEGATIVE_NORMAL_IBM_FLOAT))
if truncated_min_f <= SMALLEST_POSITIVE_NORMAL_IBM_FLOAT <= truncated_max_f:
strategies.append(floats(SMALLEST_POSITIVE_NORMAL_IBM_FLOAT, truncated_max_f))
if truncated_min_f <= 0 <= truncated_max_f:
strategies.append(just(0.0))
if len(strategies) == 0:
strategies.append(floats(truncated_min_f, truncated_max_f))
ibm = draw(one_of(*strategies))
return ibm
示例3: _build_node
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import just [as 别名]
def _build_node(applications):
# All the manifestations in `applications`.
app_manifestations = set(
app.volume.manifestation for app in applications if app.volume
)
# A set that contains all of those, plus an arbitrary set of
# manifestations.
dataset_ids = frozenset(
app.volume.manifestation.dataset_id
for app in applications if app.volume
)
manifestations = (
st.sets(MANIFESTATIONS.filter(
lambda m: m.dataset_id not in dataset_ids))
.map(pset)
.map(lambda ms: ms.union(app_manifestations))
.map(lambda ms: dict((m.dataset.dataset_id, m) for m in ms)))
return st.builds(
Node, uuid=st.uuids(),
applications=st.just({a.name: a for a in applications}),
manifestations=manifestations)
示例4: chromeResponseReceived
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import just [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,
})
})
示例5: test_reduce_broadcast_keepdim
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import just [as 别名]
def test_reduce_broadcast_keepdim(var_shape, data):
""" example broadcasting: (2, 1, 4) -> (2, 5, 4)"""
grad = data.draw(
hnp.arrays(
dtype=float,
shape=broadcastable_shapes(
shape=var_shape, min_dims=len(var_shape), max_dims=len(var_shape)
),
elements=st.just(1.0),
),
label="grad",
)
reduced_grad = reduce_broadcast(grad=grad, var_shape=var_shape)
assert reduced_grad.shape == tuple(
i if i < j else j for i, j in zip(var_shape, grad.shape)
)
assert (i == 1 for i, j in zip(var_shape, grad.shape) if i < j)
sum_axes = tuple(n for n, (i, j) in enumerate(zip(var_shape, grad.shape)) if i != j)
assert_allclose(actual=reduced_grad, desired=grad.sum(axis=sum_axes, keepdims=True))
示例6: ds_vars_dims_mixed
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import just [as 别名]
def ds_vars_dims_mixed():
def build_it(vars_to_dims_):
all_dims = list(set(sum((list(dd) for dd in vars_to_dims_.values()), [])))
ds = fixed_datasets(vars_to_dims_)
dims = subset_lists(all_dims)
vars_ = sampled_from(list(vars_to_dims_.keys()))
vars_dict = dictionaries(vars_, dims, dict_class=OrderedDict)
vars_dict = vars_dict.map(OrderedDict.items).map(list)
return tuples(ds, vars_dict, just(all_dims))
vars_to_dims_st = vars_to_dims_dicts(min_vars=0, min_dims=0)
S = vars_to_dims_st.flatmap(build_it)
return S
示例7: test_joint_space_warp_fixed_vars
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import just [as 别名]
def test_joint_space_warp_fixed_vars(args):
meta, X, _, fixed_vars = args
# set X vals equal to fixed_vars
for xx in X:
for param in fixed_vars:
xx[param] = fixed_vars[param]
S = sp.JointSpace(meta)
lower, upper = S.get_bounds().T
X_w = S.warp(X)
assert X_w.dtype == sp.WARPED_DTYPE
# Test bounds
lower, upper = S.get_bounds().T
assert np.all(lower <= X_w)
assert np.all(X_w <= upper)
X2 = S.unwarp(X_w, fixed_vals=fixed_vars)
# Make sure we get == not just close in unwarp for fixed vars
for xx in X2:
for param in fixed_vars:
assert xx[param] == fixed_vars[param]
示例8: _build_charge_strategy
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import just [as 别名]
def _build_charge_strategy(
draw: Callable[[SearchStrategy], Any], charge_type: ChargeType, case: CaseSummary
) -> SearchStrategy[Charge]:
if charge_type == DismissedCharge():
disposition_status = one_of(
just(DispositionStatus.DISMISSED), just(DispositionStatus.NO_COMPLAINT), just(DispositionStatus.DIVERTED)
)
else:
disposition_status = one_of(just(DispositionStatus.CONVICTED), just(DispositionStatus.UNRECOGNIZED))
disposition_date = just(DateWithFuture(date=draw(dates(max_value=date(9000, 12, 31)))))
disposition = builds(Disposition, status=disposition_status, date=disposition_date)
arrest_date = just(DateWithFuture(date=draw(dates(max_value=date(9000, 12, 31)))))
probation_revoked_date = one_of(none(), just(DateWithFuture(date=draw(dates(max_value=date(9000, 12, 31))))))
return draw(
builds(
Charge,
charge_type=just(charge_type),
case_number=just(case.case_number),
disposition=disposition,
date=arrest_date,
probation_revoked=probation_revoked_date,
)
)
示例9: fcall
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import just [as 别名]
def fcall(fn, args=None, kwargs=None):
"""
Call function with given positional and keyword args.
"""
if args == () or args is None:
args = st.just(())
elif isinstance(args, (tuple, list)):
args = st.tuples(*args)
if kwargs == {} or kwargs is None:
kwargs = st.just({})
elif isinstance(kwargs, dict):
ks = list(kwargs.keys())
kwargs = st.builds(lambda *xs: dict(zip(ks, xs)), *kwargs.values())
return st.builds(lambda xs, kw: fn(*xs, **kw), args, kwargs)
示例10: trees
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import just [as 别名]
def trees(*args, max_depth=None, allow_attrs=True, **kwargs):
"""
Return random trees.
"""
attrs = st.just([])
kwargs["allow_attrs"] = allow_attrs
if allow_attrs:
keys = identifiers(allow_private=False, exclude=("children", "parent"))
attr = st.tuples(keys, kwargs.get("attrs") or atoms())
attrs = st.lists(attr)
fn = partial(shape_tree, max_depth)
return st.builds(fn, attrs, st.lists(leaves(*args, **kwargs)))
#
# Utility functions
#
示例11: _create_hyp_class
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import just [as 别名]
def _create_hyp_class(attrs_and_strategy):
"""
A helper function for Hypothesis to generate attrs classes.
The result is a tuple: an attrs class, and a tuple of values to
instantiate it.
"""
def key(t):
return t[0].default is not NOTHING
attrs_and_strat = sorted(attrs_and_strategy, key=key)
attrs = [a[0] for a in attrs_and_strat]
for i, a in enumerate(attrs):
a.counter = i
vals = tuple((a[1]) for a in attrs_and_strat)
return st.tuples(
st.just(
make_class("HypClass", OrderedDict(zip(gen_attr_names(), attrs)))
),
st.tuples(*vals),
)
示例12: _create_hyp_nested_strategy
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import just [as 别名]
def _create_hyp_nested_strategy(simple_class_strategy):
"""
Create a recursive attrs class.
Given a strategy for building (simpler) classes, create and return
a strategy for building classes that have as an attribute:
* just the simpler class
* a list of simpler classes
* a dict mapping the string "cls" to a simpler class.
"""
# A strategy producing tuples of the form ([list of attributes], <given
# class strategy>).
attrs_and_classes = st.tuples(
lists_of_attrs(defaults=True), simple_class_strategy
)
return (
attrs_and_classes.flatmap(just_class)
| attrs_and_classes.flatmap(just_class_with_type)
| attrs_and_classes.flatmap(list_of_class)
| attrs_and_classes.flatmap(list_of_class_with_type)
| attrs_and_classes.flatmap(dict_of_class)
)
示例13: regex_patterns
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import just [as 别名]
def regex_patterns(draw: Any) -> str:
"""Return a recursive strategy for simple regular expression patterns."""
fragments = st.one_of(
st.just("."),
st.from_regex(r"\[\^?[A-Za-z0-9]+\]"),
REGEX_PATTERNS.map("{}+".format),
REGEX_PATTERNS.map("{}?".format),
REGEX_PATTERNS.map("{}*".format),
)
result = draw(st.lists(fragments, min_size=1, max_size=3).map("".join))
assert isinstance(result, str)
try:
re.compile(result)
except re.error:
assume(False)
return result
示例14: ibm_compatible_non_negative_floats
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import just [as 别名]
def ibm_compatible_non_negative_floats(draw):
return draw(one_of(
just(0.0),
floats(SMALLEST_POSITIVE_NORMAL_IBM_FLOAT, MAX_IBM_FLOAT)))
示例15: ibm_compatible_non_positive_floats
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import just [as 别名]
def ibm_compatible_non_positive_floats(draw):
return draw(one_of(
just(0.0),
floats(MIN_IBM_FLOAT, LARGEST_NEGATIVE_NORMAL_IBM_FLOAT)))