Python源码示例:hypothesis.strategies.builds()
示例1
def _get_case_strategy(
endpoint: Endpoint,
extra_static_parameters: Dict[str, Any],
strategies: Dict[str, st.SearchStrategy],
hook_dispatcher: Optional[HookDispatcher] = None,
) -> st.SearchStrategy[Case]:
static_parameters: Dict[str, Any] = {"endpoint": endpoint, **extra_static_parameters}
if endpoint.schema.validate_schema and endpoint.method == "GET":
if endpoint.body is not None:
raise InvalidSchema("Body parameters are defined for GET request.")
static_parameters["body"] = None
strategies.pop("body", None)
context = HookContext(endpoint)
_apply_hooks(strategies, GLOBAL_HOOK_DISPATCHER, context)
_apply_hooks(strategies, endpoint.schema.hooks, context)
if hook_dispatcher is not None:
_apply_hooks(strategies, hook_dispatcher, context)
return st.builds(partial(Case, **static_parameters), **strategies)
示例2
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)
示例3
def urlsStr ():
return st.builds (lambda x: str (x), urls ())
示例4
def fixedDicts (fixed, dynamic):
return st.builds (lambda x, y: x.update (y), st.fixed_dictionaries (fixed), st.lists (dynamic))
示例5
def _get_strategy_from_factory(
expected_type: str,
name: Optional[str] = None,
) -> Optional[SearchStrategy[Any]]:
if name not in get_user_defined_mapping():
return None
def type_cast() -> Any:
"""Use known types to cast output, if applicable."""
output = get_user_defined_mapping()[name]()
if output is None:
# NOTE: We don't currently support `nullable` values, so we use `None`
# as a proxy to exclude the parameter from the final dictionary.
return None
if expected_type == 'string':
return str(output)
elif expected_type == 'integer':
return int(output)
return output
return st.builds(type_cast)
示例6
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,
)
)
示例7
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)
示例8
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
#
示例9
def urls():
"""
Strategy for generating urls.
"""
return st.builds(
parsed_url,
scheme=st.sampled_from(uri_schemes),
netloc=dns_names(),
path=st.lists(
st.text(
max_size=64,
alphabet=st.characters(
blacklist_characters="/?#", blacklist_categories=("Cs",)
),
),
min_size=1,
max_size=10,
)
.map(to_text)
.map("".join),
)
示例10
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
示例11
def merge_dicts_max_size_strategy(dict1, dict2, max_size):
"""Combine dict strategies into one to produce a dict up to a max size.
Assumes both dicts have distinct keys.
:param max_size: Maximum number of keys in dicts generated by the strategy.
:type max_size: int
"""
# This is grim, but combine both dictionaries after creating a copy of the
# second containing a reduced number of keys if that would take us over the
# max size.
result = hy_st.builds(
lambda x, y: dict((list(x.items()) + list(y.items()))[:max_size]),
dict1,
dict2)
return result
示例12
def auth_url_strategy():
# taken from the hypothesis provisional url generation strategy
def url_encode(s):
return "".join(c if c in URL_SAFE_CHARACTERS else "%%%02X" % ord(c) for c in s)
schemes = ["{0}://".format(scheme) for scheme in uri_schemes if scheme != "file"]
schemes.append("file:///")
return st.builds(
AuthUrl,
scheme=st.sampled_from(schemes),
auth=auth_strings()
.filter(lambda x: x != ":")
.map(lambda x: "" if not x else "{0}@".format(x)),
domain=domains().filter(lambda x: x != "").map(lambda x: x.lower()),
port=st.integers(min_value=0, max_value=65535),
path=st.lists(
st.text(string.printable)
.map(url_encode)
.filter(lambda x: x not in ["", ".", ".."])
).map("/".join),
)
示例13
def as_strategy(self) -> st.SearchStrategy[GraphQLCase]:
constructor = partial(GraphQLCase, path=self.path)
return st.builds(constructor, data=gql_st.query(self.schema))
示例14
def viewport ():
return st.builds (lambda x, y: f'{x}x{y}', st.integers (), st.integers ())
示例15
def event ():
return st.one_of (
st.builds (ControllerStart, jsonObject ()),
st.builds (Script.fromStr, st.text (), st.one_of(st.none (), st.text ())),
st.builds (ScreenshotEvent, urls (), st.integers (), st.binary ()),
st.builds (DomSnapshotEvent, urls (), st.builds (lambda x: x.encode ('utf-8'), st.text ()), viewport()),
requestResponsePair (),
)
示例16
def urls ():
""" Build http/https URL """
scheme = st.sampled_from (['http', 'https'])
# Path must start with a slash
pathSt = st.builds (lambda x: '/' + x, st.text ())
args = st.fixed_dictionaries ({
'scheme': scheme,
'host': domains (),
'port': st.one_of (st.none (), st.integers (min_value=1, max_value=2**16-1)),
'path': pathSt,
'query_string': st.text (),
'fragment': st.text (),
})
return st.builds (lambda x: URL.build (**x), args)
示例17
def urls():
"""
Strategy for generating ``twisted.python.url.URL``\\s.
"""
return s.builds(
URL,
scheme=s.just(u'https'),
host=dns_names(),
path=s.lists(s.text(
max_size=64,
alphabet=s.characters(blacklist_characters=u'/?#',
blacklist_categories=('Cs',))
), min_size=1, max_size=10))
示例18
def buildable(message_obj):
"""Return a "buildable" callable for st.builds which will handle optionals."""
def builder(**kwargs):
return message_obj(**{
k: v
for k, v in kwargs.items()
if v is not None # filter out unpopulated optional param
})
builder.__name__ = message_obj.DESCRIPTOR.full_name
return builder
示例19
def message_to_strategy(message_obj, env, overrides=None):
"""Generate strategy from message."""
# Protobuf messages may have recursive dependencies.
# We can manage these by lazily constructing strategies using st.deferred
return st.deferred(lambda: st.builds(
buildable(message_obj),
**{
field_name: field_to_strategy(field, env, overrides=overrides)
for field_name, field in message_obj.DESCRIPTOR.fields_by_name.items()
})
)
示例20
def auto_parameters(
auto_function_: Callable, *args, auto_limit_: int = 50, **kwargs
) -> Generator[Parameters, None, None]:
"""Generates parameters from the given callable up to the specified limit
(`auto_limit_` parameter).
By default auto_parameters uses type annotations to automatically decide on strategies via the
hypothesis builds strategy. You can override individual strategies by passing them in under
the corresponding `*arg` or `**kwarg` OR you can pass in specific values that must be used for
certain parameters while letting others be auto generated.
All `*arg` and `**kwargs` are automatically passed along to
`hypothesis.strategies.builds` to enable this. Non strategies are automatically converted
to strategies using `hypothesis.strategies.just`.
Except for the following option:
- *auto_limit_*: Number of strategies combinations to run the given function against.
"""
strategy_args = [arg if isinstance(arg, SearchStrategy) else just(arg) for arg in args]
strategy_kwargs = {
name: value if isinstance(value, SearchStrategy) else just(value)
for name, value in kwargs.items()
}
def pass_along_variables(*args, **kwargs):
return Parameters(args=args, kwargs=kwargs)
pass_along_variables.__signature__ = signature(auto_function_) # type: ignore
pass_along_variables.__annotations__ = getattr(auto_function_, "__annotations__", {})
strategy = builds(pass_along_variables, *strategy_args, **strategy_kwargs)
for _ in range(auto_limit_):
yield strategy.example()
示例21
def auto_test_cases(
auto_function_: Callable,
*args,
auto_allow_exceptions_: Union[Tuple[BaseException], Tuple] = (),
auto_limit_: int = 50,
auto_verify_: Optional[Callable[[Scenario], Any]] = None,
**kwargs
) -> Generator[TestCase, None, None]:
"""Generates test cases from the given callable up to the specified limit
(`auto_limit_` parameter).
By default auto_test_cases uses type annotations to automatically decide on strategies via the
hypothesis builds strategy. You can override individual strategies by passing them in under
the corresponding `*arg` or `**kwarg` OR you can pass in specific values that must be used for
certain parameters while letting others be auto generated.
All `*arg` and `**kwargs` are automatically passed along to
`hypothesis.strategies.builds` to enable this. Non strategies are automatically converted
to strategies using `hypothesis.strategies.just`.
Except for the following options:
- *auto_allow_exceptions_*: A tuple of exceptions that are acceptable for the function to raise
and will no be considered a test error.
- *auto_limit_*: Number of strategies combinations to run the given function against.
- *auto_verify_*: An optional callback function that will be called to allow custom verification
of the functions return value. The callback function should raise an AssertionError if the
return value does not match expectations.
"""
test_function = _test_function(
auto_function_, auto_verify_=auto_verify_, auto_allow_exceptions_=auto_allow_exceptions_
)
for parameters in auto_parameters(auto_function_, *args, auto_limit_=auto_limit_, **kwargs):
yield TestCase(parameters=parameters, test_function=test_function)
示例22
def auto_test(
auto_function_: Callable,
*args,
auto_allow_exceptions_: Union[Tuple[BaseException], Tuple] = (),
auto_runs_: int = 50,
auto_verify_: Optional[Callable[[Scenario], Any]] = None,
**kwargs
) -> None:
"""A simple utility function for hypothesis that enables fully automatic testing for a
type hinted callable, including return type verification.
By default auto_test uses type annotations to automatically decide on strategies via the
hypothesis builds strategy. You can override individual strategies by passing them in under
the corresponding `*arg` or `**kwarg` OR you can pass in specific values that must be used for
certain parameters while letting others be auto generated.
All `*arg` and `**kwargs` are automatically passed along to
`hypothesis.strategies.builds` to enable this. Non strategies are automatically converted
to strategies using `hypothesis.strategies.just`.
Except for the following options:
- *auto_allow_exceptions_*: A tuple of exceptions that are acceptable for the function to raise
and will no be considered a test error.
- *auto_runs_*: Number of strategies combinations to run the given function against.
- *auto_verify_*: An optional callback function that will be called to allow custom verification
of the functions return value. The callback function should raise an AssertionError if the
return value does not match expectations.
"""
for test_case in auto_test_cases(
auto_function_,
*args,
auto_allow_exceptions_=auto_allow_exceptions_,
auto_limit_=auto_runs_,
auto_verify_=auto_verify_,
**kwargs
):
test_case()
示例23
def _build_case_strategy(draw: Callable[[SearchStrategy], Any], min_charges_size=0) -> Case:
case_summary = draw(builds(CaseSummary, date=just(DateWithFuture(date=draw(dates())))))
charge_classes = get_charge_classes()
charge_strategy_choices = list(
map(lambda charge_class: _build_charge_strategy(charge_class(), case_summary), charge_classes)
)
charge_strategy = one_of(charge_strategy_choices)
charges = draw(lists(charge_strategy, min_charges_size))
return Case(case_summary, charges=tuple(charges))
示例24
def build_record_strategy(draw: Callable[[SearchStrategy], Any], min_cases_size=0, min_charges_size=0) -> Record:
case_strategy = _build_case_strategy(min_charges_size)
cases = draw(lists(case_strategy, min_cases_size))
record = draw(builds(Record, cases=none()))
return replace(record, cases=tuple(cases))
示例25
def element_size_st():
return st.builds(lambda power: 2 ** power, st.integers(min_value=0, max_value=5))
示例26
def hash_tree_st():
return st.builds(
lambda chunks_and_chunk_count: HashTree.compute(*chunks_and_chunk_count),
chunks_and_chunk_count_st(),
)
示例27
def bitlist_value_st(max_size=None):
return st.builds(tuple, st.lists(st.booleans(), max_size=max_size))
示例28
def bitvector_value_st(size=None):
min_size = size or 1
max_size = size
return st.builds(
tuple, st.lists(st.booleans(), min_size=min_size, max_size=max_size)
)
示例29
def vector_value_st(draw, elements, *, size=None):
if size is None:
size = draw(st.integers(0, 10))
return st.builds(tuple, st.lists(elements, min_size=size, max_size=size))
示例30
def relative_paths():
relative_leaders = (".", "..")
separators = [
to_text(sep) for sep in (os.sep, os.path.sep, os.path.altsep) if sep is not None
]
return st.builds(
relative_path,
leading_dots=st.sampled_from(relative_leaders),
separator=st.sampled_from(separators),
dest=legal_path_chars(),
)