コード例 #1
0
def all_types(draw):
    return draw(
        one_of(
            text(),
            integers(),
            none(),
            booleans(),
            floats(),
            tuples(),
            times(),
            uuids(),
            lists(integers()),
            dictionaries(text(), text()),
        ))
コード例 #2
0
def array_dtypes(
    subtype_strategy=scalar_dtypes(),  # type: st.SearchStrategy[np.dtype]
    min_size=1,  # type: int
    max_size=5,  # type: int
    allow_subarrays=False,  # type: bool
):
    # type: (...) -> st.SearchStrategy[np.dtype]
    """Return a strategy for generating array (compound) dtypes, with members
    drawn from the given subtype strategy."""
    order_check("size", 0, min_size, max_size)
    # Field names must be native strings and the empty string is weird; see #1963.
    if PY2:
        field_names = st.binary(min_size=1)
    else:
        field_names = st.text(min_size=1)
    elements = st.tuples(field_names, subtype_strategy)
    if allow_subarrays:
        elements |= st.tuples(
            field_names, subtype_strategy, array_shapes(max_dims=2, max_side=2)
        )
    return st.lists(
        elements=elements,
        min_size=min_size,
        max_size=max_size,
        unique_by=lambda d: d[0],
    )
コード例 #3
0
def from_dtype(dtype):
    # type: (np.dtype) -> st.SearchStrategy[Any]
    """Creates a strategy which can generate any value of the given dtype."""
    check_type(np.dtype, dtype, "dtype")
    # Compound datatypes, eg 'f4,f4,f4'
    if dtype.names is not None:
        # mapping np.void.type over a strategy is nonsense, so return now.
        return st.tuples(*[from_dtype(dtype.fields[name][0]) for name in dtype.names])

    # Subarray datatypes, eg '(2, 3)i4'
    if dtype.subdtype is not None:
        subtype, shape = dtype.subdtype
        return arrays(subtype, shape)

    # Scalar datatypes
    if dtype.kind == u"b":
        result = st.booleans()  # type: SearchStrategy[Any]
    elif dtype.kind == u"f":
        if dtype.itemsize == 2:
            result = st.floats(width=16)
        elif dtype.itemsize == 4:
            result = st.floats(width=32)
        else:
            result = st.floats()
    elif dtype.kind == u"c":
        if dtype.itemsize == 8:
            float32 = st.floats(width=32)
            result = st.builds(complex, float32, float32)
        else:
            result = st.complex_numbers()
    elif dtype.kind in (u"S", u"a"):
        # Numpy strings are null-terminated; only allow round-trippable values.
        # `itemsize == 0` means 'fixed length determined at array creation'
        result = st.binary(max_size=dtype.itemsize or None).filter(
            lambda b: b[-1:] != b"\0"
        )
    elif dtype.kind == u"u":
        result = st.integers(min_value=0, max_value=2 ** (8 * dtype.itemsize) - 1)
    elif dtype.kind == u"i":
        overflow = 2 ** (8 * dtype.itemsize - 1)
        result = st.integers(min_value=-overflow, max_value=overflow - 1)
    elif dtype.kind == u"U":
        # Encoded in UTF-32 (four bytes/codepoint) and null-terminated
        result = st.text(max_size=(dtype.itemsize or 0) // 4 or None).filter(
            lambda b: b[-1:] != u"\0"
        )
    elif dtype.kind in (u"m", u"M"):
        if "[" in dtype.str:
            res = st.just(dtype.str.split("[")[-1][:-1])
        else:
            res = st.sampled_from(TIME_RESOLUTIONS)
        result = st.builds(dtype.type, st.integers(-(2 ** 63), 2 ** 63 - 1), res)
    else:
        raise InvalidArgument(u"No strategy inference for {}".format(dtype))
    return result.map(dtype.type)
コード例 #4
0
ファイル: provisional.py プロジェクト: MarkAgimba/Mtribune
def domains():
    """A strategy for :rfc:`1035` fully qualified domain names."""
    atoms = st.text(
        string.ascii_letters + "0123456789-", min_size=1, max_size=63
    ).filter(lambda s: "-" not in s[0] + s[-1])
    return st.builds(
        lambda x, y: ".".join(x + [y]),
        st.lists(atoms, min_size=1),
        # TODO: be more devious about top-level domains
        st.sampled_from(["com", "net", "org", "biz", "info"]),
    ).filter(lambda url: len(url) <= 255)
コード例 #5
0
def urls():
    # type: () -> SearchStrategy[Text]
    """A strategy for :rfc:`3986`, generating http/https URLs."""
    def url_encode(s):
        return "".join(c if c in URL_SAFE_CHARACTERS else "%%%02X" % ord(c)
                       for c in s)

    schemes = st.sampled_from(["http", "https"])
    ports = st.integers(min_value=0, max_value=2**16 - 1).map(":{}".format)
    paths = st.lists(st.text(string.printable).map(url_encode)).map("/".join)

    return st.builds(u"{}://{}{}/{}".format, schemes, domains(),
                     st.just(u"") | ports, paths)
コード例 #6
0
ファイル: provisional.py プロジェクト: MarkAgimba/Mtribune
def urls():
    """A strategy for :rfc:`3986`, generating http/https URLs."""

    def url_encode(s):
        safe_chars = set(string.ascii_letters + string.digits + "$-_.+!*'(),")
        return "".join(c if c in safe_chars else "%%%02X" % ord(c) for c in s)

    schemes = st.sampled_from(["http", "https"])
    ports = st.integers(min_value=0, max_value=2 ** 16 - 1).map(":{}".format)
    paths = st.lists(st.text(string.printable).map(url_encode)).map(
        lambda path: "/".join([""] + path)
    )

    return st.builds(
        "{}://{}{}{}".format, schemes, domains(), st.one_of(st.just(""), ports), paths
    )
コード例 #7
0
def array_dtypes(
        subtype_strategy=scalar_dtypes(),  # type: st.SearchStrategy[np.dtype]
        min_size=1,  # type: int
        max_size=5,  # type: int
        allow_subarrays=False,  # type: bool
):
    # type: (...) -> st.SearchStrategy[np.dtype]
    """Return a strategy for generating array (compound) dtypes, with members
    drawn from the given subtype strategy."""
    order_check("size", 0, min_size, max_size)
    native_strings = st.text()  # type: SearchStrategy[Any]
    if text_type is not str:  # pragma: no cover
        native_strings = st.binary()
    elements = st.tuples(native_strings, subtype_strategy)
    if allow_subarrays:
        elements |= st.tuples(native_strings, subtype_strategy,
                              array_shapes(max_dims=2, max_side=2))
    return st.lists(
        elements=elements,
        min_size=min_size,
        max_size=max_size,
        unique_by=lambda d: d[0],
    )