Python hypothesis.strategies.builds() Examples

The following are 30 code examples of hypothesis.strategies.builds(). 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: _hypothesis.py    From schemathesis with MIT License 6 votes vote down vote up
def _get_case_strategy(
    endpoint: Endpoint,
    extra_static_parameters: Dict[str, Any],
    strategies: Dict[str, st.SearchStrategy],
    hook_dispatcher: Optional[HookDispatcher] = None,
) -> st.SearchStrategy[Case]:
    static_parameters: Dict[str, Any] = {"endpoint": endpoint, **extra_static_parameters}
    if endpoint.schema.validate_schema and endpoint.method == "GET":
        if endpoint.body is not None:
            raise InvalidSchema("Body parameters are defined for GET request.")
        static_parameters["body"] = None
        strategies.pop("body", None)
    context = HookContext(endpoint)
    _apply_hooks(strategies, GLOBAL_HOOK_DISPATCHER, context)
    _apply_hooks(strategies, endpoint.schema.hooks, context)
    if hook_dispatcher is not None:
        _apply_hooks(strategies, hook_dispatcher, context)
    return st.builds(partial(Case, **static_parameters), **strategies) 
Example #2
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 #3
Source File: generator.py    From recordexpungPDX with MIT License 6 votes vote down vote up
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,
        )
    ) 
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 requirementslib with MIT License 6 votes vote down vote up
def auth_url_strategy():
    # taken from the hypothesis provisional url generation strategy
    def url_encode(s):
        return "".join(c if c in URL_SAFE_CHARACTERS else "%%%02X" % ord(c) for c in s)

    schemes = ["{0}://".format(scheme) for scheme in uri_schemes if scheme != "file"]
    schemes.append("file:///")
    return st.builds(
        AuthUrl,
        scheme=st.sampled_from(schemes),
        auth=auth_strings()
        .filter(lambda x: x != ":")
        .map(lambda x: "" if not x else "{0}@".format(x)),
        domain=domains().filter(lambda x: x != "").map(lambda x: x.lower()),
        port=st.integers(min_value=0, max_value=65535),
        path=st.lists(
            st.text(string.printable)
            .map(url_encode)
            .filter(lambda x: x not in ["", ".", ".."])
        ).map("/".join),
    ) 
Example #6
Source File: base.py    From sidekick with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: tree.py    From sidekick with MIT License 6 votes vote down vote up
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
# 
Example #8
Source File: fuzzer.py    From fuzz-lightyear with Apache License 2.0 6 votes vote down vote up
def _get_strategy_from_factory(
    expected_type: str,
    name: Optional[str] = None,
) -> Optional[SearchStrategy[Any]]:
    if name not in get_user_defined_mapping():
        return None

    def type_cast() -> Any:
        """Use known types to cast output, if applicable."""
        output = get_user_defined_mapping()[name]()
        if output is None:
            # NOTE: We don't currently support `nullable` values, so we use `None`
            #       as a proxy to exclude the parameter from the final dictionary.
            return None
        if expected_type == 'string':
            return str(output)
        elif expected_type == 'integer':
            return int(output)

        return output

    return st.builds(type_cast) 
Example #9
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 #10
Source File: test_browser.py    From crocoite with MIT License 6 votes vote down vote up
def urlsStr ():
    return st.builds (lambda x: str (x), urls ()) 
Example #11
Source File: strategies.py    From vistir with ISC License 6 votes vote down vote up
def urls():
    """
    Strategy for generating urls.
    """
    return st.builds(
        parsed_url,
        scheme=st.sampled_from(uri_schemes),
        netloc=dns_names(),
        path=st.lists(
            st.text(
                max_size=64,
                alphabet=st.characters(
                    blacklist_characters="/?#", blacklist_categories=("Cs",)
                ),
            ),
            min_size=1,
            max_size=10,
        )
        .map(to_text)
        .map("".join),
    ) 
Example #12
Source File: test_persistence.py    From flocker with Apache License 2.0 6 votes vote down vote up
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) 
Example #13
Source File: basestrategies.py    From swagger-conformance with MIT License 5 votes vote down vote up
def datetimes():
    """Hypothesis strategy for generating `datetime.datetime` values."""
    return hy_st.builds(datetime.datetime.combine, dates(), times()) 
Example #14
Source File: basestrategies.py    From swagger-conformance with MIT License 5 votes vote down vote up
def file_objects():
    """Hypothesis strategy for generating pre-populated `file objects`."""
    return hy_st.builds(io.BytesIO, hy_st.binary()) 
Example #15
Source File: basestrategies.py    From swagger-conformance with MIT License 5 votes vote down vote up
def times():
    """Hypothesis strategy for generating `datetime.time` values."""
    return hy_st.builds(
        datetime.time,
        hour=hy_st.integers(min_value=0, max_value=23),
        minute=hy_st.integers(min_value=0, max_value=59),
        second=hy_st.integers(min_value=0, max_value=59),
        microsecond=hy_st.integers(min_value=0, max_value=999999)) 
