Python hypothesis.strategies.fixed_dictionaries() Examples

The following are 13 code examples of hypothesis.strategies.fixed_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: test_browser.py    From crocoite with MIT License 6 votes vote down vote up
def fixedDicts (fixed, dynamic):
    return st.builds (lambda x, y: x.update (y), st.fixed_dictionaries (fixed), st.lists (dynamic)) 
Example #2
Source File: test_browser.py    From crocoite with MIT License 6 votes vote down vote up
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,
                })
            }) 
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: basestrategies.py    From swagger-conformance with MIT License 6 votes vote down vote up
def merge_optional_dict_strategy(required_fields, optional_fields):
    """Combine dicts of strings mapping to required and optional strategies.

    :param required_fields: Mapping containing required fields.
    :type required_fields: dict(str)
    :param optional_fields: Mapping containing optional fields.
    :type optional_fields: dict(str)
    """
    # Create a strategy for a set of keys from the optional dict strategy, then
    # a strategy to build those back into a dictionary.
    # Finally, merge the strategy of selected optionals with the required one.
    opt_keys = hy_st.sets(hy_st.sampled_from(list(optional_fields.keys())))
    selected_optionals = hy_st.builds(
        lambda dictionary, keys: {key: dictionary[key] for key in keys},
        hy_st.fixed_dictionaries(optional_fields),
        opt_keys)
    result = merge_dicts_strategy(hy_st.fixed_dictionaries(required_fields),
                                  selected_optionals)
    return result 
Example #5
Source File: strategies.py    From segpy with GNU Affero General Public License v3.0 5 votes vote down vote up
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)) 
Example #6
Source File: strategies.py    From segpy with GNU Affero General Public License v3.0 5 votes vote down vote up
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) 
Example #7
Source File: test_browser.py    From crocoite with MIT License 5 votes vote down vote up
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) 
Example #8
Source File: test_browser.py    From crocoite with MIT License 5 votes vote down vote up
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
                })
            }) 
Example #9
Source File: fuzzer.py    From fuzz-lightyear with Apache License 2.0 5 votes vote down vote up
def fuzz_parameters(
    parameters: List[Tuple[str, Dict[str, Any]]],
) -> SearchStrategy:
    output = {}
    for name, parameter in parameters:
        output[name] = _fuzz_parameter(parameter)

    return st.fixed_dictionaries(output) 
Example #10
Source File: fuzzer.py    From fuzz-lightyear with Apache License 2.0 5 votes vote down vote up
def _fuzz_object(
    parameter: Dict[str, Any],
    **kwargs: Any,
) -> SearchStrategy:
    # TODO: Handle `additionalProperties`
    output = {}
    for name, specification in parameter['properties'].items():
        try:
            strategy = _get_strategy_from_factory(specification['type'], name)
        except KeyError:
            log.error(
                'Invalid swagger specification: expected \'type\'. Got \'{}\''.format(
                    json.dumps(specification),
                ),
            )
            raise

        if strategy:
            output[name] = strategy
            continue

        # `required` can be True, False, or an array of names that
        # are required.
        required = parameter.get('required', False)
        if required and isinstance(required, list):
            required = name in required

        output[name] = _fuzz_parameter(
            specification,
            bool(required),
        )

    return st.fixed_dictionaries(output) 
Example #11
Source File: test_misc.py    From MyGrad with MIT License 5 votes vote down vote up
def to_min_max(arr: np.ndarray) -> st.SearchStrategy:
    bnd_shape = hnp.broadcastable_shapes(
        shape=arr.shape, max_dims=arr.ndim, max_side=min(arr.shape) if arr.ndim else 1
    )
    bnd_strat = hnp.arrays(
        shape=bnd_shape, elements=st.floats(-1e6, 1e6), dtype=np.float64
    )
    return st.fixed_dictionaries(dict(a_min=bnd_strat, a_max=bnd_strat)) 
Example #12
Source File: test_tensor_manip.py    From MyGrad with MIT License 5 votes vote down vote up
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,)
    ) 
Example #13
Source File: gen_schemas.py    From hypothesis-jsonschema with Mozilla Public License 2.0 5 votes vote down vote up
def gen_enum() -> st.SearchStrategy[Dict[str, List[JSONType]]]:
    """Return a strategy for enum schema."""
    return st.fixed_dictionaries(
        {
            "enum": st.lists(
                JSON_STRATEGY, min_size=1, max_size=10, unique_by=encode_canonical_json
            )
        }
    )