首页 > 解决方案 > 从修补的 input() 函数中捕获标准输出

问题描述

我正在尝试编写一个测试来检查一个函数(在另一个文件中定义)是否正在打印一个特定的字符串。此功能可以打印到stdout使用print()input()。我正在捕捉stdout并检查那里打印的内容。我还patch()用于将控制台输入提供给该函数。

我的问题是捕获的标准输出流。我能够得到打印输出,print()但不能从input(). 这是代码:

import io
from contextlib import redirect_stdout
from unittest.mock import patch
import scratch_1

# Returns the output and printed string of a function with user shell input
def test_function_with_input(user_input_sequence, expected_output, function):
    captured_stdout = io.StringIO()
    with redirect_stdout(captured_stdout):
        # With each patched usage of 'input', use the next 'user input' in the sequence
        with patch('builtins.input', side_effect=iter(user_input_sequence)) as mocked_input:
            output = function()
    return output, captured_stdout.getvalue()

test_function = scratch_1.ff
_, printed_string = test_function_with_input([],None, test_function)
print(printed_string)

我正在测试的功能是scratch_1.ff. 例如,如果我有这个:

def ff():
    print(f'from print ')
    input('from input prompt')

captured_stdout.getvalue()返回值from print。它不返回from input prompt。我怎么也能得到呢?我怀疑这与patch()声明有关,但我不知道如何进行。谢谢!

标签: pythonpython-3.xiostdout

解决方案


推荐阅读