本文整理汇总了Python中hypothesis.strategies.booleans方法的典型用法代码示例。如果您正苦于以下问题:Python strategies.booleans方法的具体用法?Python strategies.booleans怎么用?Python strategies.booleans使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类hypothesis.strategies
的用法示例。
在下文中一共展示了strategies.booleans方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: strategy
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import booleans [as 别名]
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: from_schema
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import booleans [as 别名]
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: a_composite_strategy
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import booleans [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)
示例4: bits
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import booleans [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
示例5: requestResponsePair
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import booleans [as 别名]
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)
示例6: action_structures
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import booleans [as 别名]
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)
示例7: generate_dictionary_with_fixed_tokens
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import booleans [as 别名]
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}
示例8: simple_attrs_with_metadata
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import booleans [as 别名]
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,
)
示例9: dfs_min
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import booleans [as 别名]
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
示例10: dfs_no_min
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import booleans [as 别名]
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
示例11: possibly_commented
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import booleans [as 别名]
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()
示例12: har_post_dicts
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import booleans [as 别名]
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
示例13: bipartite_graph
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import booleans [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
示例14: ifexp_node
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import booleans [as 别名]
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
示例15: test_no_hash_collisions
# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import booleans [as 别名]
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))
)