我想测试一些直接使用printand input函数的(python 3)代码。据我了解,最简单的方法是依赖注入:修改代码,使其将输入和输出流作为参数,默认情况下使用sys.stdin和sys.stdout,并在测试过程中传入模拟对象。很明显,如何处理print呼叫:
print(text)
#replaced with...
print(text, file=output_stream)
Run Code Online (Sandbox Code Playgroud)
但是,input没有输入和输出流的参数。以下代码是否正确地重现其行为?
text = input(prompt)
#replaced with...
print(prompt, file=output_stream, end='')
text = input_stream.readline()[:-1]
Run Code Online (Sandbox Code Playgroud)
我看过了的实现input,它做了很多魔术,调用sys.stdin.fileno和检查sys.stdin.encoding,sys.stdin.errors而不是调用任何read*方法-我不知道从哪里开始模拟这些方法。