Python hypothesis.strategies.none() Examples

The following are 20 code examples of hypothesis.strategies.none(). 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: tough-bonus-problems.py    From escape-from-automanual-testing with GNU Affero General Public License v3.0 6 votes vote down vote up
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! 
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_browser.py    From crocoite with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: gen_schemas.py    From hypothesis-jsonschema with Mozilla Public License 2.0 6 votes vote down vote up
def gen_string(draw: Any) -> Dict[str, Union[str, int]]:
    """Draw a string schema."""
    min_size = draw(st.none() | st.integers(0, 10))
    max_size = draw(st.none() | st.integers(0, 1000))
    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
    pattern = draw(st.none() | REGEX_PATTERNS)
    format_ = draw(st.none() | st.sampled_from(sorted(STRING_FORMATS)))
    out: Dict[str, Union[str, int]] = {"type": "string"}
    if pattern is not None:
        out["pattern"] = pattern
    elif format_ is not None:
        out["format"] = format_
    if min_size is not None:
        out["minLength"] = min_size
    if max_size is not None:
        out["maxLength"] = max_size
    return out 
Example #5
Source File: test_tensor_manip.py    From MyGrad with MIT License 6 votes vote down vote up
def gen_roll_args(draw, arr):
    shift = draw(st.integers() | st.tuples(*(st.integers() for i in arr.shape)))

    if arr.ndim:
        ax_strat = hnp.valid_tuple_axes(
            arr.ndim,
            **(
                dict(min_size=len(shift), max_size=len(shift))
                if isinstance(shift, tuple)
                else {}
            )
        )
        axis = draw(st.none() | st.integers(-arr.ndim, arr.ndim - 1) | ax_strat)
    else:
        axis = None
    return dict(shift=shift, axis=axis) 
Example #6
Source File: test_tensor_manip.py    From MyGrad with MIT License 5 votes vote down vote up
def gen_tuple_repeat_args(draw: st.DataObject.draw, arr: Tensor):

    valid_axis = draw(
        st.none() | (st.integers(-arr.ndim, arr.ndim - 1) if arr.ndim else st.just(0))
    )

    num_repeats = (
        arr.shape[valid_axis] if valid_axis is not None and arr.ndim else arr.size
    )
    repeats = draw(st.tuples(*[st.integers(0, 5)] * num_repeats))
    return dict(repeats=repeats, axis=valid_axis,) 
Example #7
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 #8
Source File: gen_schemas.py    From hypothesis-jsonschema with Mozilla Public License 2.0 5 votes vote down vote up
def gen_number(draw: Any, kind: str) -> Dict[str, Union[str, float]]:
    """Draw a numeric schema."""
    max_int_float = 2 ** 53
    lower = draw(st.none() | st.integers(-max_int_float, max_int_float))
    upper = draw(st.none() | st.integers(-max_int_float, max_int_float))
    if lower is not None and upper is not None and lower > upper:
        lower, upper = upper, lower
    multiple_of = draw(
        st.none() | st.integers(2, 100) | st.floats(1 / 1024, 100, exclude_min=True)
    )
    assume(None in (multiple_of, lower, upper) or multiple_of <= (upper - lower))
    assert kind in ("integer", "number")
    out: Dict[str, Union[str, float]] = {"type": kind}
    # Generate the latest draft supported by jsonschema.
    assert hasattr(jsonschema, "Draft7Validator")
    if lower is not None:
        if draw(st.booleans(), label="exclusiveMinimum"):
            out["exclusiveMinimum"] = lower - 1
        else:
            out["minimum"] = lower
    if upper is not None:
        if draw(st.booleans(), label="exclusiveMaximum"):
            out["exclusiveMaximum"] = upper + 1
        else:
            out["maximum"] = upper
    if multiple_of is not None:
        out["multipleOf"] = multiple_of
    return out 
Example #9
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def optional_attrs(draw, defaults=None):
    """
    Generate a tuple of an attribute and a strategy that yields values
    for that attribute. The strategy generates optional integers.
    """
    default = NOTHING
    val_strat = st.integers() | st.none()
    if defaults is True or (defaults is None and draw(st.booleans())):
        default = draw(val_strat)

    return (attr.ib(default=default), val_strat) 
Example #10
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 #11
Source File: test_prettyprinter.py    From prettyprinter with MIT License 5 votes vote down vote up
def primitives():
    return (
        st.integers() |
        st.floats(allow_nan=False) |
        st.text() |
        st.binary() |
        st.datetimes(timezones=timezones() | st.none()) |
        st.dates() |
        st.times(timezones=timezones() | st.none()) |
        st.timedeltas() |
        st.booleans() |
        st.none()
    ) 
Example #12
Source File: strategies.py    From dataclasses-json with MIT License 5 votes vote down vote up
def optionals(strategy):
    return one_of(strategy, none()) 
Example #13
Source File: custom_hypothesis_support.py    From pyta with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #14
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 #15
Source File: test_sliding_window.py    From MyGrad with MIT License 5 votes vote down vote up
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)]) 
Example #16
Source File: test_sequential_funcs.py    From MyGrad with MIT License 5 votes vote down vote up
def single_axis_arg(*arrs):
    """ Wrapper for passing valid-axis (single-value only)
    search strategy to test factory"""
    if arrs[0].ndim:
        return valid_axes(arrs[0].ndim, single_axis_only=True)
    else:
        return st.none() 
Example #17
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 #18
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 #19
Source File: strategies.py    From requirementslib with MIT License 4 votes vote down vote up
def requirements(
    draw, requirement_selection=random_requirements(), markers=random_marker_strings()
):
    req = draw(requirement_selection)
    marker_selection = draw(markers)
    name, versions, extras, hashes = req
    line = "{0}".format(name)
    if extras is not None:
        extras_choice = draw(st.one_of(st.lists(st.sampled_from(extras)), st.none()))
    else:
        extras_choice = None
    if versions:
        version_choice = draw(st.one_of(st.sampled_from(versions), st.none()))
    else:
        version_choice = None
    hashes_option = None
    if hashes:
        hashes_option = next(iter(h for v, h in hashes if v == version_choice), [])
    spec_op = ""
    extras_list = sorted(set(extras_choice)) if extras_choice is not None else []
    extras_str = "[{0}]".format(",".join(extras_list)) if extras_list else ""
    if not version_choice:
        version_str = ""
    else:
        spec_op = draw(st.sampled_from(list(Specifier._operators.keys())))
        version_str = "{0}{1}".format(spec_op, version_choice)
    line = line_without_markers = "{0}{1}{2}".format(
        line.strip(), extras_str.strip(), version_str.strip()
    )
    as_list = ["{0}".format(line)]
    list_without_markers = as_list[:]
    marker_str = ""
    if marker_selection:
        marker_str = "; {0}".format(marker_selection)
        line = "{0}{1}".format(line, marker_str)
        as_list = ["{0}".format(line)]
    if hashes_option:
        hashes_list = sorted(set(hashes_option))
        hashes_line = " ".join(["--hash={0}".format(h) for h in hashes_list])
        line = "{0} {1}".format(line, hashes_line)
        line_without_markers = "{0} {1}".format(line_without_markers, hashes_line)
        as_list.extend(hashes_list)
        list_without_markers.extend(hashes_list)
    else:
        hashes_list = None
    return NormalRequirement(
        name=name,
        specifier=spec_op,
        version=version_choice,
        extras=extras_list,
        markers=marker_selection,
        hashes=hashes_list,
        line=line,
        line_without_markers=line_without_markers,
        as_list=as_list,
        list_without_markers=list_without_markers,
    ) 
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