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


Python strategies.text方法代码示例

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


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

示例1: _fuzz_string

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import text [as 别名]
def _fuzz_string(
    parameter: Dict[str, Any],
    required: bool = False,
) -> SearchStrategy:
    if parameter.get('in', None) == 'header':
        return st.text(
            # According to RFC 7230, non-ascii letters are deprecated, and there's
            # no telling what the server will do if they are sent. Since the intent
            # is not to break the server, but to send valid requests instead, we're
            # just going to limit it accordingly.
            alphabet=string.ascii_letters,
        )

    # TODO: Handle a bunch of swagger string formats.
    # https://swagger.io/docs/specification/data-models/data-types/#string
    kwargs = {}                                     # type: Dict[str, Any]

    if parameter.get('required', required):
        kwargs['min_size'] = 1
    if not get_settings().unicode_enabled:
        kwargs['alphabet'] = string.printable

    return st.text(**kwargs) 
开发者ID:Yelp,项目名称:fuzz-lightyear,代码行数:25,代码来源:fuzzer.py

示例2: test_invalid_endpoint

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import text [as 别名]
def test_invalid_endpoint(cli, cli_args, workers):
    # When the app's schema contains errors
    # For example if its type is "int" but should be "integer"
    # And schema validation is disabled
    result = cli.run(*cli_args, f"--workers={workers}", "--validate-schema=false")
    # Then the whole Schemathesis run should fail
    assert result.exit_code == ExitCode.TESTS_FAILED, result.stdout
    # And standard Hypothesis error should not appear in the output
    assert "You can add @seed" not in result.stdout
    # And this endpoint should be marked as errored in the progress line
    lines = result.stdout.split("\n")
    if workers == 1:
        assert lines[10].startswith("POST /api/invalid E")
    else:
        assert lines[10] == "E"
    assert " POST: /api/invalid " in lines[13]
    # There shouldn't be a section end immediately after section start - there should be some error text
    # An internal error happened during a test run
    # Error: AssertionError
    assert not lines[14].startswith("=") 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:22,代码来源:test_commands.py

