Python hypothesis.strategies.dictionaries() Examples

The following are 20 code examples of hypothesis.strategies.dictionaries(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module hypothesis.strategies , or try the search function .
Example #1
Source File: basestrategies.py    From swagger-conformance with MIT License 6 votes vote down vote up
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 
Example #2
Source File: strategies.py    From attrs with MIT License 6 votes vote down vote up
def simple_attrs_with_metadata(draw):
    """
    Create a simple attribute with arbitrary metadata.
    """
    c_attr = draw(simple_attrs)
    keys = st.booleans() | st.binary() | st.integers() | st.text()
    vals = st.booleans() | st.binary() | st.integers() | st.text()
    metadata = draw(
        st.dictionaries(keys=keys, values=vals, min_size=1, max_size=3)
    )

    return attr.ib(
        default=c_attr._default,
        validator=c_attr._validator,
        repr=c_attr.repr,
        eq=c_attr.eq,
        order=c_attr.order,
        hash=c_attr.hash,
        init=c_attr.init,
        metadata=metadata,
        type=None,
        converter=c_attr.converter,
    ) 
Example #3
Source File: test_output_mask.py    From telepresence with Apache License 2.0 6 votes vote down vote up
def generate_dictionary_with_fixed_tokens(draw):
    """
    Builds random nested dictionary structure which is then used as JSON to
    mask two fixed "token" keys.

    Structure is based on TEST_JSON sample fixture defined above.
    """
    base = draw(
        st.fixed_dictionaries({'token': st.text(printable, min_size=10)})
    )

    optional = draw(
        st.nothing() | st.dictionaries(
            st.text(ascii_letters, min_size=1),
            st.floats() | st.integers() | st.text(printable) | st.booleans()
            | st.nothing(),
            min_size=10,
            max_size=50
        )
    )

    return {**base, **optional} 
Example #4
Source File: xr_util_test.py    From bayesmark with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: signatures_test.py    From bayesmark with Apache License 2.0 6 votes vote down vote up
def sig_pair():
    def separate(D):
        signatures, signatures_ref = {}, {}
        for kk in D:
            if len(D[kk]) == 1:
                v_ref, = D[kk]
                signatures_ref[kk] = np.asarray(v_ref)
            elif len(D[kk]) == 2:
                v, v_ref = D[kk]
                signatures[kk] = np.asarray(v)
                signatures_ref[kk] = np.asarray(v_ref)
            else:
                assert False
        return signatures, signatures_ref

    sig_dict = dictionaries(text(), tuples(bsigs()) | tuples(bsigs(), bsigs()))
    S = sig_dict.map(separate)
    return S 
Example #6
Source File: custom_hypothesis_support.py    From pyta with GNU General Public License v3.0 5 votes vote down vote up
def homogeneous_dictionary(**kwargs):
    """Return a strategy which generates a dictionary of uniform key:value type."""
    return index_types.flatmap(lambda s: hs.dictionaries(s(), s(),  **kwargs)) 
Example #7
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def dict_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields dictionaries
    for that attribute. The dictionaries map strings to integers.
    """
    default = NOTHING
    val_strat = st.dictionaries(keys=st.text(), values=st.integers())
    if defaults is True or (defaults is None and draw(st.booleans())):
        default_val = draw(val_strat)
        default = attr.Factory(lambda: default_val)
    return (attr.ib(default=default), val_strat) 
Example #8
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def create_dict_and_type(tuple_of_strats):
    """Map two primitive strategies into a strategy for dict and type."""
    (prim_strat_1, type_1), (prim_strat_2, type_2) = tuple_of_strats

    return st.tuples(
        st.dictionaries(prim_strat_1, prim_strat_2),
        create_generic_dict_type(type_1, type_2),
    ) 
Example #9
Source File: basestrategies.py    From swagger-conformance with MIT License 5 votes vote down vote up
def json(value_limit=5):
    """Hypothesis strategy for generating values that can be passed to
    `json.dumps` to produce valid JSON data.

    :param value_limit: A limit on the number of values in the JSON data -
                        setting this too high can cause value generation to
                        time out.
    :type value_limit: int
    """
    return hy_st.recursive(
        hy_st.floats() | hy_st.booleans() | hy_st.text() | hy_st.none(),
        lambda children: hy_st.dictionaries(hy_st.text(), children),
        max_leaves=value_limit) 
Example #10
Source File: test_prettyprinter.py    From prettyprinter with MIT License 5 votes vote down vote up
def nested_dictionaries():
    simple_strings_alphabet = 'abcdefghijklmnopqrstuvwxyz\'"\r\n '
    simple_text = st.text(alphabet=simple_strings_alphabet, min_size=5)

    def extend(base):
        return st.one_of(
            st.lists(base, min_size=5),
            st.dictionaries(keys=simple_text, values=base, min_size=1)
        )

    return st.recursive(simple_text, extend, max_leaves=50) 
Example #11
Source File: test_prettyprinter.py    From prettyprinter with MIT License 5 votes vote down vote up
def containers(primitives):
    def extend(base):
        return st.one_of(
            st.lists(base, max_size=50),
            st.lists(base, max_size=50).map(tuple),
            st.dictionaries(
                keys=hashable_containers(primitives),
                values=base,
                max_size=10
            ),
        )

    return st.recursive(primitives, extend, max_leaves=50) 
Example #12
Source File: module_conversion.py    From hypothesis-protobuf with MIT License 5 votes vote down vote up
def field_to_strategy(field, env):
    """Generate strategy for field."""
    if SCALAR_MAPPINGS.get(field.type) is not None:
        return apply_modifier(
            strategy=SCALAR_MAPPINGS[field.type],
            field=field
        )

    if field.type is FieldDescriptor.TYPE_ENUM:
        return apply_modifier(
            strategy=find_strategy_in_env(field.enum_type, env),
            field=field
        )

    if field.type is FieldDescriptor.TYPE_MESSAGE:
        field_options = field.message_type.GetOptions()

        if field_options.deprecated:
            return st.none()

        if field_options.map_entry:
            k, v = field.message_type.fields
            return st.dictionaries(
                field_to_strategy(k, env).filter(non_null),
                field_to_strategy(v, env).filter(non_null)
            )

        return apply_modifier(
            strategy=find_strategy_in_env(field.message_type, env),
            field=field
        )

    raise Exception("Unhandled field {}.".format(field)) 
Example #13
Source File: test_browser.py    From crocoite with MIT License 5 votes vote down vote up
def chromeHeaders ():
    # token as defined by https://tools.ietf.org/html/rfc7230#section-3.2.6
    token = st.sampled_from('abcdefghijklmnopqrstuvwxyz0123456789!#$%&\'*+-.^_`|~')
    # XXX: the value should be asciiText without leading/trailing spaces
    return st.dictionaries (token, token) 
Example #14
Source File: test_warc.py    From crocoite with MIT License 5 votes vote down vote up
def jsonObject ():
    """ JSON-encodable objects """
    return st.dictionaries (st.text (), st.one_of (st.integers (), st.text ())) 
Example #15
Source File: custom_hypothesis_support.py    From pyta with GNU General Public License v3.0 5 votes vote down vote up
def dict_node(draw, key=const_node(), value=const_node(), **kwargs):
    items = draw(hs.dictionaries(key, value, **kwargs)).items()
    node = astroid.Dict()
    node.postinit(items)
    return node 
Example #16
Source File: custom_hypothesis_support.py    From pyta with GNU General Public License v3.0 5 votes vote down vote up
def random_dict_variable_homogeneous_value(**kwargs):
    """Return a strategy which generates a random dictionary of variable name and value"""
    return primitive_types.flatmap(lambda s: hs.dictionaries(valid_identifier(), s(), **kwargs)) 
Example #17
Source File: custom_hypothesis_support.py    From pyta with GNU General Public License v3.0 5 votes vote down vote up
def random_dictionary(**kwargs):
    """Return a strategy which generates a random list."""
    return hs.dictionaries(primitive_values, primitive_values, **kwargs) 
Example #18
Source File: unit_test_composer.py    From APIFuzzer with GNU General Public License v3.0 5 votes vote down vote up
def dict_str(draw):
    return draw(st.dictionaries(st.text(min_size=1), st.text(min_size=1), min_size=1)) 
Example #19
Source File: primitivestrategies.py    From swagger-conformance with MIT License 4 votes vote down vote up
def strategy(self):
        """Return a hypothesis strategy defining this collection, including
        random additional properties if the object supports them.

        Will add only up to `MAX_ADDITIONAL_PROPERTIES` extra values to
        prevent data generation taking too long and timing out.

        :param required_properties: The required fields in the generated dict.
        :type required_properties: dict
        :param optional_properties: The optional fields in the generated dict.
        :type optional_properties: dict
        """
        required_properties = {
            name: field.strategy()
            for name, field in self._properties.items()
            if name in self._swagger_definition.required_properties}
        optional_properties = {
            name: field.strategy()
            for name, field in self._properties.items()
            if name not in self._swagger_definition.required_properties}

        # The result must contain the specified propereties.
        result = base_st.merge_optional_dict_strategy(required_properties,
                                                      optional_properties)

        # If we allow arbitrary additional properties, create a dict with some
        # then update it with the fixed ones to ensure they are retained.
        if self._additional_properties:
            # Generate enough to stay within the allowed bounds, but don't
            # generate more than a fixed maximum.
            min_properties = (0 if self._min_properties is None else
                              self._min_properties)
            min_properties = max(0, min_properties - len(required_properties))
            max_properties = (self.MAX_ADDITIONAL_PROPERTIES
                              if self._max_properties is None else
                              self._max_properties)
            max_properties = min(self.MAX_ADDITIONAL_PROPERTIES,
                                 max_properties - len(required_properties))
            max_properties = max(max_properties, min_properties)
            log.debug("Determined max, min extra properties: %r, %r",
                      max_properties, min_properties)
            forbidden_prop_names = set(required_properties.keys() &
                                       optional_properties.keys())
            extra = hy_st.dictionaries(
                hy_st.text().filter(lambda x: x not in forbidden_prop_names),
                base_st.json(),
                min_size=min_properties,
                max_size=max_properties)

            if self._max_properties is not None:
                result = base_st.merge_dicts_max_size_strategy(
                    result, extra, self._max_properties)
            else:
                result = base_st.merge_dicts_strategy(result, extra)

        return result 
Example #20
Source File: gen_schemas.py    From hypothesis-jsonschema with Mozilla Public License 2.0 4 votes vote down vote up
def gen_object(draw: Any) -> Schema:
    """Draw an object schema."""
    out: Schema = {"type": "object"}
    names = draw(st.sampled_from([None, None, None, draw(gen_string())]))
    name_strat = st.text() if names is None else from_schema(names)
    required = draw(
        st.just(False) | st.lists(name_strat, min_size=1, max_size=5, unique=True)
    )

    # Trying to generate schemata that are consistent would mean dealing with
    # overlapping regex and names, and that would suck.  So instead we ensure that
    # there *are* no overlapping requirements, which is much easier.
    properties = draw(st.dictionaries(name_strat, _json_schemata(recur=False)))
    disjoint = REGEX_PATTERNS.filter(
        lambda r: all(re.search(r, string=name) is None for name in properties)
    )
    patterns = draw(st.dictionaries(disjoint, _json_schemata(recur=False), max_size=1))
    additional = draw(st.none() | _json_schemata(recur=False))

    min_size = draw(st.none() | st.integers(0, 5))
    max_size = draw(st.none() | st.integers(2, 5))
    if min_size is not None and max_size is not None and min_size > max_size:
        min_size, max_size = max_size, min_size

    if names is not None:
        out["propertyNames"] = names
    if required:
        out["required"] = required
        if min_size is not None:
            min_size += len(required)
        if max_size is not None:
            max_size += len(required)
    if min_size is not None:
        out["minProperties"] = min_size
    if max_size is not None:
        out["maxProperties"] = max_size
    if properties:
        out["properties"] = properties

        props = st.sampled_from(sorted(properties))
        if draw(st.integers(0, 3)) == 3:
            out["dependencies"] = draw(
                st.dictionaries(props, st.lists(props, unique=True))
            )
        elif draw(st.integers(0, 3)) == 3:
            out["dependencies"] = draw(st.dictionaries(props, json_schemata()))
    if patterns:
        out["patternProperties"] = patterns
    if additional is not None:
        out["additionalProperties"] = additional

    return out