Python 3 unittest 模拟用户输入 [英] Python 3 unittest simulate user input
问题描述
如何在单元测试调用的函数中间模拟用户输入(使用 Python 3 的单元测试)?例如,我有一个函数 foo()
是我正在测试的输出.在 foo()
函数中,它要求用户输入:
How can I simulate user input in the middle of a function called by a unit test (Using Python 3's unittest)? For example, I have a function foo()
who's output I'm testing. In the foo()
function, it asks for user input:
x = input(msg)
输出是基于输入的:
print("input: {0}".format(x))
我希望我的单元测试运行 foo()
,输入一个输入并将结果与预期结果进行比较.
I would like my unit test to run foo()
, enter an input and compare the result with the expected result.
推荐答案
当我尝试测试为用户输入显示对话框的代码时,我经常遇到这个问题,并且相同的解决方案应该适用于两者.您需要在测试范围内提供一个绑定到名称 input
的新函数,其签名与标准 input
函数相同,该函数只返回一个测试值而不实际提示用户.根据您的测试和代码的设置方式,此注入可以通过多种方式完成,因此我将其作为练习留给读者,但您的替换方法将很简单,例如:
I have this problem regularly when I'm trying to test code that brings up dialogs for user input, and the same solution should work for both. You need to provide a new function bound to the name input
in your test scope with the same signature as the standard input
function which just returns a test value without actually prompting the user. Depending on how your tests and code are setup this injection can be done in a number of ways, so I'll leave that as an exercise for the reader, but your replacement method will be something simple like:
def my_test_input(message):
return 7
显然,如果相关,您也可以打开 message
的内容,并返回您选择的数据类型.您还可以做一些更灵活和更通用的事情,以便在多种情况下重复使用相同的替换方法:
Obviously you could also switch on the contents of message
if that were relevant, and return the datatype of your choice of course. You can also do something more flexible and general that allows for reusing the same replacement method in a number of situations:
def my_test_input(retval, message):
return retval
然后你会在 input
中注入一个部分函数:
and then you would inject a partial function into input
:
import functools
test_input_a = functools.partial(my_test_input, retval=7)
test_input_b = functools.partial(my_test_input, retval="Foo")
将 test_input_a
和 test_input_b
保留为接受单个 message
参数的函数,并且 retval
参数已经绑定.
Leaving test_input_a
and test_input_b
as functions that take a single message
argument, with the retval
argument already bound.
这篇关于Python 3 unittest 模拟用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!