Open vallsv opened 8 months ago
Sounds like it is because of the app context from the contextvar.
from prompt_toolkit.application import current
def test_1(capsys):
print(current._current_app_session.get())
print(current._current_app_session.get().output.stdout)
print(current._current_app_session.get().output.stdout.closed)
print_formatted_text("1", file=sys.stdout)
def test_2(capsys):
print(current._current_app_session.get())
print(current._current_app_session.get().output.stdout)
print(current._current_app_session.get().output.stdout.closed)
print_formatted_text("2", file=sys.stdout)
test_pt.py::test_1 AppSession(app=None)
<_io.TextIOWrapper encoding='UTF-8'>
False
1
PASSED
test_pt.py::test_2 AppSession(app=None)
<_io.TextIOWrapper encoding='UTF-8'>
True
2
PASSED
It is easy to patch the tests. But is there any chance to make it work without local fixes?
I would prefer that the tests were not aware that they use prompt toolkit.
So, here is my workaround for now.
I haven't found an easy way to clear the contextvars for the general use case.
And i have to patch capsys
fixture.
But it works without changing the tests, which is good, i think.
# conftest.py
import contextvars
import pytest
from prompt_toolkit.application import current
@pytest.fixture
def clear_pt_context():
"""Clear the context used by prompt-toolkit in order to isolate tests"""
yield
# FIXME: Would be better to only clear the value.
# But i haven't found the way.
current._current_app_session = contextvars.ContextVar(
"_current_app_session", default=current.AppSession()
)
@pytest.fixture
def capsys(clear_pt_context, capsys):
"""Monkey patch capsys to make it compatible with prompt-toolkit
capsys replace sys.stdout, then prompt toolkit creates a context on it.
This mocked stdout is finally closed, but the prompt toolkit context
still point to it. `clear_pt_context` force to drop the pt context.
"""
yield capsys
Looks like this was addressed in #1880.
Hi,
Here is something i have noticed while testing the project i manage.
Sounds like
print_formatted_text
andcapsys
does not interoperate together.Do you have any idea how to deal with that problem? Does it make sense to patch one or the other project?
Test
Result
My env