當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。