python - 从修补的 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()
声明有关,但我不知道如何进行。谢谢!
解决方案
推荐阅读
- android - 长按RecyclerView时让ImageView出现,释放时消失?
- php - 你仍然可以使用 PDO::quote() 被黑客入侵吗?
- angular - Angular 材质 mat-menu 多次复制内部组件
- javascript - 如何在php中回显ajax变量?
- node.js - 带有 vhost 和 greenlock-express 的 NodeJS 子域
- javascript - 进行多个快速 API 调用而不发送垃圾邮件的最有效方法?
- scala - Spark 结构化流中的 LocalTableScan 有什么用?
- python - 无法使用终端将本地 Python 文件复制到 HIVE
- swift - 让编辑按钮到我需要的地方
- javascript - 合并手风琴菜单和jQuery轮播