コード例 #1
0
ファイル: ipaddress.py プロジェクト: beyonddream/hypothesis
def ip_addresses(
    *,
    v: int = None,
    network: Union[str, IPv4Network, IPv6Network] = None
) -> SearchStrategy[Union[IPv4Address, IPv6Address]]:
    r"""Generate IP addresses - ``v=4`` for :class:`~python:ipaddress.IPv4Address`\ es,
    ``v=6`` for :class:`~python:ipaddress.IPv6Address`\ es, or leave unspecified
    to allow both versions.

    ``network`` may be an :class:`~python:ipaddress.IPv4Network` or
    :class:`~python:ipaddress.IPv6Network`, or a string representing a network such as
    ``"127.0.0.0/24"`` or ``"2001:db8::/32"``.  As well as generating addresses within
    a particular routable network, this can be used to generate addresses from a
    reserved range listed in the
    `IANA <https://www.iana.org/assignments/iana-ipv4-special-registry/>`__
    `registries <https://www.iana.org/assignments/iana-ipv6-special-registry/>`__.

    If you pass both ``v`` and ``network``, they must be for the same version.
    """
    if v is not None:
        check_type(int, v, "v")
        if v != 4 and v != 6:
            raise InvalidArgument("v=%r, but only v=4 or v=6 are valid" %
                                  (v, ))
    if network is None:
        # We use the reserved-address registries to boost the chance
        # of generating one of the various special types of address.
        four = binary(
            4, 4).map(IPv4Address) | sampled_from(SPECIAL_IPv4_RANGES).flatmap(
                lambda network: ip_addresses(network=network))
        six = binary(
            16,
            16).map(IPv6Address) | sampled_from(SPECIAL_IPv6_RANGES).flatmap(
                lambda network: ip_addresses(network=network))
        if v == 4:
            return four
        if v == 6:
            return six
        return four | six
    if isinstance(network, str):
        network = ip_network(network)
    check_type((IPv4Network, IPv6Network), network, "network")
    assert isinstance(network, (IPv4Network, IPv6Network))  # for Mypy
    if v not in (None, network.version):
        raise InvalidArgument("v=%r is incompatible with network=%r" %
                              (v, network))
    addr_type = IPv4Address if network.version == 4 else IPv6Address
    return integers(int(network[0]),
                    int(network[-1])).map(addr_type)  # type: ignore
コード例 #2
0
ファイル: random.py プロジェクト: pexip/os-python-hypothesis
    def _hypothesis_do_random(self, method, kwargs):
        if method == "choices":
            key = (method, len(kwargs["population"]), kwargs.get("k"))
        elif method == "choice":
            key = (method, len(kwargs["seq"]))
        elif method == "shuffle":
            key = (method, len(kwargs["x"]))
        else:
            key = (method, ) + tuple(sorted(kwargs))

        try:
            result, self.__state = self.__state.next_states[key]
        except KeyError:
            pass
        else:
            return self.__convert_result(method, kwargs, result)

        if method == "_randbelow":
            result = cu.integer_range(self.__data, 0, kwargs["n"] - 1)
        elif method in ("betavariate", "random"):
            result = self.__data.draw(UNIFORM)
        elif method == "uniform":
            a = normalize_zero(kwargs["a"])
            b = normalize_zero(kwargs["b"])
            result = self.__data.draw(st.floats(a, b))
        elif method in ("weibullvariate", "gammavariate"):
            result = self.__data.draw(
                st.floats(min_value=0.0, allow_infinity=False))
        elif method in ("gauss", "normalvariate"):
            mu = kwargs["mu"]
            result = mu + self.__data.draw(
                st.floats(allow_nan=False, allow_infinity=False))
        elif method == "vonmisesvariate":
            result = self.__data.draw(st.floats(0, 2 * math.pi))
        elif method == "randrange":
            if kwargs["stop"] is None:
                stop = kwargs["start"]
                start = 0
            else:
                start = kwargs["start"]
                stop = kwargs["stop"]

            step = kwargs["step"]
            if start == stop:
                raise ValueError("empty range for randrange(%d, %d, %d)" %
                                 (start, stop, step))

            if step != 1:
                endpoint = (stop - start) // step
                if (start - stop) % step == 0:
                    endpoint -= 1

                i = cu.integer_range(self.__data, 0, endpoint)
                result = start + i * step
            else:
                result = cu.integer_range(self.__data, start, stop - 1)
        elif method == "randint":
            result = cu.integer_range(self.__data, kwargs["a"], kwargs["b"])
        elif method == "choice":
            seq = kwargs["seq"]
            result = cu.integer_range(self.__data, 0, len(seq) - 1)
        elif method == "choices":
            k = kwargs["k"]
            result = self.__data.draw(
                st.lists(
                    st.integers(0,
                                len(kwargs["population"]) - 1),
                    min_size=k,
                    max_size=k,
                ))
        elif method == "sample":
            k = kwargs["k"]
            seq = kwargs["population"]

            if k > len(seq) or k < 0:
                raise ValueError(
                    "Sample size %d not in expected range 0 <= k <= %d" %
                    (k, len(seq)))

            result = self.__data.draw(
                st.lists(
                    st.sampled_from(range(len(seq))),
                    min_size=k,
                    max_size=k,
                    unique=True,
                ))

        elif method == "getrandbits":
            result = self.__data.draw_bits(kwargs["n"])
        elif method == "triangular":
            low = normalize_zero(kwargs["low"])
            high = normalize_zero(kwargs["high"])
            mode = normalize_zero(kwargs["mode"])
            if mode is None:
                result = self.__data.draw(st.floats(low, high))
            elif self.__data.draw_bits(1):
                result = self.__data.draw(st.floats(mode, high))
            else:
                result = self.__data.draw(st.floats(low, mode))
        elif method in ("paretovariate", "expovariate", "lognormvariate"):
            result = self.__data.draw(st.floats(min_value=0.0))
        elif method == "shuffle":
            result = self.__data.draw(st.permutations(range(len(kwargs["x"]))))
        # This is tested for but only appears in 3.9 so doesn't appear in coverage.
        elif method == "randbytes":  # pragma: no cover
            n = kwargs["n"]
            result = self.__data.draw(st.binary(min_size=n, max_size=n))
        else:
            raise NotImplementedError(method)

        new_state = RandomState()
        self.__state.next_states[key] = (result, new_state)
        self.__state = new_state

        return self.__convert_result(method, kwargs, result)