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

示例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 _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) 
示例4
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,
                })
            }) 
示例5
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)) 
示例6
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 
示例7
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] 
示例8
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,
        )
    ) 
示例9
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) 
示例10
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
# 
示例11
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),
    ) 
示例12
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)
    ) 
示例13
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 
示例14
def ibm_compatible_non_negative_floats(draw):
    return draw(one_of(
        just(0.0),
        floats(SMALLEST_POSITIVE_NORMAL_IBM_FLOAT, MAX_IBM_FLOAT))) 
示例15
def ibm_compatible_non_positive_floats(draw):
    return draw(one_of(
        just(0.0),
        floats(MIN_IBM_FLOAT, LARGEST_NEGATIVE_NORMAL_IBM_FLOAT))) 
示例16
def header(header_class, **kwargs):
    """Create a strategy for producing headers of a specific class.

    Args:
        header_class: The type of header to be produced. This class will be
            introspected to determine suitable strategies for each named
            field.

        **kwargs: Any supplied keyword arguments can be used to fix the value
            of particular header fields.
    """

    field_strategies = {}
    for field_name in header_class.ordered_field_names():
        if field_name in kwargs:
            field_strategy = just(kwargs.pop(field_name))
        else:
            value_type = getattr(header_class, field_name).value_type
            if hasattr(value_type, 'ENUM'):
                field_strategy = sampled_from(sorted(value_type.ENUM))
            else:
                field_strategy = integers(value_type.MINIMUM, value_type.MAXIMUM)
        field_strategies[field_name] = field_strategy

    if len(kwargs) > 0:
        raise TypeError("Unrecognised binary header field names {} for {}".format(
            ', '.join(kwargs.keys()),
            header_class.__name__))

    return fixed_dictionaries(field_strategies) \
           .map(lambda kw: header_class(**kw)) 
示例17
def fixed_dict_of_printable_strings(keys, **overrides):
    """Create a strategy for producing a dictionary of strings with specific keys.

    Args:
        keys: A list of keys which the strategy will associate with arbitrary strings.

        **overrides: Specific keywords arguments can be supplied to associate certain keys
            with specific values.  The values supplied via kwargs override any supplied
            through the keys argument.
    """
    d = {key: text(alphabet=PRINTABLE_ASCII_ALPHABET) for key in keys}
    for keyword in overrides:
        d[keyword] = just(overrides[keyword])
    return fixed_dictionaries(d) 
示例18
def valid_identifier(**kwargs):
    """Return a strategy which generates a valid Python Identifier"""
    return hs.integers(min_value=0, max_value=1000).flatmap(
        lambda n: hs.just(f'x{n}')
    ) 
示例19
def comprehension_node(draw, target=None, iter=None,
                       ifs=hs.just([])):
    target = target or const_node(valid_identifier())
    iter = iter or list_node()
    node = astroid.Comprehension()
    node.postinit(draw(target), draw(iter), draw(ifs))
    return node 
示例20
def graphs(
    draw,
    keys=ascii_uppercase,
    allow_self_links=True,
    directed=True,
    force_path=True,
    edge_cost=False,
):
    result = {c: set() for c in keys}
    for i, c in enumerate(keys):
        # The inner strategy for keys (node identifiers) is a sampled_from,
        # rejecting the current node iff allow_self_links is False.
        # Cost will always be 1, or 1-10 inclusive if edge_cost is True.
        # Then we choose a set of neighbors for node c, and update the graph:
        key_strat = st.sampled_from(keys).filter(lambda k: allow_self_links or k != c)
        cost_strat = st.integers(1, 10) if edge_cost else st.just(1)
        neighbors = draw(
            st.sets(st.tuples(key_strat, cost_strat), min_size=1, max_size=4)
        )

        result[c].update(neighbors)
        if not directed:
            for k in neighbors:
                result[k].add((c, 1))
        if force_path:
            # Ensure that there *is* always a path between any pair of nodes,
            # by linking each node to the next in order.  We therefore have a
            # directed ring, plus some number of cross-links.
            result[c].add((keys[i - 1], 1))
            if not directed:
                result[keys[i - 1]].add((c, 1))
    return result 