Example #16
Source File: gen_schemas.py    From hypothesis-jsonschema with Mozilla Public License 2.0 5 votes vote down vote up
def gen_array(draw: Any) -> Schema:
    """Draw an array schema."""
    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
    items = draw(
        st.builds(dict)
        | _json_schemata(recur=False)
        | st.lists(_json_schemata(recur=False), min_size=1, max_size=10)
    )
    out = {"type": "array", "items": items}
    if isinstance(items, list):
        increment = len(items)
        additional = draw(st.none() | _json_schemata(recur=False))
        if additional is not None:
            out["additionalItems"] = additional
        elif draw(st.booleans()):
            out["contains"] = draw(_json_schemata(recur=False).filter(bool))
            increment += 1
        if min_size is not None:
            min_size += increment
        if max_size is not None:
            max_size += increment
    else:
        if draw(st.booleans()):
            out["uniqueItems"] = True
        if items == {}:
            out["contains"] = draw(_json_schemata(recur=False))
    if min_size is not None:
        out["minItems"] = min_size
    if max_size is not None:
        out["maxItems"] = max_size
    return out 
Example #17
Source File: basestrategies.py    From swagger-conformance with MIT License 5 votes vote down vote up
def dates():
    """Hypothesis strategy for generating `datetime.date` values."""
    return hy_st.builds(
        datetime.date.fromordinal,
        hy_st.integers(min_value=1, max_value=datetime.date.max.toordinal())) 
Example #18
Source File: strategies.py    From requirementslib with MIT License 5 votes vote down vote up
def urls():
    """
    Strategy for generating urls.
    """

    def url_encode(s):
        return "".join(c if c in URL_SAFE_CHARACTERS else "%%%02X" % ord(c) for c in s)

    return st.builds(
        URI,
        scheme=st.sampled_from(uri_schemes),
        host=domains(),
        port=st.integers(min_value=1, max_value=65535),
        path=st.lists(st.text(string.printable).map(url_encode)).map("/".join),
        query=st.lists(
            st.text(
                max_size=10,
                alphabet=st.characters(
                    blacklist_characters="/?#", blacklist_categories=("Cs",)
                ),
            ),
            min_size=2,
            max_size=2,
        )
        .map("=".join)
        .map(vistir.misc.to_text),
        ref=st.text(max_size=64, alphabet="abcdefghijklmnopqrstuvwxyz0123456789"),
        subdirectory=st.text(
            max_size=64, alphabet="abcdefghijklmnopqrstuvwxyz0123456789"
        ),
        extras=st.lists(
            st.text(max_size=20, alphabet="abcdefghijklmnopqrstuvwxyz0123456789_-."),
            min_size=0,
            max_size=10,
        ),
    ) 
Example #19
Source File: strategies.py    From requirementslib with MIT License 5 votes vote down vote up
def relative_paths():
    relative_leaders = (".", "..")
    separators = [
        vistir.misc.to_text(sep)
        for sep in (os.sep, os.path.sep, os.path.altsep)
        if sep is not None
    ]
    return st.builds(
        relative_path,
        leading_dots=st.sampled_from(relative_leaders),
        separator=st.sampled_from(separators),
        dest=legal_path_chars(),
    ) 
Example #20
Source File: strategies.py    From requirementslib with MIT License 5 votes vote down vote up
def unparsed_urls():
    return st.builds(urllib_parse.urlunparse, urls()) 
Example #21
Source File: strategies.py    From requirementslib with MIT License 5 votes vote down vote up
def vcs_requirements():
    def url_encode(s):
        return "".join(c if c in URL_SAFE_CHARACTERS else "%%%02X" % ord(c) for c in s)

    return st.builds(
        parsed_url,
        scheme=st.sampled_from(vcs_schemes),
        netloc=domains(),
        path=st.lists(st.text(string.printable).map(url_encode)).map("/".join),
        fragment=valid_names(),
    ) 
Example #22
Source File: strategies.py    From requirementslib with MIT License 5 votes vote down vote up
def vcs_req():
    return st.builds(unparse_requirement, vcs_requirements()) 
Example #23
Source File: strategies.py    From requirementslib with MIT License 5 votes vote down vote up
def marker_tuple_val_lists():
    return st.builds(
        MarkerTuple,
        variable=random_marker_variables(),
        op=st.sampled_from(["in", "not in"]),
        value=st.lists(random_marker_values(), min_size=2, max_size=4)
        .map(", ".join)
        .map("'{0}'".format),
    ).map(" ".join) 
