當前位置: 首頁>>代碼示例>>Python>>正文


Python strategies.from_regex方法代碼示例

本文整理匯總了Python中hypothesis.strategies.from_regex方法的典型用法代碼示例。如果您正苦於以下問題:Python strategies.from_regex方法的具體用法?Python strategies.from_regex怎麽用?Python strategies.from_regex使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在hypothesis.strategies的用法示例。


在下文中一共展示了strategies.from_regex方法的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: regex_patterns

# 需要導入模塊: from hypothesis import strategies [as 別名]
# 或者: from hypothesis.strategies import from_regex [as 別名]
def regex_patterns(draw: Any) -> str:
    """Return a recursive strategy for simple regular expression patterns."""
    fragments = st.one_of(
        st.just("."),
        st.from_regex(r"\[\^?[A-Za-z0-9]+\]"),
        REGEX_PATTERNS.map("{}+".format),
        REGEX_PATTERNS.map("{}?".format),
        REGEX_PATTERNS.map("{}*".format),
    )
    result = draw(st.lists(fragments, min_size=1, max_size=3).map("".join))
    assert isinstance(result, str)
    try:
        re.compile(result)
    except re.error:
        assume(False)
    return result 
開發者ID:Zac-HD,項目名稱:hypothesis-jsonschema,代碼行數:18,代碼來源:_from_schema.py

示例2: test_custom_strategies

# 需要導入模塊: from hypothesis import strategies [as 別名]
# 或者: from hypothesis.strategies import from_regex [as 別名]
def test_custom_strategies(swagger_20):
    register_string_format("even_4_digits", strategies.from_regex(r"\A[0-9]{4}\Z").filter(lambda x: int(x) % 2 == 0))
    endpoint = make_endpoint(
        swagger_20,
        query={
            "required": ["id"],
            "type": "object",
            "additionalProperties": False,
            "properties": {"id": {"type": "string", "format": "even_4_digits"}},
        },
    )
    result = get_case_strategy(endpoint).example()
    assert len(result.query["id"]) == 4
    assert int(result.query["id"]) % 2 == 0 
開發者ID:kiwicom,項目名稱:schemathesis,代碼行數:16,代碼來源:test_hypothesis.py

示例3: dns_labels

# 需要導入模塊: from hypothesis import strategies [as 別名]
# 或者: from hypothesis.strategies import from_regex [as 別名]
def dns_labels():
    """
    Strategy for generating limited charset DNS labels.
    """
    # This is too limited, but whatever
    return s.from_regex(u'\\A[a-z]{3}[a-z0-9-]{0,21}[a-z]\\Z') 
開發者ID:twisted,項目名稱:txacme,代碼行數:8,代碼來源:strategies.py

示例4: from_grammar

# 需要導入模塊: from hypothesis import strategies [as 別名]
# 或者: from hypothesis.strategies import from_regex [as 別名]
def from_grammar() -> st.SearchStrategy[str]:
    """
    Generate syntactically-valid Python source code based on the grammar.
    """
    grammar = get_lark_grammar()
    explicit_strategies = dict(
        _INDENT=st.just(" " * 4),
        _DEDENT=st.just(""),
        NAME=st.from_regex(r"[a-z_A-Z]+", fullmatch=True).filter(str.isidentifier),
    )
    return GrammarStrategy(grammar, "module", explicit_strategies)


# Avoid examples with *only* single or double quote docstrings
# because they trigger a trivial compiler bug 
開發者ID:vyperlang,項目名稱:vyper,代碼行數:17,代碼來源:test_grammar.py

示例5: identifiers

# 需要導入模塊: from hypothesis import strategies [as 別名]
# 或者: from hypothesis.strategies import from_regex [as 別名]
def identifiers(allow_private=True, exclude=None):
    """
    Valid Python identifiers.
    """
    regex = IDENTIFIER_RE if allow_private else PUBLIC_IDENTIFIER_RE
    strategy = st.from_regex(regex, fullmatch=True).filter(lambda x: not iskeyword(x))
    if exclude:
        exclude = set(exclude)
        strategy = strategy.filter(lambda x: x not in exclude)
    return strategy


# noinspection PyShadowingNames 
開發者ID:fabiommendes,項目名稱:sidekick,代碼行數:15,代碼來源:base.py

示例6: rfc3339

# 需要導入模塊: from hypothesis import strategies [as 別名]
# 或者: from hypothesis.strategies import from_regex [as 別名]
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) 
開發者ID:Zac-HD,項目名稱:hypothesis-jsonschema,代碼行數:39,代碼來源:_from_schema.py

示例7: relative_json_pointers

# 需要導入模塊: from hypothesis import strategies [as 別名]
# 或者: from hypothesis.strategies import from_regex [as 別名]
def relative_json_pointers() -> st.SearchStrategy[str]:
    """Return a strategy for strings in relative-json-pointer format."""
    return st.builds(
        operator.add,
        st.from_regex(r"0|[1-9][0-9]*", fullmatch=True),
        st.just("#") | json_pointers(),
    )


# Via the `webcolors` package, to match the logic `jsonschema`
# uses to check it's (non-standard?) "color" format. 
開發者ID:Zac-HD,項目名稱:hypothesis-jsonschema,代碼行數:13,代碼來源:_from_schema.py

示例8: string_schema

# 需要導入模塊: from hypothesis import strategies [as 別名]
# 或者: from hypothesis.strategies import from_regex [as 別名]
def string_schema(schema: dict) -> st.SearchStrategy[str]:
    """Handle schemata for strings."""
    # also https://json-schema.org/latest/json-schema-validation.html#rfc.section.7
    min_size = schema.get("minLength", 0)
    max_size = schema.get("maxLength")
    strategy = st.text(min_size=min_size, max_size=max_size)
    if schema.get("format") in STRING_FORMATS:
        # Unknown "format" specifiers should be ignored for validation.
        # See https://json-schema.org/latest/json-schema-validation.html#format
        strategy = STRING_FORMATS[schema["format"]]
        if "pattern" in schema:
            # This isn't really supported, but we'll do our best.
            strategy = strategy.filter(
                lambda s: re.search(schema["pattern"], string=s) is not None
            )
    elif "pattern" in schema:
        try:
            re.compile(schema["pattern"])
            strategy = st.from_regex(schema["pattern"])
        except re.error:
            # Patterns that are invalid in Python, or just malformed
            return st.nothing()
    # If we have size bounds but we're generating strings from a regex or pattern,
    # apply a filter to ensure our size bounds are respected.
    if ("format" in schema or "pattern" in schema) and (
        min_size != 0 or max_size is not None
    ):
        max_size = math.inf if max_size is None else max_size
        strategy = strategy.filter(lambda s: min_size <= len(s) <= max_size)
    return strategy 
開發者ID:Zac-HD,項目名稱:hypothesis-jsonschema,代碼行數:32,代碼來源:_from_schema.py


注:本文中的hypothesis.strategies.from_regex方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。