本文整理汇总了Python中hypothesis.internal.conjecture.data.TestData类的典型用法代码示例。如果您正苦于以下问题:Python TestData类的具体用法?Python TestData怎么用?Python TestData使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TestData类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_distribution_is_correctly_translated
def test_distribution_is_correctly_translated(inter, rnd):
assert inter == sorted(inter)
lower, c1, c2, upper = inter
d = TestData(
draw_bytes=lambda data, n, distribution: distribution(rnd, n),
max_length=10 ** 6
)
assert d.draw(interval(lower, upper, c1, lambda r: c2)) == c2
assert d.draw(interval(lower, upper, c2, lambda r: c1)) == c1
示例2: incorporate_new_buffer
def incorporate_new_buffer(self, buffer):
if buffer in self.seen:
return False
assert self.last_data.status == Status.INTERESTING
if (
self.settings.timeout > 0 and
time.time() >= self.start_time + self.settings.timeout
):
raise RunIsComplete()
self.examples_considered += 1
buffer = buffer[:self.last_data.index]
if sort_key(buffer) >= sort_key(self.last_data.buffer):
return False
assert sort_key(buffer) <= sort_key(self.last_data.buffer)
data = TestData.for_buffer(buffer)
self.test_function(data)
data.freeze()
self.note_for_corpus(data)
if self.consider_new_test_data(data):
self.shrinks += 1
self.last_data = data
if self.shrinks >= self.settings.max_shrinks:
raise RunIsComplete()
self.last_data = data
self.changed += 1
return True
return False
示例3: test_draw_past_end_sets_overflow
def test_draw_past_end_sets_overflow():
x = TestData.for_buffer(bytes(5))
with pytest.raises(StopTest) as e:
x.draw_bytes(6)
assert e.value.testcounter == x.testcounter
assert x.frozen
assert x.status == Status.OVERRUN
示例4: new_buffer
def new_buffer(self):
self.last_data = TestData(
max_length=self.settings.buffer_size,
draw_bytes=lambda data, n, distribution:
distribution(self.random, n)
)
self.test_function(self.last_data)
self.last_data.freeze()
示例5: test_variadic_draw
def test_variadic_draw():
def draw_list(data):
result = []
while True:
data.start_example()
d = data.draw_bytes(1)[0] & 7
if d:
result.append(data.draw_bytes(d))
data.stop_example()
if not d:
break
return result
@run_to_buffer
def b(data):
if any(all(d) for d in draw_list(data)):
data.mark_interesting()
l = draw_list(TestData.for_buffer(b))
assert len(l) == 1
assert len(l[0]) == 1
示例6: test_can_draw_zero_bytes
def test_can_draw_zero_bytes():
x = TestData.for_buffer(b'')
for _ in range(10):
assert x.draw_bytes(0) == b''
示例7: test_can_double_freeze
def test_can_double_freeze():
x = TestData.for_buffer(b'hi')
x.freeze()
assert x.frozen
x.freeze()
assert x.frozen
示例8: test_cannot_draw_after_freeze
def test_cannot_draw_after_freeze():
x = TestData.for_buffer(b'hi')
x.draw_bytes(1)
x.freeze()
with pytest.raises(Frozen):
x.draw_bytes(1)
示例9: test_buffer_draws_as_self
def test_buffer_draws_as_self(buf):
x = TestData.for_buffer(buf)
assert x.draw_bytes(len(buf), bogus_dist) == buf
示例10: test_closes_interval_on_error_in_strategy
def test_closes_interval_on_error_in_strategy():
x = TestData.for_buffer(b'hi')
with pytest.raises(ValueError):
x.draw(BoomStrategy())
x.freeze()
assert len(x.intervals) == 1
示例11: test_can_mark_interesting
def test_can_mark_interesting():
x = TestData.for_buffer(bytes())
with pytest.raises(StopTest):
x.mark_interesting()
assert x.frozen
assert x.status == Status.INTERESTING
示例12: TestRunner
class TestRunner(object):
def __init__(
self, test_function, settings=None, random=None,
database_key=None,
):
self._test_function = test_function
self.settings = settings or Settings()
self.last_data = None
self.changed = 0
self.shrinks = 0
self.examples_considered = 0
self.iterations = 0
self.valid_examples = 0
self.start_time = time.time()
self.random = random or Random(getrandbits(128))
self.database_key = database_key
self.seen = set()
def new_buffer(self):
self.last_data = TestData(
max_length=self.settings.buffer_size,
draw_bytes=lambda data, n, distribution:
distribution(self.random, n)
)
self.test_function(self.last_data)
self.last_data.freeze()
self.note_for_corpus(self.last_data)
def test_function(self, data):
self.iterations += 1
try:
self._test_function(data)
data.freeze()
except StopTest as e:
if e.testcounter != data.testcounter:
self.save_buffer(data.buffer)
raise e
except:
self.save_buffer(data.buffer)
raise
if (
data.status == Status.INTERESTING and (
self.last_data is None or
data.buffer != self.last_data.buffer
)
):
self.debug_data(data)
if data.status >= Status.VALID:
self.valid_examples += 1
def consider_new_test_data(self, data):
# Transition rules:
# 1. Transition cannot decrease the status
# 2. Any transition which increases the status is valid
# 3. If the previous status was interesting, only shrinking
# transitions are allowed.
key = hbytes(data.buffer)
if key in self.seen:
return False
self.seen.add(key)
if data.buffer == self.last_data.buffer:
return False
if self.last_data.status < data.status:
return True
if self.last_data.status > data.status:
return False
if data.status == Status.INVALID:
return data.index >= self.last_data.index
if data.status == Status.OVERRUN:
return data.overdraw <= self.last_data.overdraw
if data.status == Status.INTERESTING:
assert len(data.buffer) <= len(self.last_data.buffer)
if len(data.buffer) == len(self.last_data.buffer):
assert data.buffer < self.last_data.buffer
return True
return True
def save_buffer(self, buffer):
if (
self.settings.database is not None and
self.database_key is not None and
Phase.reuse in self.settings.phases
):
self.settings.database.save(
self.database_key, hbytes(buffer)
)
def note_for_corpus(self, data):
if data.status == Status.INTERESTING:
self.save_buffer(data.buffer)
def debug(self, message):
with self.settings:
debug_report(message)
def debug_data(self, data):
self.debug(u'%d bytes %s -> %s, %s' % (
data.index,
unicode_safe_repr(list(data.buffer[:data.index])),
#.........这里部分代码省略.........
示例13: _run
def _run(self):
self.last_data = None
mutations = 0
start_time = time.time()
if (
self.settings.database is not None and
self.database_key is not None
):
corpus = sorted(
self.settings.database.fetch(self.database_key),
key=lambda d: (len(d), d)
)
for existing in corpus:
if self.valid_examples >= self.settings.max_examples:
return
if self.iterations >= max(
self.settings.max_iterations, self.settings.max_examples
):
return
data = TestData.for_buffer(existing)
self.test_function(data)
data.freeze()
self.last_data = data
if data.status < Status.VALID:
self.settings.database.delete(
self.database_key, existing)
elif data.status == Status.VALID:
# Incremental garbage collection! we store a lot of
# examples in the DB as we shrink: Those that stay
# interesting get kept, those that become invalid get
# dropped, but those that are merely valid gradually go
# away over time.
if self.random.randint(0, 2) == 0:
self.settings.database.delete(
self.database_key, existing)
else:
assert data.status == Status.INTERESTING
self.last_data = data
break
if Phase.generate in self.settings.phases:
if (
self.last_data is None or
self.last_data.status < Status.INTERESTING
):
self.new_buffer()
mutator = self._new_mutator()
while self.last_data.status != Status.INTERESTING:
if self.valid_examples >= self.settings.max_examples:
return
if self.iterations >= max(
self.settings.max_iterations, self.settings.max_examples
):
return
if (
self.settings.timeout > 0 and
time.time() >= start_time + self.settings.timeout
):
return
if mutations >= self.settings.max_mutations:
mutations = 0
self.new_buffer()
mutator = self._new_mutator()
else:
data = TestData(
draw_bytes=mutator,
max_length=self.settings.buffer_size
)
self.test_function(data)
data.freeze()
self.note_for_corpus(data)
prev_data = self.last_data
if self.consider_new_test_data(data):
self.last_data = data
if data.status > prev_data.status:
mutations = 0
else:
mutator = self._new_mutator()
mutations += 1
data = self.last_data
if data is None:
return
assert isinstance(data.output, text_type)
if self.settings.max_shrinks <= 0:
return
if Phase.shrink not in self.settings.phases:
return
if not self.last_data.buffer:
return
data = TestData.for_buffer(self.last_data.buffer)
self.test_function(data)
if data.status != Status.INTERESTING:
#.........这里部分代码省略.........
示例14: wrapped_test
def wrapped_test(*arguments, **kwargs):
settings = wrapped_test._hypothesis_internal_use_settings
if wrapped_test._hypothesis_internal_use_seed is not None:
random = Random(
wrapped_test._hypothesis_internal_use_seed)
elif settings.derandomize:
random = Random(function_digest(test))
else:
random = new_random()
import hypothesis.strategies as sd
selfy = None
arguments, kwargs = convert_positional_arguments(
wrapped_test, arguments, kwargs)
# If the test function is a method of some kind, the bound object
# will be the first named argument if there are any, otherwise the
# first vararg (if any).
if argspec.args:
selfy = kwargs.get(argspec.args[0])
elif arguments:
selfy = arguments[0]
test_runner = new_style_executor(selfy)
for example in reversed(getattr(
wrapped_test, 'hypothesis_explicit_examples', ()
)):
if example.args:
if len(example.args) > len(original_argspec.args):
raise InvalidArgument(
'example has too many arguments for test. '
'Expected at most %d but got %d' % (
len(original_argspec.args), len(example.args)))
example_kwargs = dict(zip(
original_argspec.args[-len(example.args):],
example.args
))
else:
example_kwargs = example.kwargs
example_kwargs.update(kwargs)
# Note: Test may mutate arguments and we can't rerun explicit
# examples, so we have to calculate the failure message at this
# point rather than than later.
message_on_failure = 'Falsifying example: %s(%s)' % (
test.__name__, arg_string(test, arguments, example_kwargs)
)
try:
with BuildContext() as b:
test_runner(
None,
lambda data: test(*arguments, **example_kwargs)
)
except BaseException:
report(message_on_failure)
for n in b.notes:
report(n)
raise
if settings.max_examples <= 0:
return
arguments = tuple(arguments)
given_specifier = sd.tuples(
sd.just(arguments),
sd.fixed_dictionaries(generator_kwargs).map(
lambda args: dict(args, **kwargs)
)
)
def fail_health_check(message):
message += (
'\nSee http://hypothesis.readthedocs.org/en/latest/health'
'checks.html for more information about this.'
)
raise FailedHealthCheck(message)
search_strategy = given_specifier
search_strategy.validate()
perform_health_check = settings.perform_health_check
perform_health_check &= Settings.default.perform_health_check
from hypothesis.internal.conjecture.data import TestData, Status, \
StopTest
if perform_health_check:
initial_state = getglobalrandomstate()
health_check_random = Random(random.getrandbits(128))
# We "pre warm" the health check with one draw to give it some
# time to calculate any cached data. This prevents the case
# where the first draw of the health check takes ages because
# of loading unicode data the first time.
data = TestData(
max_length=settings.buffer_size,
draw_bytes=lambda data, n, distribution:
distribution(health_check_random, n)
)
with Settings(settings, verbosity=Verbosity.quiet):
try:
#.........这里部分代码省略.........
示例15: wrapped_test
def wrapped_test(*arguments, **kwargs):
settings = wrapped_test._hypothesis_internal_use_settings
if wrapped_test._hypothesis_internal_use_seed is not None:
random = Random(wrapped_test._hypothesis_internal_use_seed)
elif settings.derandomize:
random = Random(function_digest(test))
else:
random = new_random()
import hypothesis.strategies as sd
selfy = None
arguments, kwargs = convert_positional_arguments(wrapped_test, arguments, kwargs)
# If the test function is a method of some kind, the bound object
# will be the first named argument if there are any, otherwise the
# first vararg (if any).
if argspec.args:
selfy = kwargs.get(argspec.args[0])
elif arguments:
selfy = arguments[0]
test_runner = new_style_executor(selfy)
for example in reversed(getattr(wrapped_test, "hypothesis_explicit_examples", ())):
if example.args:
if len(example.args) > len(original_argspec.args):
raise InvalidArgument(
"example has too many arguments for test. "
"Expected at most %d but got %d" % (len(original_argspec.args), len(example.args))
)
example_kwargs = dict(zip(original_argspec.args[-len(example.args) :], example.args))
else:
example_kwargs = example.kwargs
if Phase.explicit not in settings.phases:
continue
example_kwargs.update(kwargs)
# Note: Test may mutate arguments and we can't rerun explicit
# examples, so we have to calculate the failure message at this
# point rather than than later.
message_on_failure = "Falsifying example: %s(%s)" % (
test.__name__,
arg_string(test, arguments, example_kwargs),
)
try:
with BuildContext() as b:
test_runner(None, lambda data: test(*arguments, **example_kwargs))
except BaseException:
report(message_on_failure)
for n in b.notes:
report(n)
raise
if settings.max_examples <= 0:
return
arguments = tuple(arguments)
given_specifier = sd.tuples(
sd.just(arguments), sd.fixed_dictionaries(generator_kwargs).map(lambda args: dict(args, **kwargs))
)
def fail_health_check(message, label):
if label in settings.suppress_health_check:
return
message += (
"\nSee https://hypothesis.readthedocs.io/en/latest/health"
"checks.html for more information about this. "
)
message += (
"If you want to disable just this health check, add %s "
"to the suppress_health_check settings for this test."
) % (label,)
raise FailedHealthCheck(message)
search_strategy = given_specifier
if selfy is not None:
search_strategy = WithRunner(search_strategy, selfy)
search_strategy.validate()
perform_health_check = settings.perform_health_check
perform_health_check &= Settings.default.perform_health_check
from hypothesis.internal.conjecture.data import TestData, Status, StopTest
if not (Phase.reuse in settings.phases or Phase.generate in settings.phases):
return
if perform_health_check:
health_check_random = Random(random.getrandbits(128))
# We "pre warm" the health check with one draw to give it some
# time to calculate any cached data. This prevents the case
# where the first draw of the health check takes ages because
# of loading unicode data the first time.
data = TestData(
max_length=settings.buffer_size,
draw_bytes=lambda data, n, distribution: distribution(health_check_random, n),
)
with Settings(settings, verbosity=Verbosity.quiet):
try:
test_runner(data, reify_and_execute(search_strategy, lambda *args, **kwargs: None))
#.........这里部分代码省略.........