示例3: stanza_line

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import text [as 别名]
def stanza_line(draw):
    "Generate an extended textual header stanze non-header line."

    alphabet = list(PRINTABLE_ASCII_ALPHABET)
    # Remove the separator character
    alphabet.remove('=')

    key = draw(text(alphabet=alphabet,
                    min_size=1,
                    max_size=(CARD_LENGTH - 3) // 2))

    value = draw(text(alphabet=alphabet,
                      min_size=1,
                      max_size=(CARD_LENGTH - 3) // 2))

    line = '{} = {}'.format(key, value)
    assert len(line) <= CARD_LENGTH

    padded_line = '{:{width}}'.format(line, width=CARD_LENGTH)
    assert len(padded_line) == CARD_LENGTH

    return padded_line 
开发者ID:sixty-north,项目名称:segpy,代码行数:24,代码来源:dataset_strategy.py

示例4: lineage_st

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import text [as 别名]
def lineage_st(draw):
    """Hypothesis strategy for generated lineage strings."""
    first = draw(st.text(
        alphabet = list('abcdef0123456789'),
        min_size=8,
        max_size=8))
    second = draw(st.text(
        alphabet = list('abcdef0123456789'),
        min_size=4,
        max_size=4))
    third = draw(st.text(
        alphabet = list('abcdef0123456789'),
        min_size=4,
        max_size=4))
    fourth = draw(st.text(
        alphabet = list('abcdef0123456789'),
        min_size=4,
        max_size=4))
    fifth = draw(st.text(
        alphabet = list('abcdef0123456789'),
        min_size=12,
        max_size=12))

    return '{}-{}-{}-{}-{}'.format(first, second, third, fourth, fifth) 
开发者ID:mantl,项目名称:terraform.py,代码行数:26,代码来源:hypothesis_state.py

示例5: s3_bucket_name_st

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import text [as 别名]
def s3_bucket_name_st(draw):
    """Hypothesis strategy for s3 bucket names.
    
    http://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-s3-bucket-naming-requirements.html
    """
    char1 = draw(st.text(
        alphabet = list(ascii_lowercase + digits),
        min_size=1,
        max_size=1))
    middle = draw(st.text(
        alphabet = list(ascii_lowercase + digits + '.-'),
        min_size = 4,
        max_size = 61).filter(lambda x: '..' not in x and '.-' not in x and '.-' not in x))
    endchar = draw(st.text(
        alphabet = list(ascii_lowercase + digits + '.'),
        min_size = 1,
        max_size = 1))

    return '{}{}{}'.format(char1, middle, endchar) 
开发者ID:mantl,项目名称:terraform.py,代码行数:21,代码来源:hypothesis_state.py

示例6: remote_init_st

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import text [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

示例7: test_corpus_add_doc

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import text [as 别名]
def test_corpus_add_doc():
    c = Corpus()
    with pytest.raises(ValueError):
        c.add_doc('', 'x')
    with pytest.raises(ValueError):
        c.add_doc(123, 'x')
    with pytest.raises(ValueError):
        c.add_doc('d1', None)

    c.add_doc('d1', 'd1 text')
    with pytest.raises(ValueError):
        c.add_doc('d1', 'd1 text')

    c.add_doc('d2', '')

    assert set(c.keys()) == {'d1', 'd2'} 
开发者ID:WZBSocialScienceCenter,项目名称:tmtoolkit,代码行数:18,代码来源:test_corpus.py

示例8: test_corpus_from_tabular

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import text [as 别名]
def test_corpus_from_tabular():
    for ext in ('csv', 'xlsx'):
        c = Corpus.from_tabular('tests/data/100NewsArticles.' + ext, 'article_id', 'text')
        assert len(c.docs) == 100
        assert all(dl.startswith('100NewsArticles') for dl in c.doc_labels)

        c.add_tabular('tests/data/100NewsArticles.' + ext, 'article_id', 'text', prepend_columns=['title', 'subtitle'],
                      doc_label_fmt='added-{id}')
        assert len(c.docs) == 200

        n_added = 0
        for dl, nchars in c.doc_lengths.items():
            if dl.startswith('added'):
                n_added += 1
                _, doc_id = dl.split('-')
                assert nchars >= c.doc_lengths['100NewsArticles-' + doc_id]

        assert n_added == 100

    assert len(Corpus.from_tabular('tests/data/bt18_speeches_sample.csv', 0, 2)) == 1000 
开发者ID:WZBSocialScienceCenter,项目名称:tmtoolkit,代码行数:22,代码来源:test_corpus.py

示例9: _strategy_2d_array

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import text [as 别名]
def _strategy_2d_array(dtype, minval=0, maxval=None, **kwargs):
    if 'min_side' in kwargs:
        min_side = kwargs.pop('min_side')
    else:
        min_side = 1

    if 'max_side' in kwargs:
        max_side = kwargs.pop('max_side')
    else:
        max_side = None

    if dtype is np.int:
        elems = st.integers(minval, maxval, **kwargs)
    elif dtype is np.float:
        elems = st.floats(minval, maxval, **kwargs)
    elif dtype is np.str:
        elems = st.text(min_size=minval, max_size=maxval, **kwargs)
    else:
        raise ValueError('no elements strategy for dtype', dtype)

    return arrays(dtype, array_shapes(2, 2, min_side, max_side), elements=elems) 
开发者ID:WZBSocialScienceCenter,项目名称:tmtoolkit,代码行数:23,代码来源:_testtools.py

示例10: from_schema

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import text [as 别名]
def from_schema(schema):
    """Returns a strategy for objects that match the given schema."""
    check_schema(schema)
    # TODO: actually handle constraints on number/string/array schemas
    return dict(
        null=st.none(),
        bool=st.booleans(),
        number=st.floats(allow_nan=False),
        string=st.text(),
        array=st.lists(st.nothing()),
    )[schema["type"]]


# `@st.composite` is one way to write this - another would be to define a
# bare function, and `return st.one_of(st.none(), st.booleans(), ...)` so
# each strategy can be defined individually.  Use whichever seems more
# natural to you - the important thing in tests is usually readability! 
开发者ID:Zac-HD,项目名称:escape-from-automanual-testing,代码行数:19,代码来源:tough-bonus-problems.py

示例11: chromeResponseReceived

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import text [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

示例12: generate_dictionary_with_fixed_tokens

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import text [as 别名]
def generate_dictionary_with_fixed_tokens(draw):
    """
    Builds random nested dictionary structure which is then used as JSON to
    mask two fixed "token" keys.

    Structure is based on TEST_JSON sample fixture defined above.
    """
    base = draw(
        st.fixed_dictionaries({'token': st.text(printable, min_size=10)})
    )

    optional = draw(
        st.nothing() | st.dictionaries(
            st.text(ascii_letters, min_size=1),
            st.floats() | st.integers() | st.text(printable) | st.booleans()
            | st.nothing(),
            min_size=10,
            max_size=50
        )
    )

    return {**base, **optional} 
开发者ID:telepresenceio,项目名称:telepresence,代码行数:24,代码来源:test_output_mask.py

示例13: sig_pair

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import text [as 别名]
def sig_pair():
    def separate(D):
        signatures, signatures_ref = {}, {}
        for kk in D:
            if len(D[kk]) == 1:
                v_ref, = D[kk]
                signatures_ref[kk] = np.asarray(v_ref)
            elif len(D[kk]) == 2:
                v, v_ref = D[kk]
                signatures[kk] = np.asarray(v)
                signatures_ref[kk] = np.asarray(v_ref)
            else:
                assert False
        return signatures, signatures_ref

    sig_dict = dictionaries(text(), tuples(bsigs()) | tuples(bsigs(), bsigs()))
    S = sig_dict.map(separate)
    return S 
开发者ID:uber,项目名称:bayesmark,代码行数:20,代码来源:signatures_test.py

示例14: simple_attrs_with_metadata

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import text [as 别名]
def simple_attrs_with_metadata(draw):
    """
    Create a simple attribute with arbitrary metadata.
    """
    c_attr = draw(simple_attrs)
    keys = st.booleans() | st.binary() | st.integers() | st.text()
    vals = st.booleans() | st.binary() | st.integers() | st.text()
    metadata = draw(
        st.dictionaries(keys=keys, values=vals, min_size=1, max_size=3)
    )

    return attr.ib(
        default=c_attr._default,
        validator=c_attr._validator,
        repr=c_attr.repr,
        eq=c_attr.eq,
        order=c_attr.order,
        hash=c_attr.hash,
        init=c_attr.init,
        metadata=metadata,
        type=None,
        converter=c_attr.converter,
    ) 
开发者ID:python-attrs,项目名称:attrs,代码行数:25,代码来源:strategies.py

示例15: urls

# 需要导入模块: from hypothesis import strategies [as 别名]
# 或者: from hypothesis.strategies import text [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


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