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


Python strategies.one_of方法代码示例

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


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

示例1: pattern_to_statements

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import one_of [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 one_of [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: from_schema

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import one_of [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! 
开发者ID:Zac-HD,项目名称:escape-from-automanual-testing,代码行数:19,代码来源:tough-bonus-problems.py

示例4: number

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import one_of [as 别名]
def number(draw, include_complex_numbers=True):
    if include_complex_numbers:
        return draw(
            one_of(
                floats(allow_nan=False, allow_infinity=False, width=16),
                complex_numbers(allow_nan=False, allow_infinity=False),
                intc_bounded_intergers(),
            )
        )
    else:
        return draw(
            one_of(
                floats(allow_nan=False, allow_infinity=False, width=16),
                intc_bounded_intergers(),
            )
        ) 
开发者ID:GoLP-IST,项目名称:nata,代码行数:18,代码来源:strategies.py

示例5: anyarray

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import one_of [as 别名]
def anyarray(
    draw,
    min_dims: int = 0,
    max_dims: int = 2,
    include_complex_numbers: bool = True,
    dtype: Optional[np.dtype] = None,
):
    if dtype is None:
        if include_complex_numbers:
            dtype = one_of(
                integer_dtypes(), floating_dtypes(), complex_number_dtypes()
            )
        else:
            dtype = one_of(integer_dtypes(), floating_dtypes())

    arr = draw(
        arrays(
            dtype=dtype,
            shape=array_shapes(min_dims=min_dims, max_dims=max_dims),
        )
    )
    assume(not np.any(np.isnan(arr)))
    assume(np.all(np.isfinite(arr)))

    return arr 
开发者ID:GoLP-IST,项目名称:nata,代码行数:27,代码来源:strategies.py

示例6: random_array

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import one_of [as 别名]
def random_array(
    draw,
    *,
    min_dims: int = 0,
    max_dims: int = 3,
    return_with_indexing: bool = False,
):
    arr = draw(
        arrays(
            dtype=one_of(integer_dtypes(), floating_dtypes()),
            shape=array_shapes(min_dims=min_dims, max_dims=max_dims),
        )
    )

    assume(not np.any(np.isnan(arr)))
    assume(np.all(np.isfinite(arr)))

    if return_with_indexing:
        ind = draw(basic_indices(arr.shape))
        return arr, ind
    else:
        return arr 
开发者ID:GoLP-IST,项目名称:nata,代码行数:24,代码来源:test_containers.py

示例7: chromeResponseReceived

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import one_of [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

示例8: requestResponsePair

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

示例9: _fuzz_array

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import one_of [as 别名]
def _fuzz_array(
    parameter: Dict[str, Any],
    required: bool = False,
) -> SearchStrategy:
    item = parameter['items']
    required = parameter.get('required', required)

    # TODO: Handle `oneOf`
    strategy = st.lists(
        elements=_fuzz_parameter(item, required=required),
        min_size=parameter.get(
            'minItems',
            0 if not required else 1,
        ),
        max_size=parameter.get('maxItems', None),
    )
    if not required:
        return st.one_of(st.none(), strategy)

    return strategy 
开发者ID:Yelp,项目名称:fuzz-lightyear,代码行数:22,代码来源:fuzzer.py

示例10: _build_charge_strategy

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import one_of [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

示例11: nested_container_sedes_and_values_st

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import one_of [as 别名]
def nested_container_sedes_and_values_st(draw, size=None):
    if size is None:
        size = draw(st.integers(min_value=1, max_value=4))
    fields = st.one_of(
        basic_sedes_and_values_st(), basic_composite_sedes_and_values_st()
    )
    element_sedes_and_elements_sequence = draw(
        st.lists(fields, min_size=size, max_size=size)
    )
    return draw(
        general_container_sedes_and_values_st(element_sedes_and_elements_sequence)
    )


#
# Combinations
# 
开发者ID:ethereum,项目名称:py-ssz,代码行数:19,代码来源:hashable_strategies.py

示例12: enums_of_primitives

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

示例13: merged_as_strategies

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import one_of [as 别名]
def merged_as_strategies(schemas: List[Schema]) -> st.SearchStrategy[JSONType]:
    assert schemas, "internal error: must pass at least one schema to merge"
    if len(schemas) == 1:
        return from_schema(schemas[0])
    # Try to merge combinations of strategies.
    strats = []
    combined: Set[str] = set()
    inputs = {encode_canonical_json(s): s for s in schemas}
    for group in itertools.chain.from_iterable(
        itertools.combinations(inputs, n) for n in range(len(inputs), 0, -1)
    ):
        if combined.issuperset(group):
            continue
        s = merged([inputs[g] for g in group])
        if s is not None and s != FALSEY:
            validators = [make_validator(s) for s in schemas]
            strats.append(
                from_schema(s).filter(
                    lambda obj: all(v.is_valid(obj) for v in validators)
                )
            )
            combined.update(group)
    return st.one_of(strats) 
开发者ID:Zac-HD,项目名称:hypothesis-jsonschema,代码行数:25,代码来源:_from_schema.py

示例14: regex_patterns

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import one_of [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

示例15: _draw_capabilities

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import one_of [as 别名]
def _draw_capabilities(self, data, sensor):
        if len(sensor.allowed_combo) > 0:
            # test capabilities 1 by 1, 
            # or some combination of those in the allowed_combo list
            capabilities = data.draw(
                    st.one_of(
                        st.lists(st.sampled_from([cap.name for cap in list(sensor.capability)]), min_size=1, max_size=1),
                        st.lists(st.sampled_from(sensor.capability), min_size=1, max_size=1),
                        st.lists(st.sampled_from(sensor.allowed_combo), min_size=1, unique=True)
                    )
                )
        else:
            # if no combos allowed, then just test 1 by 1
            capabilities = data.draw(st.lists(st.sampled_from(sensor.capability), min_size=1, max_size=1))
        return capabilities 
开发者ID:virantha,项目名称:bricknil,代码行数:17,代码来源:test_hub.py


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