Example #24
Source File: strategies.py    From requirementslib with MIT License 5 votes vote down vote up
def marker_tuple():
    return st.builds(
        MarkerTuple,
        variable=random_marker_variables(),
        op=random_marker_ops().filter(lambda x: x not in ("in", "not in")),
        value=random_marker_values().map("'{0}'".format),
    ).map(" ".join) 
Example #25
Source File: strategies.py    From axiom with MIT License 5 votes vote down vote up
def timestamps(*a, **kw):
    """
    Strategy for generating L{epsilon.extime.Time} objects.
    """
    return st.builds(Time.fromDatetime, datetimes(timezones=[], *a, **kw)) 
Example #26
Source File: _from_schema.py    From hypothesis-jsonschema with Mozilla Public License 2.0 5 votes vote down vote up
def from_schema(schema: Union[bool, Schema]) -> st.SearchStrategy[JSONType]:
    """Take a JSON schema and return a strategy for allowed JSON objects.

    Schema reuse with "definitions" and "$ref" is not yet supported, but
    everything else in drafts 04, 05, and 07 is fully tested and working.
    """
    try:
        return __from_schema(schema)
    except Exception as err:
        error = err

        def error_raiser() -> NoReturn:
            raise error

        return st.builds(error_raiser) 
Example #27
Source File: _from_schema.py    From hypothesis-jsonschema with Mozilla Public License 2.0 5 votes vote down vote up
def relative_json_pointers() -> st.SearchStrategy[str]:
    """Return a strategy for strings in relative-json-pointer format."""
    return st.builds(
        operator.add,
        st.from_regex(r"0|[1-9][0-9]*", fullmatch=True),
        st.just("#") | json_pointers(),
    )


# Via the `webcolors` package, to match the logic `jsonschema`
# uses to check it's (non-standard?) "color" format. 
Example #28
Source File: gen_schemas.py    From hypothesis-jsonschema with Mozilla Public License 2.0 5 votes vote down vote up
def _json_schemata(draw: Any, recur: bool = True) -> Any:
    # Current version of jsonschema does not support boolean schemata,
    # but 3.0 will.  See https://github.com/Julian/jsonschema/issues/337
    options = [
        st.builds(dict),
        st.just({"type": "null"}),
        st.just({"type": "boolean"}),
        gen_number("integer"),
        gen_number("number"),
        gen_string(),
        st.builds(dict, const=JSON_STRATEGY),
        gen_enum(),
        st.booleans(),
    ]
    if recur:
        options += [
            gen_array(),
            gen_object(),
            # Conditional subschemata
            gen_if_then_else(),
            json_schemata().map(lambda v: assume(v and v is not True) and {"not": v}),
            st.builds(dict, anyOf=st.lists(json_schemata(), min_size=1)),
            st.builds(dict, oneOf=st.lists(json_schemata(), min_size=1, max_size=2)),
            st.builds(dict, allOf=st.lists(json_schemata(), min_size=1, max_size=2)),
        ]

    return draw(st.one_of(options)) 
Example #29
Source File: tester.py    From hypothesis-auto with MIT License 5 votes vote down vote up
def auto_test(
    auto_function_: Callable,
    *args,
    auto_allow_exceptions_: Union[Tuple[BaseException], Tuple] = (),
    auto_runs_: int = 50,
    auto_verify_: Optional[Callable[[Scenario], Any]] = None,
    **kwargs
) -> None:
    """A simple utility function for hypothesis that enables fully automatic testing for a
    type hinted callable, including return type verification.

    By default auto_test uses type annotations to automatically decide on strategies via the
    hypothesis builds strategy. You can override individual strategies by passing them in under
    the corresponding `*arg` or `**kwarg` OR you can pass in specific values that must be used for
    certain parameters while letting others be auto generated.

    All `*arg` and `**kwargs` are automatically passed along to
    `hypothesis.strategies.builds` to enable this. Non strategies are automatically converted
    to strategies using `hypothesis.strategies.just`.

    Except for the following options:

    - *auto_allow_exceptions_*: A tuple of exceptions that are acceptable for the function to raise
      and will no be considered a test error.
    - *auto_runs_*: Number of strategies combinations to run the given function against.
    - *auto_verify_*: An optional callback function that will be called to allow custom verification
      of the functions return value. The callback function should raise an AssertionError if the
      return value does not match expectations.
    """
    for test_case in auto_test_cases(
        auto_function_,
        *args,
        auto_allow_exceptions_=auto_allow_exceptions_,
        auto_limit_=auto_runs_,
        auto_verify_=auto_verify_,
        **kwargs
    ):
        test_case() 
Example #30
Source File: schemas.py    From schemathesis with MIT License 5 votes vote down vote up
def as_strategy(self) -> st.SearchStrategy[GraphQLCase]:
        constructor = partial(GraphQLCase, path=self.path)
        return st.builds(constructor, data=gql_st.query(self.schema))