示例21
def persistent_state_strategy(draw):
    """
    A hypothesis strategy to generate a ``PersistentState``

    Presently just returns and empty ``PersistentState``
    """
    return PersistentState() 
示例22
def test_no_hash_collisions(self, data):
        """
        Hashes of different deployments do not have hash collisions, hashes of
        the same object have the same hash.
        """
        # With 128 bits of hash, a collision here indicates a fault in the
        # algorithm.

        # Generate the first deployment.
        deployment_a = data.draw(deployment_strategy())

        # Decide if we want to generate a second deployment, or just compare
        # the first deployment to a re-serialized version of itself:
        simple_comparison = data.draw(st.booleans())
        if simple_comparison:
            deployment_b = wire_decode(wire_encode(deployment_a))
        else:
            deployment_b = data.draw(deployment_strategy())

        should_be_equal = (deployment_a == deployment_b)
        if simple_comparison:
            self.assertThat(
                should_be_equal,
                Is(True)
            )

        hash_a = generation_hash(deployment_a)
        hash_b = generation_hash(deployment_b)

        if should_be_equal:
            self.assertThat(
                hash_a,
                Equals(hash_b)
            )
        else:
            self.assertThat(
                hash_a,
                Not(Equals(hash_b))
            ) 
示例23
def random_references(draw):
    '''generates random sorted lists of references with the same prefix like ['IASDHAH1', 'IASDHAH1569', ...]'''
    prefix = st.just(draw(random_prefix()))
    parts = draw(st.lists(random_reference(prefix = prefix)))
    parts.sort()
    return list(map(toRef, parts)) 
示例24
def chromeRequestWillBeSent (reqid, url):
    methodSt = st.sampled_from (['GET', 'POST', 'PUT', 'DELETE'])
    return st.fixed_dictionaries ({
            'requestId': reqid,
            'initiator': st.just ('Test'),
            'wallTime': timestamp,
            'timestamp': timestamp,
            'request': st.fixed_dictionaries ({
                'url': url,
                'method': methodSt,
                'headers': chromeHeaders (),
                # XXX: postData, hasPostData
                })
            }) 
示例25
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)) 
示例26
def test_overrides_respected():
    """Ensure provided overrides are respected."""
    protobuf_strategies = modules_to_strategies(im_pb2, **{
        full_field_name(im_pb2.InstantMessage, 'message'): st.just('test message')
    })
    instant_message_strategy = protobuf_strategies[im_pb2.InstantMessage]
    instant_message_example = instant_message_strategy.example()
    assert instant_message_example.message == 'test message' 
示例27
def axis_arg(*arrs, min_dim=0):
    """ Wrapper for passing valid-axis search strategy to test factory"""
    if arrs[0].ndim:
        return valid_axes(arrs[0].ndim, min_dim=min_dim)
    else:
        return st.just(tuple()) 
示例28
def ddof_arg(*arrs):
    """ Wrapper for passing ddof strategy to test factory
    (argument for var and std)"""
    min_side = min(arrs[0].shape) if arrs[0].shape else 0
    return st.integers(0, min_side - 1) if min_side else st.just(0) 
示例29
def _swap_axes_axis(arr):
    return st.integers(-arr.ndim, arr.ndim - 1) if arr.ndim else st.just(0) 
示例30
def gen_int_repeat_args(arr: Tensor) -> st.SearchStrategy[dict]:
    valid_axis = st.none()
    valid_axis |= st.integers(-arr.ndim, arr.ndim - 1) if arr.ndim else st.just(0)
    return st.fixed_dictionaries(
        dict(repeats=st.integers(min_value=0, max_value=5), axis=valid_axis,)
    )