Python hypothesis.strategies.one_of() Examples

The following are 30 code examples of hypothesis.strategies.one_of(). 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: hashable_strategies.py    From py-ssz with MIT License 6 votes vote down vote up
def nested_container_sedes_and_values_st(draw, size=None):
    if size is None:
        size = draw(st.integers(min_value=1, max_value=4))
    fields = st.one_of(
        basic_sedes_and_values_st(), basic_composite_sedes_and_values_st()
    )
    element_sedes_and_elements_sequence = draw(
        st.lists(fields, min_size=size, max_size=size)
    )
    return draw(
        general_container_sedes_and_values_st(element_sedes_and_elements_sequence)
    )


#
# Combinations
# 
Example #2
Source File: fuzzer.py    From fuzz-lightyear with Apache License 2.0 6 votes vote down vote up
def _fuzz_array(
    parameter: Dict[str, Any],
    required: bool = False,
) -> SearchStrategy:
    item = parameter['items']
    required = parameter.get('required', required)

    # TODO: Handle `oneOf`
    strategy = st.lists(
        elements=_fuzz_parameter(item, required=required),
        min_size=parameter.get(
            'minItems',
            0 if not required else 1,
        ),
        max_size=parameter.get('maxItems', None),
    )
    if not required:
        return st.one_of(st.none(), strategy)

    return strategy 
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: 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 #5
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 #6
Source File: test_containers.py    From nata with MIT License 6 votes vote down vote up
def random_array(
    draw,
    *,
    min_dims: int = 0,
    max_dims: int = 3,
    return_with_indexing: bool = False,
):
    arr = draw(
        arrays(
            dtype=one_of(integer_dtypes(), floating_dtypes()),
            shape=array_shapes(min_dims=min_dims, max_dims=max_dims),
        )
    )

    assume(not np.any(np.isnan(arr)))
    assume(np.all(np.isfinite(arr)))

    if return_with_indexing:
        ind = draw(basic_indices(arr.shape))
        return arr, ind
    else:
        return arr 
Example #7
Source File: __init__.py    From cattrs with MIT License 6 votes vote down vote up
def enums_of_primitives(draw):
    """Generate enum classes with primitive values."""
    names = draw(st.sets(st.text(min_size=1), min_size=1))
    n = len(names)
    vals = draw(
        st.one_of(
            st.sets(
                st.one_of(
                    st.integers(),
                    st.floats(allow_nan=False),
                    st.text(min_size=1),
                ),
                min_size=n,
                max_size=n,
            )
        )
    )
    return Enum("HypEnum", list(zip(names, vals))) 
Example #8
Source File: strategies.py    From nata with MIT License 6 votes vote down vote up
def anyarray(
    draw,
    min_dims: int = 0,
    max_dims: int = 2,
    include_complex_numbers: bool = True,
    dtype: Optional[np.dtype] = None,
):
    if dtype is None:
        if include_complex_numbers:
            dtype = one_of(
                integer_dtypes(), floating_dtypes(), complex_number_dtypes()
            )
        else:
            dtype = one_of(integer_dtypes(), floating_dtypes())

    arr = draw(
        arrays(
            dtype=dtype,
            shape=array_shapes(min_dims=min_dims, max_dims=max_dims),
        )
    )
    assume(not np.any(np.isnan(arr)))
    assume(np.all(np.isfinite(arr)))

    return arr 
Example #9
Source File: strategies.py    From nata with MIT License 6 votes vote down vote up
def number(draw, include_complex_numbers=True):
    if include_complex_numbers:
        return draw(
            one_of(
                floats(allow_nan=False, allow_infinity=False, width=16),
                complex_numbers(allow_nan=False, allow_infinity=False),
                intc_bounded_intergers(),
            )
        )
    else:
        return draw(
            one_of(
                floats(allow_nan=False, allow_infinity=False, width=16),
                intc_bounded_intergers(),
            )
        ) 
