Python hypothesis.strategies.sampled_from() Examples

The following are 30 code examples of hypothesis.strategies.sampled_from(). 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: 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 #2
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 #3
Source File: custom_hypothesis_support.py    From pyta with GNU General Public License v3.0 6 votes vote down vote up
def functiondef_node(draw, name=None, annotated=False, returns=False):
    name = name or draw(valid_identifier())
    args = draw(arguments_node(annotated))
    body = []
    returns_node = astroid.Return()
    arg_node, arg_type_node = draw(hs.sampled_from(list(zip(args.args, args.annotations))))
    if returns:
        returns_node.postinit(arg_node)
    else:
        returns_node.postinit(const_node(None))
    body.append(returns_node)
    node = astroid.FunctionDef(name=name)
    node.parent = astroid.Module('Default', None)
    node.postinit(
        args,
        body,
        None,
        arg_type_node
    )
    return node 
Example #4
Source File: hypothesis_state.py    From terraform.py with Apache License 2.0 6 votes vote down vote up
def remote_init_st(draw):
    """Hypothesis strategy to generate terraform remote init state."""
    be_type = draw(st.sampled_from(['s3']))
    ri_dict = {
        "version": 3,
        "serial": 0,
        "lineage": draw(lineage_st()),
        "backend": {
            "type": be_type,
            "config": draw(get_be_config_st(be_type)()),
            "hash": draw(st.text(alphabet=list(digits), min_size=18, max_size=18))
        },
        "modules": [
            {
                "path": [
                    "root"
                ],
                "outputs": {},
                "resources": {},
                "depends_on": []
            }
        ]
    }

    return ri_dict 
Example #5
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 #6
Source File: algebraic.py    From flocker with Apache License 2.0 6 votes vote down vote up
def tagged_union_strategy(draw, type_, attr_strategies):
    """
    Create a strategy for building a type with a ``TaggedUnionInvariant``.

    :param type_: Type to generate a strategy for.
    :param attr_strategies: Mapping of attributes to strategies to
        generate corresponding attributes.
    :type attr_strategies: ``dict`` mapping ``str`` to ``SearchStrategy`s.
    """
    invariant = type_.__invariant__
    tag = draw(sampled_from(invariant._allowed_tags))
    attributes = {invariant.tag_attribute: tag}
    for name, strategy in attr_strategies.items():
        if (
                name in invariant.attributes_for_tag[tag]
                or name not in invariant._all_attributes
        ):
            attributes[name] = draw(strategy)
    return type_(**attributes) 
Example #7
Source File: strategies.py    From torchvideo with Mozilla Public License 2.0 6 votes vote down vote up
def numpy_video(
    draw,
    min_length=1,
    max_length=3,
    min_width=1,
    max_width=10,
    min_height=1,
    max_height=10,
    mode=None,
):
    length, height, width = draw(
        video_shape(
            min_length, max_length, min_height, max_height, min_width, max_width
        )
    )
    if mode is None:
        mode = draw(st.sampled_from(["RGB", "L"]))
    if mode == "RGB":
        array_st = arrays(dtype=np.uint8, shape=(length, width, height, 3))
    else:
        array_st = arrays(dtype=np.uint8, shape=(length, width, height))
    return draw(array_st) 
Example #8
Source File: test_funcs.py    From attrs with MIT License 6 votes vote down vote up
def test_change(self, C, data):
        """
        Changes work.
        """
        # Take the first attribute, and change it.
        assume(fields(C))  # Skip classes with no attributes.
        field_names = [a.name for a in fields(C)]
        original = C()
        chosen_names = data.draw(st.sets(st.sampled_from(field_names)))
        # We pay special attention to private attributes, they should behave
        # like in `__init__`.
        change_dict = {
            name.replace("_", ""): data.draw(st.integers())
            for name in chosen_names
        }
        changed = evolve(original, **change_dict)
        for name in chosen_names:
            assert getattr(changed, name) == change_dict[name.replace("_", "")] 
Example #9
Source File: test_structure_attrs.py    From cattrs with MIT License 6 votes vote down vote up
def test_structure_simple_from_dict_default(converter, cl_and_vals, data):
    """Test structuring non-nested attrs classes with default value."""
    cl, vals = cl_and_vals
    obj = cl(*vals)
    attrs_with_defaults = [a for a in fields(cl) if a.default is not NOTHING]
    to_remove = data.draw(
        lists(elements=sampled_from(attrs_with_defaults), unique=True)
    )

    for a in to_remove:
        if isinstance(a.default, Factory):
            setattr(obj, a.name, a.default.factory())
        else:
            setattr(obj, a.name, a.default)

    dumped = asdict(obj)

    for a in to_remove:
        del dumped[a.name]

    assert obj == converter.structure(dumped, cl) 
