[CentralOH] Pytest, FileInput, and captured output
Eric Floehr
eric at intellovations.com
Thu Jul 4 16:19:08 EDT 2024
Len,
This may be a long-shot and it's a bit of a hack, but what about using
stderr for output? stderr doesn't get captured by inplace=True. Though I'm
not an expert with pytest and what it might do. Or could you create a
"prompt_user" function that could take a StringIO object for input and
output and pass that through the test since it has a stream-like interface?
Here is a quick test I tried, you could in process_file create and pass in
StringIO's in a pytest test as well.
-------------------
import fileinput
import sys
def prompt_user(prompt, input_stream=sys.stdin, output_stream=sys.stderr):
output_stream.write(prompt)
output_stream.flush()
return input_stream.readline()
def process_file(filename):
with fileinput.input(files=(filename,), inplace=True) as f:
for line in f:
user_input = prompt_user(f"Edit line '{line.strip()}': ")
print(user_input if user_input else line, end='')
process_file('test.txt')
-------------------
Cheers,
Eric
On Wed, Jul 3, 2024 at 4:32 PM Len Jaffe <lenjaffe at jaffesystems.com> wrote:
> I have a method that present a user prompt, and returns the respond, and
> method tests using pytest.
>
> First draft using print(), input() and pytest capsys.out worked fine.
>
> But now I want to move the prompt into another method which is called
> inside a FileInput context manager. The FileInput is instantiated with
> inplace=True, so I can no longer use stdout for the use prompt since
> fileinput uses it for the in-place processing.
>
> I have no problem opening /dev/tty on new fds to do the prompt and
> response, but I'm stumped trying to figure out an alternative solution for
> capturing that output in pytest.
>
> My web searches found nothing of value. Please help.
>
> Suggestions and advice would be greatly appreciated.
>
> Len
> _______________________________________________
> CentralOH mailing list
> CentralOH at python.org
> https://mail.python.org/mailman/listinfo/centraloh
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.python.org/pipermail/centraloh/attachments/20240704/1fa94abd/attachment.html>
More information about the CentralOH
mailing list