Example #10
Source File: test_matching.py    From xapi-profiles with Apache License 2.0 6 votes vote down vote up
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. 
Example #11
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 #12
Source File: _from_schema.py    From hypothesis-jsonschema with Mozilla Public License 2.0 6 votes vote down vote up
def merged_as_strategies(schemas: List[Schema]) -> st.SearchStrategy[JSONType]:
    assert schemas, "internal error: must pass at least one schema to merge"
    if len(schemas) == 1:
        return from_schema(schemas[0])
    # Try to merge combinations of strategies.
    strats = []
    combined: Set[str] = set()
    inputs = {encode_canonical_json(s): s for s in schemas}
    for group in itertools.chain.from_iterable(
        itertools.combinations(inputs, n) for n in range(len(inputs), 0, -1)
    ):
        if combined.issuperset(group):
            continue
        s = merged([inputs[g] for g in group])
        if s is not None and s != FALSEY:
            validators = [make_validator(s) for s in schemas]
            strats.append(
                from_schema(s).filter(
                    lambda obj: all(v.is_valid(obj) for v in validators)
                )
            )
            combined.update(group)
    return st.one_of(strats) 
Example #13
Source File: test_float.py    From segpy with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #14
Source File: _from_schema.py    From hypothesis-jsonschema with Mozilla Public License 2.0 6 votes vote down vote up
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 
Example #15
Source File: hashable_strategies.py    From py-ssz with MIT License 5 votes vote down vote up
def nested_composite_sedes_and_values_st():
    return st.one_of(
        nested_vector_sedes_and_values_st(),
        nested_list_sedes_and_values_st(),
        nested_container_sedes_and_values_st(),
    ) 
Example #16
Source File: hashable_strategies.py    From py-ssz with MIT License 5 votes vote down vote up
def composite_sedes_and_values_st():
    return st.one_of(
        basic_composite_sedes_and_values_st(), nested_composite_sedes_and_values_st()
    ) 
Example #17
Source File: hashable_strategies.py    From py-ssz with MIT License 5 votes vote down vote up
def vector_sedes_and_values_st(size=None):
    return st.one_of(
        basic_vector_sedes_and_values_st(size=size),
        nested_vector_sedes_and_values_st(size=size),
    ) 
Example #18
Source File: hashable_strategies.py    From py-ssz with MIT License 5 votes vote down vote up
def basic_sedes_and_values_st():
    # bitlist, bitvector and bytevector are not technically basic, but we include them here as our
    # implementation does not allow them to have children
    return st.one_of(
        boolean_sedes_and_values_st(),
        uint_sedes_and_values_st(),
        bitlist_sedes_and_values_st(),
        bitvector_sedes_and_values_st(),
        bytevector_sedes_and_values_st(),
    ) 
Example #19
Source File: hashable_strategies.py    From py-ssz with MIT License 5 votes vote down vote up
def list_sedes_and_values_st(size=None):
    return st.one_of(
        basic_list_sedes_and_values_st(size=size),
        nested_list_sedes_and_values_st(size=size),
    ) 
Example #20
Source File: test_prettyprinter.py    From prettyprinter with MIT License 5 votes vote down vote up
def hashable_containers(primitives):
    def extend(base):
        return st.one_of(
            st.frozensets(base, max_size=50),
            st.lists(base, max_size=50).map(tuple),
        )
    return st.recursive(primitives, extend) 
Example #21
Source File: hashable_strategies.py    From py-ssz with MIT License 5 votes vote down vote up
def container_sedes_and_values_st(size=None):
    return st.one_of(
        basic_container_sedes_and_values_st(size=size),
        nested_container_sedes_and_values_st(size=size),
    )


