使用模拟库在循环中进行用户输入的Python测试 [英] Python testing using mock library for user input in a loop
问题描述
我正在尝试使用模拟库来测试一段代码.在此代码中,用户原始输入在for循环中被接受,如下所示.我编写了测试用例test_apple_record
,该用例可以为托盘号提供一个用户输入值.
I am trying to use mock library for testing a piece of the code. In this code, the user raw input is accepted in a for loop as shown below. I have written the test case test_apple_record
that can feed a single user input value for the tray number.
但是,对于for循环中的每个迭代,它只是采用与预期相同的值(5).
But, for every iteration within the for loop, it just takes this same value (5) as expected.
问题是:如何为每次迭代提供不同的值?例如,对于i = 0、1、2的纸盘号,分别指定5、6和7的特定值.
Question is: How to feed different values for each iteration? for example, specific values of 5, 6, and 7 for the tray numbers for i=0, 1 and 2 respectively.
class SomeClass(unittest.TestCase):
def apple_counter(self):
apple_record = {}
for i in range(3):
apple_tray = input("enter tray number:")
apple_record[apple_tray] = (i+1)*10
print("i=%d, apple_record=%s"%(i, apple_record))
def test_apple_record(self):
with mock.patch('builtins.input', return_value='5'):
self.apple_counter()
推荐答案
您可以将side_effect
参数与可迭代使用的参数一起提供返回值:
You can use the side_effect
parameter with an iterable to provide return values:
with mock.patch('builtins.input', side_effect=[5, 6, 7]):
self.apple_counter()
请参见文档:>
See the docs:
如果 side_effect 是可迭代的,则每次对模拟的调用都将返回可迭代的下一个值.
If side_effect is an iterable then each call to the mock will return the next value from the iterable.
这篇关于使用模拟库在循环中进行用户输入的Python测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!