Python源码示例:hypothesis.strategies.sets()
示例1
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)
示例2
def test_change(self, C, data):
"""
Changes work.
"""
# Take the first attribute, and change it.
assume(fields(C)) # Skip classes with no attributes.
field_names = [a.name for a in fields(C)]
original = C()
chosen_names = data.draw(st.sets(st.sampled_from(field_names)))
change_dict = {name: data.draw(st.integers()) for name in chosen_names}
with pytest.deprecated_call():
changed = assoc(original, **change_dict)
for k, v in change_dict.items():
assert getattr(changed, k) == v
示例3
def test_change(self, C, data):
"""
Changes work.
"""
# Take the first attribute, and change it.
assume(fields(C)) # Skip classes with no attributes.
field_names = [a.name for a in fields(C)]
original = C()
chosen_names = data.draw(st.sets(st.sampled_from(field_names)))
# We pay special attention to private attributes, they should behave
# like in `__init__`.
change_dict = {
name.replace("_", ""): data.draw(st.integers())
for name in chosen_names
}
changed = evolve(original, **change_dict)
for name in chosen_names:
assert getattr(changed, name) == change_dict[name.replace("_", "")]
示例4
def merge_optional_dict_strategy(required_fields, optional_fields):
"""Combine dicts of strings mapping to required and optional strategies.
:param required_fields: Mapping containing required fields.
:type required_fields: dict(str)
:param optional_fields: Mapping containing optional fields.
:type optional_fields: dict(str)
"""
# Create a strategy for a set of keys from the optional dict strategy, then
# a strategy to build those back into a dictionary.
# Finally, merge the strategy of selected optionals with the required one.
opt_keys = hy_st.sets(hy_st.sampled_from(list(optional_fields.keys())))
selected_optionals = hy_st.builds(
lambda dictionary, keys: {key: dictionary[key] for key in keys},
hy_st.fixed_dictionaries(optional_fields),
opt_keys)
result = merge_dicts_strategy(hy_st.fixed_dictionaries(required_fields),
selected_optionals)
return result
示例5
def enums_of_primitives(draw):
"""Generate enum classes with primitive values."""
names = draw(st.sets(st.text(min_size=1), min_size=1))
n = len(names)
vals = draw(
st.one_of(
st.sets(
st.one_of(
st.integers(),
st.floats(allow_nan=False),
st.text(min_size=1),
),
min_size=n,
max_size=n,
)
)
)
return Enum("HypEnum", list(zip(names, vals)))
示例6
def set_node(draw, elt=const_node(), **kwargs):
"""Return a Set node with elements drawn from elt.
"""
node = astroid.Set()
node.postinit(draw(hs.sets(elt, **kwargs)))
return node
示例7
def graphs(
draw,
keys=ascii_uppercase,
allow_self_links=True,
directed=True,
force_path=True,
edge_cost=False,
):
result = {c: set() for c in keys}
for i, c in enumerate(keys):
# The inner strategy for keys (node identifiers) is a sampled_from,
# rejecting the current node iff allow_self_links is False.
# Cost will always be 1, or 1-10 inclusive if edge_cost is True.
# Then we choose a set of neighbors for node c, and update the graph:
key_strat = st.sampled_from(keys).filter(lambda k: allow_self_links or k != c)
cost_strat = st.integers(1, 10) if edge_cost else st.just(1)
neighbors = draw(
st.sets(st.tuples(key_strat, cost_strat), min_size=1, max_size=4)
)
result[c].update(neighbors)
if not directed:
for k in neighbors:
result[k].add((c, 1))
if force_path:
# Ensure that there *is* always a path between any pair of nodes,
# by linking each node to the next in order. We therefore have a
# directed ring, plus some number of cross-links.
result[c].add((keys[i - 1], 1))
if not directed:
result[keys[i - 1]].add((c, 1))
return result
示例8
def test_sets_and_objects_differ(self):
"""
Sets can be hashed and 1 element sets have a different hash than the
hash of the single element.
"""
self.assertThat(
generation_hash(5),
Not(Equals(generation_hash(frozenset([5]))))
)
示例9
def test_lists_and_objects_differ(self):
"""
Lists can be hashed, and have a different hash value than scalars with
the same value or sets with the same values.
"""
self.assertThat(
generation_hash(913),
Not(Equals(generation_hash([913])))
)
self.assertThat(
generation_hash(frozenset([913])),
Not(Equals(generation_hash([913])))
)
示例10
def test_empty_sets_can_be_hashed(self):
"""
Empty sets can be hashed and result in different hashes than empty
strings or the string 'NULLSET'.
"""
self.assertThat(
generation_hash(frozenset()),
Not(Equals(generation_hash('')))
)
self.assertThat(
generation_hash(frozenset()),
Not(Equals(generation_hash(b'NULLSET')))
)
示例11
def mut_sets_of_primitives(draw):
"""A strategy that generates mutable sets of primitives."""
prim_strat, t = draw(primitive_strategies)
set_t = draw(set_types.map(lambda set_t: set_t[t]) | set_types)
return draw(st.sets(prim_strat)), set_t
示例12
def frozen_sets_of_primitives(draw):
"""A strategy that generates frozen sets of primitives."""
prim_strat, t = draw(primitive_strategies)
set_t = draw(st.just(Set) | st.just(Set[t]))
return frozenset(draw(st.sets(prim_strat))), set_t
示例13
def test_request_examples_without_huffman(self):
"""
This section shows several consecutive header sets, corresponding to
HTTP requests, on the same connection.
"""
e = Encoder()
first_header_set = [
(':method', 'GET',),
(':scheme', 'http',),
(':path', '/',),
(':authority', 'www.example.com'),
]
# We should have :authority in first_header_table since we index it
first_header_table = [(':authority', 'www.example.com')]
first_result = b'\x82\x86\x84\x41\x0fwww.example.com'
assert e.encode(first_header_set, huffman=False) == first_result
assert list(e.header_table.dynamic_entries) == [
(n.encode('utf-8'), v.encode('utf-8'))
for n, v in first_header_table
]
second_header_set = [
(':method', 'GET',),
(':scheme', 'http',),
(':path', '/',),
(':authority', 'www.example.com',),
('cache-control', 'no-cache'),
]
second_header_table = [
('cache-control', 'no-cache'),
(':authority', 'www.example.com')
]
second_result = b'\x82\x86\x84\xbeX\x08no-cache'
assert e.encode(second_header_set, huffman=False) == second_result
assert list(e.header_table.dynamic_entries) == [
(n.encode('utf-8'), v.encode('utf-8'))
for n, v in second_header_table
]
third_header_set = [
(':method', 'GET',),
(':scheme', 'https',),
(':path', '/index.html',),
(':authority', 'www.example.com',),
('custom-key', 'custom-value'),
]
third_result = (
b'\x82\x87\x85\xbf@\ncustom-key\x0ccustom-value'
)
assert e.encode(third_header_set, huffman=False) == third_result
# Don't check the header table here, it's just too complex to be
# reliable. Check its length though.
assert len(e.header_table.dynamic_entries) == 3
示例14
def test_request_examples_without_huffman(self):
"""
This section shows several consecutive header sets, corresponding to
HTTP requests, on the same connection.
"""
d = Decoder()
first_header_set = [
(':method', 'GET',),
(':scheme', 'http',),
(':path', '/',),
(':authority', 'www.example.com'),
]
# The first_header_table doesn't contain 'authority'
first_data = b'\x82\x86\x84\x01\x0fwww.example.com'
assert d.decode(first_data) == first_header_set
assert list(d.header_table.dynamic_entries) == []
# This request takes advantage of the differential encoding of header
# sets.
second_header_set = [
(':method', 'GET',),
(':scheme', 'http',),
(':path', '/',),
(':authority', 'www.example.com',),
('cache-control', 'no-cache'),
]
second_data = (
b'\x82\x86\x84\x01\x0fwww.example.com\x0f\t\x08no-cache'
)
assert d.decode(second_data) == second_header_set
assert list(d.header_table.dynamic_entries) == []
third_header_set = [
(':method', 'GET',),
(':scheme', 'https',),
(':path', '/index.html',),
(':authority', 'www.example.com',),
('custom-key', 'custom-value'),
]
third_data = (
b'\x82\x87\x85\x01\x0fwww.example.com@\ncustom-key\x0ccustom-value'
)
assert d.decode(third_data) == third_header_set
# Don't check the header table here, it's just too complex to be
# reliable. Check its length though.
assert len(d.header_table.dynamic_entries) == 1