#
# Convert plain Python values generated by strategies to serializable or hashable datatypes
# 
Example #22
Source File: testing.py    From kartothek with MIT License 5 votes vote down vote up
def get_scalar_dtype_strategy(exclude=None):
    """
    A `hypothesis` strategy yielding
    """
    possible_strategies = {
        "datetime": hyp_np.datetime64_dtypes(max_period="ms", min_period="ns"),
        "uint": hyp_np.unsigned_integer_dtypes(),
        "int": hyp_np.integer_dtypes(),
        "float": hyp_np.floating_dtypes(),
        "byte": hyp_np.byte_string_dtypes(),
        "unicode": hyp_np.unicode_string_dtypes(),
    }
    if exclude is None:
        exclude = {}
    elif not isinstance(exclude, list):
        exclude = [exclude]
    for ex in exclude:
        if ex in possible_strategies:
            del possible_strategies[ex]
        else:
            raise ValueError(
                "Strategy {} unknown. Possible values are {}".format(
                    ex, possible_strategies.keys()
                )
            )
    return hyp_st.one_of(*list(possible_strategies.values())) 
Example #23
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 #24
Source File: chunk_strategies.py    From py-ssz with MIT License 5 votes vote down vote up
def chunk_count_st():
    return st.one_of(st.none(), st.integers(min_value=1, max_value=2 ** 5)) 
Example #25
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 #26
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 #27
Source File: __init__.py    From cattrs with MIT License 5 votes vote down vote up
def create_generic_dict_type(type1, type2):
    """Create a strategy for generating parameterized dict types."""
    return st.one_of(
        dict_types,
        dict_types.map(lambda t: t[type1, type2]),
        dict_types.map(lambda t: t[Any, type2]),
        dict_types.map(lambda t: t[type1, Any]),
    ) 
Example #28
Source File: test_typeclass_laws.py    From python-lenses with GNU General Public License v3.0 5 votes vote down vote up
def applicatives(substrat):
    return strat.one_of(
        strat.lists(substrat),
        strat.lists(substrat).map(tuple),
        substrat.map(lenses.identity.Identity),
        maybes(substrat),
    ) 
Example #29
Source File: _from_schema.py    From hypothesis-jsonschema with Mozilla Public License 2.0 5 votes vote down vote up
def rfc3339(name: str) -> st.SearchStrategy[str]:
    """Get a strategy for date or time strings in the given RFC3339 format.

    See https://tools.ietf.org/html/rfc3339#section-5.6
    """
    # Hmm, https://github.com/HypothesisWorks/hypothesis/issues/170
    # would make this a lot easier...
    assert name in RFC3339_FORMATS

    def zfill(width: int) -> Callable[[int], str]:
        return lambda v: str(v).zfill(width)

    simple = {
        "date-fullyear": st.integers(0, 9999).map(zfill(4)),
        "date-month": st.integers(1, 12).map(zfill(2)),
        "date-mday": st.integers(1, 28).map(zfill(2)),  # incomplete but valid
        "time-hour": st.integers(0, 23).map(zfill(2)),
        "time-minute": st.integers(0, 59).map(zfill(2)),
        "time-second": st.integers(0, 59).map(zfill(2)),  # ignore negative leap seconds
        "time-secfrac": st.from_regex(r"\.[0-9]+"),
    }
    if name in simple:
        return simple[name]
    if name == "time-numoffset":
        return st.tuples(
            st.sampled_from(["+", "-"]), rfc3339("time-hour"), rfc3339("time-minute")
        ).map("%s%s:%s".__mod__)
    if name == "time-offset":
        return st.one_of(st.just("Z"), rfc3339("time-numoffset"))
    if name == "partial-time":
        return st.times().map(str)
    if name == "date" or name == "full-date":
        return st.dates().map(str)
    if name == "time" or name == "full-time":
        return st.tuples(rfc3339("partial-time"), rfc3339("time-offset")).map("".join)
    assert name == "date-time"
    return st.tuples(rfc3339("full-date"), rfc3339("full-time")).map("T".join) 
Example #30
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))