Python源码示例:hypothesis.strategies.text()
示例1
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)
示例2
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("=")
示例3
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
示例4
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)
示例5
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)
示例6
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
示例7
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'}
示例8
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
示例9
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)
示例10
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!
示例11
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,
})
})
示例12
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}
示例13
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
示例14
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,
)
示例15
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),
)
示例16
def possibly_commented(strategy):
@st.composite
def _strategy(draw):
value = draw(strategy)
add_trailing_comment = False
if isinstance(value, (list, tuple, set)):
add_trailing_comment = draw(st.booleans())
add_comment = draw(st.booleans())
if add_trailing_comment:
comment_text = draw(st.text(alphabet='abcdefghijklmnopqrstuvwxyz #\\\'"'))
value = trailing_comment(value, comment_text)
if add_comment:
comment_text = draw(st.text(alphabet='abcdefghijklmnopqrstuvwxyz #\\\'"'))
value = comment(value, comment_text)
return value
return _strategy()
示例17
def string_and_substring(draw):
x = draw(text(min_size=2, alphabet=string.printable))
i = draw(integers(min_value=0, max_value=len(x)-2))
j = draw(integers(min_value=i+1, max_value=len(x)-1))
return (x, x[i:j])
示例18
def string_and_not_substring(draw):
x = draw(text(min_size=2, alphabet=string.printable))
i = draw(integers(min_value=1, max_value=len(x)-1))
y = ''.join(sample(x, i))
assume(x.find(y) == -1)
return (x, y)
示例19
def valid_text(
min_size=None, # type: int
average_size=None, # type: int
max_size=None, # type: int
): # type: (...) -> st.S
"""
Helper strategy for valid PayFast field value strings.
"""
return (st.text(min_size=min_size, average_size=average_size, max_size=max_size)
# PayFast seems to categorically refuse (with a low-level HTTP 403 Forbidden)
# requests with values that contain nulls, so avoid generating these.
.filter(lambda s: '\0' not in s))
示例20
def test_set_pattern_long(hist, message_mock, caplog, pattern):
hist.insert({'url': 'example.com/foo', 'title': 'title1', 'last_atime': 1})
cat = histcategory.HistoryCategory()
with caplog.at_level(logging.ERROR):
cat.set_pattern(pattern)
msg = message_mock.getmsg(usertypes.MessageLevel.error)
assert msg.text.startswith("Error with SQL query:")
示例21
def test_str():
text = 'https://www.example.com/'
pat = urlmatch.UrlPattern(text)
assert str(pat) == text
示例22
def __init__(self, parent=None):
super().__init__(parent)
self.text = None
示例23
def keyPressEvent(self, e):
self.text = e.text()
self.got_text.emit()
示例24
def test_text(self, qt_key, upper):
"""Test KeyInfo.text() with all possible keys.
See key_data.py for inputs and expected values.
"""
modifiers = Qt.ShiftModifier if upper else Qt.KeyboardModifiers()
info = keyutils.KeyInfo(qt_key.member, modifiers=modifiers)
expected = qt_key.uppertext if upper else qt_key.text
assert info.text() == expected
示例25
def test_surrogates(key, modifiers, text, expected):
evt = QKeyEvent(QKeyEvent.KeyPress, key, modifiers, text)
assert str(keyutils.KeyInfo.from_event(evt)) == expected
示例26
def test_append_event(self, old, key, modifiers, text, expected):
seq = keyutils.KeySequence.parse(old)
event = QKeyEvent(QKeyEvent.KeyPress, key, modifiers, text)
new = seq.append_event(event)
assert new == keyutils.KeySequence.parse(expected)
示例27
def test_key_info_to_event():
info = keyutils.KeyInfo(Qt.Key_A, Qt.ShiftModifier)
ev = info.to_event()
assert ev.key() == Qt.Key_A
assert ev.modifiers() == Qt.ShiftModifier
assert ev.text() == 'A'
示例28
def test_hypothesis_text(self, klass, val):
typ = klass()
text = json.dumps(val)
try:
converted = typ.from_str(text)
except configexc.ValidationError:
pass
else:
expected = '' if not val else text
assert typ.to_str(converted) == expected
示例29
def test_hypothesis_text(self, strtype, klass, val):
typ = klass(strtype)
text = json.dumps(val)
try:
typ.to_str(typ.from_str(text))
except configexc.ValidationError:
pass
示例30
def test_hypothesis_text(self, klass, val):
text = json.dumps(val)
klass().from_str(text)
# Can't check for string equality with to_str here, as we can get 1.0
# for 1.