當前位置: 首頁>>代碼示例>>Python>>正文


Python strategies.just方法代碼示例

本文整理匯總了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. 
開發者ID:adlnet,項目名稱:xapi-profiles,代碼行數:23,代碼來源:test_matching.py

示例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 
開發者ID:sixty-north,項目名稱:segpy,代碼行數:27,代碼來源:test_float.py

示例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) 
開發者ID:ClusterHQ,項目名稱:flocker,代碼行數:23,代碼來源:test_persistence.py

示例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,
                })
            }) 
開發者ID:PromyLOPh,項目名稱:crocoite,代碼行數:26,代碼來源:test_browser.py

示例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)) 
開發者ID:rsokl,項目名稱:MyGrad,代碼行數:22,代碼來源:test_utils.py

示例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 
開發者ID:uber,項目名稱:bayesmark,代碼行數:20,代碼來源:xr_util_test.py

示例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] 
開發者ID:uber,項目名稱:bayesmark,代碼行數:27,代碼來源:space_test.py

示例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,
        )
    ) 
開發者ID:codeforpdx,項目名稱:recordexpungPDX,代碼行數:25,代碼來源:generator.py

示例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) 
開發者ID:fabiommendes,項目名稱:sidekick,代碼行數:19,代碼來源:base.py

示例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
# 
開發者ID:fabiommendes,項目名稱:sidekick,代碼行數:19,代碼來源:tree.py

示例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),
    ) 
開發者ID:Tinche,項目名稱:cattrs,代碼行數:24,代碼來源:__init__.py

示例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)
    ) 
開發者ID:Tinche,項目名稱:cattrs,代碼行數:24,代碼來源:__init__.py

示例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 
開發者ID:Zac-HD,項目名稱:hypothesis-jsonschema,代碼行數:18,代碼來源:_from_schema.py

示例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))) 
開發者ID:sixty-north,項目名稱:segpy,代碼行數:6,代碼來源:test_float.py

示例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))) 
開發者ID:sixty-north,項目名稱:segpy,代碼行數:6,代碼來源:test_float.py


注:本文中的hypothesis.strategies.just方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。