当前位置: 首页>>代码示例>>Python>>正文


Python strategies.sampled_from方法代码示例

本文整理汇总了Python中hypothesis.strategies.sampled_from方法的典型用法代码示例。如果您正苦于以下问题:Python strategies.sampled_from方法的具体用法?Python strategies.sampled_from怎么用?Python strategies.sampled_from使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在hypothesis.strategies的用法示例。


在下文中一共展示了strategies.sampled_from方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_run_hub

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import sampled_from [as 别名]
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) 
开发者ID:virantha,项目名称:bricknil,代码行数:22,代码来源:test_hub.py

示例2: remote_init_st

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import sampled_from [as 别名]
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 
开发者ID:mantl,项目名称:terraform.py,代码行数:27,代码来源:hypothesis_state.py

示例3: functiondef_node

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import sampled_from [as 别名]
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 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:22,代码来源:custom_hypothesis_support.py

示例4: tagged_union_strategy

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import sampled_from [as 别名]
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) 
开发者ID:ClusterHQ,项目名称:flocker,代码行数:21,代码来源:algebraic.py

示例5: chromeResponseReceived

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import sampled_from [as 别名]
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,
                })
            }) 
开发者ID:PromyLOPh,项目名称:crocoite,代码行数:26,代码来源:test_browser.py

示例6: numpy_video

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import sampled_from [as 别名]
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) 
开发者ID:torchvideo,项目名称:torchvideo,代码行数:24,代码来源:strategies.py

示例7: ds_vars_dims_mixed

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import sampled_from [as 别名]
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 
开发者ID:uber,项目名称:bayesmark,代码行数:20,代码来源:xr_util_test.py

示例8: test_change

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import sampled_from [as 别名]
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 
开发者ID:python-attrs,项目名称:attrs,代码行数:18,代码来源:test_funcs.py

示例9: urls

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import sampled_from [as 别名]
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),
    ) 
开发者ID:sarugaku,项目名称:vistir,代码行数:23,代码来源:strategies.py

示例10: auth_url_strategy

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import sampled_from [as 别名]
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),
    ) 
开发者ID:sarugaku,项目名称:requirementslib,代码行数:23,代码来源:strategies.py

示例11: test_structure_simple_from_dict_default

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import sampled_from [as 别名]
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) 
开发者ID:Tinche,项目名称:cattrs,代码行数:23,代码来源:test_structure_attrs.py

示例12: gen_string

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import sampled_from [as 别名]
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 
开发者ID:Zac-HD,项目名称:hypothesis-jsonschema,代码行数:20,代码来源:gen_schemas.py

示例13: _draw_capabilities

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import sampled_from [as 别名]
def _draw_capabilities(self, data, sensor):
        if len(sensor.allowed_combo) > 0:
            # test capabilities 1 by 1, 
            # or some combination of those in the allowed_combo list
            capabilities = data.draw(
                    st.one_of(
                        st.lists(st.sampled_from([cap.name for cap in list(sensor.capability)]), min_size=1, max_size=1),
                        st.lists(st.sampled_from(sensor.capability), min_size=1, max_size=1),
                        st.lists(st.sampled_from(sensor.allowed_combo), min_size=1, unique=True)
                    )
                )
        else:
            # if no combos allowed, then just test 1 by 1
            capabilities = data.draw(st.lists(st.sampled_from(sensor.capability), min_size=1, max_size=1))
        return capabilities 
开发者ID:virantha,项目名称:bricknil,代码行数:17,代码来源:test_hub.py

示例14: test_attach_sensor

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import sampled_from [as 别名]
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) 
开发者ID:virantha,项目名称:bricknil,代码行数:15,代码来源:test_hub.py

示例15: test_attach_message

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import sampled_from [as 别名]
def test_attach_message(self, data, port, event):
        msg_type = 0x04
        msg = bytearray([msg_type, port, event])
        if event == 0: #detach
            l = self.m.parse(self._with_header(msg))
            assert l == f'Detached IO Port:{port}'
        elif event == 1: #attach
            # Need 10 bytes
            #dev_id = data.draw(st.integers(0,255))
            dev_id = data.draw(st.sampled_from(sorted(DEVICES.keys())))
            fw_version = data.draw(st.lists(st.integers(0,255), min_size=8, max_size=8))
            msg = msg + bytearray([dev_id, 0])+ bytearray(fw_version)
            l = self.m.parse(self._with_header(msg))
            self.hub.peripheral_queue.put.assert_any_call(('update_port', (port, self.m.port_info[port])))
            self.hub.peripheral_queue.put.assert_any_call(('port_detected', port))
            # ALso need to make sure the port info is added to dispatch
            assert self.m.port_info[port]['name'] == DEVICES[dev_id]
        elif event == 2: # virtual attach
            dev_id = data.draw(st.sampled_from(sorted(DEVICES.keys())))
            v_port_a = data.draw(st.integers(0,255))
            v_port_b = data.draw(st.integers(0,255))
            msg = msg + bytearray([dev_id, 0, v_port_a, v_port_b])
            l = self.m.parse(self._with_header(msg))
            self.hub.peripheral_queue.put.assert_any_call(('update_port', (port, self.m.port_info[port])))
            self.hub.peripheral_queue.put.assert_any_call(('port_detected', port))
            assert l == f'Attached VirtualIO Port:{port} {self.m.port_info[port]["name"]} Port A: {v_port_a}, Port B: {v_port_b}'
            assert self.m.port_info[port]['virtual'] == (v_port_a, v_port_b)
            assert self.m.port_info[port]['name'] == DEVICES[dev_id] 
开发者ID:virantha,项目名称:bricknil,代码行数:30,代码来源:test_messages.py


注:本文中的hypothesis.strategies.sampled_from方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。