Python源码示例:hypothesis.strategies.one_of()

示例1
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. 
示例2
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 
示例3
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! 
示例4
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(),
            )
        ) 
示例5
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 
示例6
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 
示例7
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,
                })
            }) 
示例8
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) 
示例9
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 
示例10
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,
        )
    ) 
示例11
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
# 
示例12
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))) 
示例13
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) 
示例14
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 
示例15
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 
示例16
def ibm_compatible_non_negative_floats(draw):
    return draw(one_of(
        just(0.0),
        floats(SMALLEST_POSITIVE_NORMAL_IBM_FLOAT, MAX_IBM_FLOAT))) 
示例17
def ibm_compatible_non_positive_floats(draw):
    return draw(one_of(
        just(0.0),
        floats(MIN_IBM_FLOAT, LARGEST_NEGATIVE_NORMAL_IBM_FLOAT))) 
示例18
def slice_node(draw):
    lower = draw(hs.one_of(const_node(hs.integers()), hs.none()))
    upper = draw(hs.one_of(const_node(hs.integers()), hs.none()))
    step = draw(hs.one_of(const_node(hs.integers()), hs.none()))
    node = astroid.Slice()
    node.postinit(lower, upper, step)
    return node 
示例19
def unaryop_node(draw, op=hs.one_of(non_bool_unary_op, unary_bool_operator),
                 operand=const_node()):
    op = draw(op)
    operand = draw(operand)
    node = astroid.UnaryOp(op)
    node.postinit(operand)
    return node 
示例20
def number_or_none(draw):
    return draw(
        one_of(
            none(),
            floats(allow_nan=False),
            complex_numbers(allow_nan=False),
            intc_bounded_intergers(),
        )
    ) 
示例21
def array_with_two_entries(draw, array_length=10_000):
    length = draw(integers(1, max_value=array_length))
    arr = draw(
        arrays(
            dtype=one_of(integer_dtypes(), floating_dtypes()),
            shape=(length, 2),
        )
    )
    assume(not np.any(np.isnan(arr)))
    assume(np.all(np.isfinite(arr)))
    return arr 
示例22
def jsonObject ():
    """ JSON-encodable objects """
    return st.dictionaries (st.text (), st.one_of (st.integers (), st.text ())) 
示例23
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 (),
            ) 
示例24
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) 
示例25
def optional(strategy):
    """Return an optional version of the supplied strategy."""
    return st.one_of(st.none(), strategy) 
示例26
def test_sliding_window(data, x):
    """ Test variations of window-shape, step, and dilation for sliding window
        view of N-dimensional array."""

    win_dim = data.draw(st.integers(1, x.ndim), label="win_dim")
    win_shape = data.draw(
        st.tuples(*(st.integers(1, s) for s in x.shape[-win_dim:])), label="win_shape"
    )
    step = data.draw(
        st.tuples(*(st.integers(1, s) for s in x.shape[-win_dim:])), label="step"
    )

    max_dilation = np.array(x.shape[-win_dim:]) // win_shape
    dilation = data.draw(
        st.one_of(
            st.none()
            | st.integers(1, min(max_dilation))
            | st.tuples(*(st.integers(1, s) for s in max_dilation))
        ),
        label="dilation",
    )
    y = sliding_window_view(x, window_shape=win_shape, step=step, dilation=dilation)

    if dilation is None:
        dilation = np.ones((len(win_shape),), dtype=int)

    if isinstance(dilation, int):
        dilation = np.full((len(win_shape),), fill_value=dilation, dtype=int)

    for ind in np.ndindex(*y.shape[:win_dim]):
        slices = tuple(
            slice(i * s, i * s + w * d, d)
            for i, w, s, d in zip(ind, win_shape, step, dilation)
        )
        assert_allclose(actual=y[tuple([*ind])], desired=x[(..., *slices)]) 
示例27
def test_valid_axes(shape, data, permit_none, pos_only):
    min_dim = data.draw(st.integers(0, len(shape)), label="min_dim")
    max_dim = data.draw(
        st.one_of(st.none(), st.integers(min_dim, len(shape))), label="max_dim"
    )
    axis = data.draw(
        valid_axes(
            ndim=len(shape),
            permit_none=permit_none,
            pos_only=pos_only,
            min_dim=min_dim,
            max_dim=max_dim,
        ),
        label="axis",
    )
    x = np.zeros(shape)
    np.sum(x, axis=axis)
    if not permit_none:
        assert axis is not None

    if pos_only and axis is not None:
        if isinstance(axis, tuple):
            assert all(i >= 0 for i in axis)
        else:
            assert axis >= 0

    if axis is not None:
        if isinstance(axis, tuple):
            assert min_dim <= len(axis)

            if max_dim is not None:
                assert len(axis) <= max_dim
        else:
            assert min_dim <= 1 
示例28
def n_numbers(draw, n):
    numbers = []
    for _ in range(n):
        number = draw(one_of(floats(), integers()))
        numbers.append(number)
    return numbers 
示例29
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)) 
示例30
def chunk_count_st():
    return st.one_of(st.none(), st.integers(min_value=1, max_value=2 ** 5))