Example #10
Source File: test_funcs.py    From attrs with MIT License 6 votes vote down vote up
def test_change(self, C, data):
        """
        Changes work.
        """
        # Take the first attribute, and change it.
        assume(fields(C))  # Skip classes with no attributes.
        field_names = [a.name for a in fields(C)]
        original = C()
        chosen_names = data.draw(st.sets(st.sampled_from(field_names)))
        change_dict = {name: data.draw(st.integers()) for name in chosen_names}

        with pytest.deprecated_call():
            changed = assoc(original, **change_dict)

        for k, v in change_dict.items():
            assert getattr(changed, k) == v 
Example #11
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 #12
Source File: test_hub.py    From bricknil with Apache License 2.0 6 votes vote down vote up
def test_run_hub(self, data):

        Hub.hubs = []
        sensor_name = 'sensor'
        sensor = data.draw(st.sampled_from(self.sensor_list))
        capabilities = self._draw_capabilities(data, sensor)

        hub_type = data.draw(st.sampled_from(self.hub_list))
        TestHub, stop_evt = self._get_hub_class(hub_type, sensor, sensor_name, capabilities)
        hub = TestHub('test_hub')

        # Start the hub
        #kernel.run(self._emit_control(TestHub))
        with patch('Adafruit_BluefruitLE.get_provider') as ble,\
             patch('bricknil.ble_queue.USE_BLEAK', False) as use_bleak:
            ble.return_value = MockBLE(hub)
            sensor_obj = getattr(hub, sensor_name)
            sensor_obj.send_message = Mock(side_effect=coroutine(lambda x,y: "the awaitable should return this"))
            kernel.run(self._emit_control, data, hub, stop_evt, ble(), sensor_obj)
            #start(system) 
Example #13
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 #14
Source File: test_typeclass_laws.py    From python-lenses with GNU General Public License v3.0 5 votes vote down vote up
def maybes(substrat):
    return substrat.flatmap(
        lambda a: strat.sampled_from([
            lenses.maybe.Nothing(),
            lenses.maybe.Just(a),
        ])
    )


# the free monoid should be good enough 
Example #15
Source File: test_unstructure.py    From cattrs with MIT License 5 votes vote down vote up
def test_enum_unstructure(enum, dump_strat, data):
    """Dumping enums of primitives converts them to their primitives."""
    converter = Converter(unstruct_strat=dump_strat)

    member = data.draw(sampled_from(list(enum.__members__.values())))

    assert converter.unstructure(member) == member.value 
Example #16
Source File: strategies.py    From requirementslib with MIT License 5 votes vote down vote up
def repo_url_strategy():
    def url_encode(s):
        return "".join(c if c in URL_SAFE_CHARACTERS else "%%%02X" % ord(c) for c in s)

    paths = st.lists(st.text(string.printable).map(url_encode)).map("/".join)
    ports = st.integers(min_value=0, max_value=65535).map(":{}".format)
    fragments = (
        st.text(alphabet="abcdefghijklmnopqrstuvwxyz0123456789_-.")
        .map(url_encode)
        .map("#egg={}".format)
        .map(lambda x: "" if x == "#egg=" else x)
    )
    refs = (
        st.text(alphabet="abcdefghijklmnopqrstuvwxyz0123456789_-")
        .map(url_encode)
        .map("@{}".format)
        .map(lambda x: "" if x == "@" else x)
    )
    scheme = (
        st.sampled_from(vcs_schemes)
        .filter(lambda x: "+" in x)
        .map("{}://".format)
        .map(lambda x: x.replace("file://", "file:///"))
    )
    auth = (
        auth_strings()
        .map("{}@".format)
        .map(lambda x: "" if x == "@" else x)
        .map(lambda x: x.replace(":@", "@") if x.endswith(":@") else x)
    )
    domain = domains().map(lambda x: x.lower())
    return st.builds(
        "{}{}{}{}{}{}{}".format,
        scheme,
        auth,
        domain,
        st.just("|") | ports,
        paths,
        refs,
        fragments,
    ).map(lambda x: x.replace("|", ":") if "git+git@" in x else x.replace("|", "/")) 
Example #17
Source File: strategies.py    From requirementslib with MIT License 5 votes vote down vote up
def random_requirements():
    return st.sampled_from(known_requirements) 
