当前位置: 首页>>代码示例>>Python>>正文


Python strategies.builds方法代码示例

本文整理汇总了Python中hypothesis.strategies.builds方法的典型用法代码示例。如果您正苦于以下问题:Python strategies.builds方法的具体用法?Python strategies.builds怎么用?Python strategies.builds使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在hypothesis.strategies的用法示例。


在下文中一共展示了strategies.builds方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _get_case_strategy

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import builds [as 别名]
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) 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:20,代码来源:_hypothesis.py

示例2: _build_node

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import builds [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) 
开发者ID:ClusterHQ,项目名称:flocker,代码行数:23,代码来源:test_persistence.py

示例3: _get_strategy_from_factory

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import builds [as 别名]
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) 
开发者ID:Yelp,项目名称:fuzz-lightyear,代码行数:24,代码来源:fuzzer.py

示例4: _build_charge_strategy

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import builds [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,
        )
    ) 
开发者ID:codeforpdx,项目名称:recordexpungPDX,代码行数:25,代码来源:generator.py

示例5: fcall

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import builds [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) 
开发者ID:fabiommendes,项目名称:sidekick,代码行数:19,代码来源:base.py

示例6: trees

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import builds [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
# 
开发者ID:fabiommendes,项目名称:sidekick,代码行数:19,代码来源:tree.py

示例7: urls

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import builds [as 别名]
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),
    ) 
开发者ID:sarugaku,项目名称:vistir,代码行数:23,代码来源:strategies.py

示例8: merge_optional_dict_strategy

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import builds [as 别名]
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 
开发者ID:olipratt,项目名称:swagger-conformance,代码行数:21,代码来源:basestrategies.py

示例9: merge_dicts_max_size_strategy

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import builds [as 别名]
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 
开发者ID:olipratt,项目名称:swagger-conformance,代码行数:18,代码来源:basestrategies.py

示例10: auth_url_strategy

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import builds [as 别名]
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),
    ) 
开发者ID:sarugaku,项目名称:requirementslib,代码行数:23,代码来源:strategies.py

示例11: as_strategy

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import builds [as 别名]
def as_strategy(self) -> st.SearchStrategy[GraphQLCase]:
        constructor = partial(GraphQLCase, path=self.path)
        return st.builds(constructor, data=gql_st.query(self.schema)) 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:5,代码来源:schemas.py

示例12: viewport

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import builds [as 别名]
def viewport ():
    return st.builds (lambda x, y: f'{x}x{y}', st.integers (), st.integers ()) 
开发者ID:PromyLOPh,项目名称:crocoite,代码行数:4,代码来源:test_warc.py

示例13: event

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import builds [as 别名]
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 (),
            ) 
开发者ID:PromyLOPh,项目名称:crocoite,代码行数:10,代码来源:test_warc.py

示例14: urls

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import builds [as 别名]
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) 
开发者ID:PromyLOPh,项目名称:crocoite,代码行数:16,代码来源:test_browser.py

示例15: urlsStr

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import builds [as 别名]
def urlsStr ():
    return st.builds (lambda x: str (x), urls ()) 
开发者ID:PromyLOPh,项目名称:crocoite,代码行数:4,代码来源:test_browser.py


注:本文中的hypothesis.strategies.builds方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。