test_textio:test_readline
arguments = (), kwargs = {}, __tracebackhide__ = True
test = <function test_readline at 0x00000272d9c4ec20>
settings = settings(database=DirectoryBasedExampleDatabase('d:\\pypy_stuff\\buildbot64\\slave\\pypy-c-jit-win-x86-64\\venv\\.hypo...nt_blob=False, report_multiple_bugs=True, stateful_step_count=50, suppress_health_check=(), verbosity=Verbosity.normal)
random = <random.Random object at 0x00000272dafa65a0>
processed_args = ((), {}, <function default_new_style_executor at 0x00000272d6a6d760>, TupleStrategy((just(()), fixed_dictionaries({'da...readline_universal(),
'mode': sampled_from(['\r', '\n', '\r\n', '', None])}).map(lambda args: dict(args, **kwargs)))))
test_runner = <function default_new_style_executor at 0x00000272d6a6d760>
search_strategy = TupleStrategy((just(()), fixed_dictionaries({'data': st_readline_universal(),
'mode': sampled_from(['\r', '\n', '\r\n', '', None])}).map(lambda args: dict(args, **kwargs))))
runner = None
state = <hypothesis.core.StateForActualGivenExecution object at 0x00000272d9b0cec8>
@impersonate(test)
@define_function_signature(test.__name__, test.__doc__, argspec)
def wrapped_test(*arguments, **kwargs):
# Tell pytest to omit the body of this function from tracebacks
__tracebackhide__ = True
test = wrapped_test.hypothesis.inner_test
if getattr(test, "is_hypothesis_test", False):
raise InvalidArgument(
f"You have applied @given to the test {test.__name__} more than "
"once, which wraps the test several times and is extremely slow. "
"A similar effect can be gained by combining the arguments "
"of the two calls to given. For example, instead of "
"@given(booleans()) @given(integers()), you could write "
"@given(booleans(), integers())"
)
settings = wrapped_test._hypothesis_internal_use_settings
random = get_random_for_wrapped_test(test, wrapped_test)
processed_args = process_arguments_to_given(
wrapped_test, arguments, kwargs, given_kwargs, argspec
)
arguments, kwargs, test_runner, search_strategy = processed_args
if (
inspect.iscoroutinefunction(test)
and test_runner is default_new_style_executor
):
# See https://github.com/HypothesisWorks/hypothesis/issues/3054
# If our custom executor doesn't handle coroutines, or we return an
# awaitable from a non-async-def function, we just rely on the
# return_value health check. This catches most user errors though.
raise InvalidArgument(
"Hypothesis doesn't know how to run async test functions like "
f"{test.__name__}. You'll need to write a custom executor, "
"or use a library like pytest-asyncio or pytest-trio which can "
"handle the translation for you.\n See https://hypothesis."
"readthedocs.io/en/latest/details.html#custom-function-execution"
)
runner = getattr(search_strategy, "runner", None)
if isinstance(runner, TestCase) and test.__name__ in dir(TestCase):
msg = (
f"You have applied @given to the method {test.__name__}, which is "
"used by the unittest runner but is not itself a test."
" This is not useful in any way."
)
fail_health_check(settings, msg, HealthCheck.not_a_test_method)
if bad_django_TestCase(runner): # pragma: no cover
# Covered by the Django tests, but not the pytest coverage task
raise InvalidArgument(
"You have applied @given to a method on "
f"{type(runner).__qualname__}, but this "
"class does not inherit from the supported versions in "
"`hypothesis.extra.django`. Use the Hypothesis variants "
"to ensure that each example is run in a separate "
"database transaction."
)
state = StateForActualGivenExecution(
test_runner, search_strategy, test, settings, random, wrapped_test
)
reproduce_failure = wrapped_test._hypothesis_internal_use_reproduce_failure
# If there was a @reproduce_failure decorator, use it to reproduce
# the error (or complain that we couldn't). Either way, this will
# always raise some kind of error.
if reproduce_failure is not None:
expected_version, failure = reproduce_failure
if expected_version != __version__:
raise InvalidArgument(
"Attempting to reproduce a failure from a different "
"version of Hypothesis. This failure is from %s, but "
"you are currently running %r. Please change your "
"Hypothesis version to a matching one."
% (expected_version, __version__)
)
try:
state.execute_once(
ConjectureData.for_buffer(decode_failure(failure)),
print_example=True,
is_final=True,
)
raise DidNotReproduce(
"Expected the test to raise an error, but it "
"completed successfully."
)
except StopTest:
raise DidNotReproduce(
"The shape of the test data has changed in some way "
"from where this blob was defined. Are you sure "
"you're running the same test?"
) from None
except UnsatisfiedAssumption:
raise DidNotReproduce(
"The test data failed to satisfy an assumption in the "
"test. Have you added it since this blob was "
"generated?"
) from None
# There was no @reproduce_failure, so start by running any explicit
# examples from @example decorators.
errors = list(
execute_explicit_examples(state, wrapped_test, arguments, kwargs)
)
with local_settings(state.settings):
if len(errors) > 1:
# If we're not going to report multiple bugs, we would have
# stopped running explicit examples at the first failure.
assert state.settings.report_multiple_bugs
for fragments, err in errors:
for f in fragments:
report(f)
report(format_exception(err, err.__traceback__))
raise MultipleFailures(
f"Hypothesis found {len(errors)} failures in explicit examples."
)
elif errors:
fragments, the_error_hypothesis_found = errors[0]
for f in fragments:
report(f)
raise the_error_hypothesis_found
# If there were any explicit examples, they all ran successfully.
# The next step is to use the Conjecture engine to run the test on
# many different inputs.
if not (
Phase.reuse in settings.phases or Phase.generate in settings.phases
):
return
try:
if isinstance(runner, TestCase) and hasattr(runner, "subTest"):
subTest = runner.subTest
try:
runner.subTest = types.MethodType(fake_subTest, runner)
state.run_engine()
finally:
runner.subTest = subTest
else:
> state.run_engine()
pypy-venv\Lib\site-packages\hypothesis\core.py:1159:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <hypothesis.core.StateForActualGivenExecution object at 0x00000272d9b0cec8>
def run_engine(self):
"""Run the test function many times, on database input and generated
input, using the Conjecture engine.
"""
# Tell pytest to omit the body of this function from tracebacks
__tracebackhide__ = True
try:
database_key = self.wrapped_test._hypothesis_internal_database_key
except AttributeError:
if global_force_seed is None:
database_key = function_digest(self.test)
else:
database_key = None
runner = ConjectureRunner(
self._execute_once_for_engine,
settings=self.settings,
random=self.random,
database_key=database_key,
)
# Use the Conjecture engine to run the test function many times
# on different inputs.
runner.run()
note_statistics(runner.statistics)
if runner.call_count == 0:
return
if runner.interesting_examples:
self.falsifying_examples = sorted(
runner.interesting_examples.values(),
key=lambda d: sort_key(d.buffer),
reverse=True,
)
else:
if runner.valid_examples == 0:
rep = get_pretty_function_description(self.test)
raise Unsatisfiable(f"Unable to satisfy assumptions of {rep}")
if not self.falsifying_examples:
return
elif not self.settings.report_multiple_bugs:
# Pretend that we only found one failure, by discarding the others.
del self.falsifying_examples[:-1]
# The engine found one or more failures, so we need to reproduce and
# report them.
flaky = 0
if runner.best_observed_targets:
for line in describe_targets(runner.best_observed_targets):
report(line)
report("")
explanations = explanatory_lines(self.explain_traces, self.settings)
for falsifying_example in self.falsifying_examples:
info = falsifying_example.extra_information
ran_example = ConjectureData.for_buffer(falsifying_example.buffer)
self.__was_flaky = False
assert info.__expected_exception is not None
try:
> self.execute_once(
ran_example,
print_example=not self.is_find,
is_final=True,
expected_failure=(
info.__expected_exception,
info.__expected_traceback,
),
)
pypy-venv\Lib\site-packages\hypothesis\core.py:816:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <hypothesis.core.StateForActualGivenExecution object at 0x00000272d9b0cec8>
data = ConjectureData(VALID, 5 bytes, frozen), print_example = True
is_final = True
expected_failure = (AssertionError("assert False\n + where False = <bound method str.startswith of '\\r\\n'>('\\n')\n + where <bound ... + where <bound method str.join of ''> = ''.join\n\n..\\build\\extra_tests\\test_textio.py:48: AssertionError\n")
def execute_once(
self, data, print_example=False, is_final=False, expected_failure=None
):
"""Run the test function once, using ``data`` as input.
If the test raises an exception, it will propagate through to the
caller of this method. Depending on its type, this could represent
an ordinary test failure, or a fatal error, or a control exception.
If this method returns normally, the test might have passed, or
it might have placed ``data`` in an unsuccessful state and then
swallowed the corresponding control exception.
"""
data.is_find = self.is_find
text_repr = [None]
if self.settings.deadline is None:
test = self.test
else:
@proxies(self.test)
def test(*args, **kwargs):
self.__test_runtime = None
initial_draws = len(data.draw_times)
start = time.perf_counter()
result = self.test(*args, **kwargs)
finish = time.perf_counter()
internal_draw_time = sum(data.draw_times[initial_draws:])
runtime = datetime.timedelta(
seconds=finish - start - internal_draw_time
)
self.__test_runtime = runtime
current_deadline = self.settings.deadline
if not is_final:
current_deadline = (current_deadline // 4) * 5
if runtime >= current_deadline:
raise DeadlineExceeded(runtime, self.settings.deadline)
return result
def run(data):
# Set up dynamic context needed by a single test run.
with local_settings(self.settings):
with deterministic_PRNG():
with BuildContext(data, is_final=is_final):
# Generate all arguments to the test function.
args, kwargs = data.draw(self.search_strategy)
if expected_failure is not None:
text_repr[0] = arg_string(test, args, kwargs)
if print_example or current_verbosity() >= Verbosity.verbose:
output = StringIO()
printer = RepresentationPrinter(output)
if print_example:
printer.text("Falsifying example:")
else:
printer.text("Trying example:")
if self.print_given_args:
printer.text(" ")
printer.text(test.__name__)
with printer.group(indent=4, open="(", close=""):
printer.break_()
for v in args:
printer.pretty(v)
# We add a comma unconditionally because
# generated arguments will always be kwargs,
# so there will always be more to come.
printer.text(",")
printer.breakable()
for i, (k, v) in enumerate(kwargs.items()):
printer.text(k)
printer.text("=")
printer.pretty(v)
printer.text(",")
if i + 1 < len(kwargs):
printer.breakable()
printer.break_()
printer.text(")")
printer.flush()
report(output.getvalue())
return test(*args, **kwargs)
# Run the test function once, via the executor hook.
# In most cases this will delegate straight to `run(data)`.
> result = self.test_runner(data, run)
pypy-venv\Lib\site-packages\hypothesis\core.py:637:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
data = ConjectureData(VALID, 5 bytes, frozen)
function = <function StateForActualGivenExecution.execute_once.<locals>.run at 0x00000272dc6078e0>
def default_new_style_executor(data, function):
> return function(data)
pypy-venv\Lib\site-packages\hypothesis\executors.py:47:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
data = ConjectureData(VALID, 5 bytes, frozen)
def run(data):
# Set up dynamic context needed by a single test run.
with local_settings(self.settings):
with deterministic_PRNG():
with BuildContext(data, is_final=is_final):
# Generate all arguments to the test function.
args, kwargs = data.draw(self.search_strategy)
if expected_failure is not None:
text_repr[0] = arg_string(test, args, kwargs)
if print_example or current_verbosity() >= Verbosity.verbose:
output = StringIO()
printer = RepresentationPrinter(output)
if print_example:
printer.text("Falsifying example:")
else:
printer.text("Trying example:")
if self.print_given_args:
printer.text(" ")
printer.text(test.__name__)
with printer.group(indent=4, open="(", close=""):
printer.break_()
for v in args:
printer.pretty(v)
# We add a comma unconditionally because
# generated arguments will always be kwargs,
# so there will always be more to come.
printer.text(",")
printer.breakable()
for i, (k, v) in enumerate(kwargs.items()):
printer.text(k)
printer.text("=")
printer.pretty(v)
printer.text(",")
if i + 1 < len(kwargs):
printer.breakable()
printer.break_()
printer.text(")")
printer.flush()
report(output.getvalue())
> return test(*args, **kwargs)
pypy-venv\Lib\site-packages\hypothesis\core.py:633:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
data = ('\n', [0, -1]), mode = None
> ???
..\build\extra_tests\test_textio.py:31:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
args = (('\n', [0, -1]), None), kwargs = {}, initial_draws = 1
start = 174117.255837
@proxies(self.test)
def test(*args, **kwargs):
self.__test_runtime = None
initial_draws = len(data.draw_times)
start = time.perf_counter()
> result = self.test(*args, **kwargs)
pypy-venv\Lib\site-packages\hypothesis\core.py:575:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
data = ('\n', [0, -1]), mode = None
@given(data=st_readline_universal(),
mode=st.sampled_from(['\r', '\n', '\r\n', '', None]))
def test_readline(data, mode):
txt, limits = data
textio = TextIOWrapper(
BytesIO(txt.encode('utf-8', 'surrogatepass')),
encoding='utf-8', errors='surrogatepass', newline=mode)
lines = []
for limit in limits:
line = textio.readline(limit)
if limit >= 0:
assert len(line) <= limit
if line:
lines.append(line)
elif limit:
break
if mode is None:
txt = translate_newlines(txt)
> assert txt.startswith(u''.join(lines))
E AssertionError: assert False
E + where False = <bound method str.startswith of '\r\n'>('\n')
E + where <bound method str.startswith of '\r\n'> = '\r\n'.startswith
E + and '\n' = <bound method str.join of ''>(['\n'])
E + where <bound method str.join of ''> = ''.join
..\build\extra_tests\test_textio.py:48: AssertionError
During handling of the above exception, another exception occurred:
> ???
..\build\extra_tests\test_textio.py:31:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
pypy-venv\Lib\site-packages\hypothesis\internal\escalation.py:96: in get_trimmed_traceback
is_hypothesis_file(getframeinfo(tb.tb_frame)[0])
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
frame = <frame at 0x00000272e14051a8, file 'd:\pypy_stuff\buildbot64\slave\pypy-c-jit-win-x86-64\venv\pypy-venv\Lib\site-packages\hypothesis\core.py', line -1, code run_engine>
context = 1
def getframeinfo(frame, context=1):
"""Get information about a frame or traceback object.
A tuple of five things is returned: the filename, the line number of
the current line, the function name, a list of lines of context from
the source code, and the index of the current line within that list.
The optional second argument specifies the number of lines of context
to return, which are centered around the current line."""
if istraceback(frame):
positions = _get_code_position_from_tb(frame)
lineno = frame.tb_lineno
frame = frame.tb_frame
else:
lineno = frame.f_lineno
positions = _get_code_position(frame.f_code, frame.f_lasti)
if positions[0] is None:
frame, *positions = (frame, lineno, *positions[1:])
else:
frame, *positions = (frame, *positions)
lineno = positions[0]
if not isframe(frame):
raise TypeError('{!r} is not a frame or traceback object'.format(frame))
filename = getsourcefile(frame) or getfile(frame)
if context > 0:
> start = lineno - 1 - context//2
E TypeError: unsupported operand type(s) for -: 'NoneType' and 'int'
..\build\lib-python\3\inspect.py:1728: TypeError
builder: pypy-c-jit-win-x86-64 build #2431+
test: test_textio:test_readline