Example #18
Source File: strategies.py    From requirementslib with MIT License 5 votes vote down vote up
def repository_url(draw, elements=random_repositories()):
    repo = draw(elements)
    scheme = draw(
        st.sampled_from(vcs_schemes)
        .filter(lambda s: "+" in s)
        .filter(lambda s: "file" not in s)
    )
    repo_dict = dict(repo._asdict())
    ref = repo_dict.pop("ref", None)
    extras = repo_dict.pop("extras", None)
    subdir = repo_dict.pop("subdirectory", None)
    pkg_name = repo_dict.pop("pkg_name", None)
    if pkg_name is None:
        pkg_name = repo_dict.get("repo")
    extras_str = ""
    ref_str = ""
    subdir_str = ""
    if ref:
        ref_str = "@{0}".format(ref)
    if extras and isinstance(extras, six.string_types):
        extras = [extras]
    if extras:
        extras_str = "[{0}]".format(",".join(extras))
    if subdir:
        subdir_str = "&subdirectory={0}".format(subdir)
    if scheme == "git+git":
        repo_dict["scheme"] = "{0}@".format(scheme)
        repo_dict["pathsep"] = ":"
    else:
        repo_dict["scheme"] = "{0}://".format(scheme)
        repo_dict["pathsep"] = "/"
    repo_dict.update(
        {"ref": ref_str, "extras": extras_str, "subdir": subdir_str, "pkg_name": pkg_name}
    )
    line = "{scheme}{base_url}{pathsep}{user}/{repo}.git{ref}#egg={pkg_name}{subdir}".format(
        **repo_dict
    )
    return line 
Example #19
Source File: strategies.py    From requirementslib with MIT License 5 votes vote down vote up
def random_repositories():
    return st.sampled_from(available_repos) 
Example #20
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 #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: test_cli.py    From habitipy with MIT License 5 votes vote down vote up
def index_id_alias(draw, length):
    r = dict()
    r['i'] = draw(integers(min_value=0,max_value=length-1))
    r['type'] = draw(sampled_from(('index','id','alias')))
    return r 
Example #23
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 #24
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 #25
Source File: primitivestrategies.py    From swagger-conformance with MIT License 5 votes vote down vote up
def strategy(self):
        if self._enum is not None:
            return hy_st.sampled_from(self._enum)

        strategy = hy_st.binary(min_size=self._min_length,
                                max_size=self._max_length)

        return strategy 
Example #26
Source File: primitivestrategies.py    From swagger-conformance with MIT License 5 votes vote down vote up
def strategy(self):
        if self._enum is not None:
            return hy_st.sampled_from(self._enum)

        alphabet = None
        if self._blacklist_chars:
            alphabet = hy_st.characters(
                blacklist_characters=self._blacklist_chars)
        strategy = hy_st.text(alphabet=alphabet,
                              min_size=self._min_length,
                              max_size=self._max_length)

        return strategy 
Example #27
Source File: test_custom_types.py    From swagger-conformance with MIT License 5 votes vote down vote up
def strategy(self):
        if self._enum is not None:
            return hy_st.sampled_from(self._enum)
        strategy = hy_st.text(alphabet=set(string.hexdigits),
                              min_size=6,
                              max_size=6)
        # Don't forget to add the leading `#`.
        strategy = strategy.map(lambda x: "#" + x)

        return strategy 
Example #28
Source File: hypothesis_helper.py    From pyranges with MIT License 5 votes vote down vote up
def genomicfeature(draw):

    dataset_name = draw(feature_data)
    print("dataset name " * 5, dataset_name)
    dataset = getattr(pr.data, dataset_name)()
    dataset = dataset[dataset.Feature.isin(["gene", "transcript", "exon"])]

    # subsetter = draw(arrays(np.bool, shape=len(dataset)))
    gene_ids = list(dataset.gene_id.drop_duplicates())
    genes = draw(
        st.lists(st.sampled_from(gene_ids), unique="True", min_size=1))
    dataset = dataset[dataset.gene_id.isin(genes)]

    return dataset 
Example #29
Source File: strategies.py    From vistir with ISC License 5 votes vote down vote up
def relative_paths():
    relative_leaders = (".", "..")
    separators = [
        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 #30
Source File: test_hub.py    From bricknil with Apache License 2.0 5 votes vote down vote up
def test_attach_sensor(self, data):
        
        sensor_name = 'sensor'
        sensor = data.draw(st.sampled_from(self.sensor_list))
        capabilities = self._draw_capabilities(data, sensor)

        hub_type = data.draw(st.sampled_from(self.hub_list))
        TestHub, stop_evt = self._get_hub_class(hub_type, sensor, sensor_name, capabilities)
        hub = TestHub('testhub')
        # Check to make sure we have the peripheral attached
        # and the sensor inserted as an attribute
        assert sensor_name in hub.peripherals
        assert hasattr(hub, sensor_name)