我正在寻找一种将随机值传递给 python 代码的方法,该代码从 python 命令的用户命令行获取多个用户输入。我认为它可以帮助我进行测试。
num = input("Some prompt")
是否有任何方法/方法可以自动(以编程方式)将值传递给这些 python input() 函数而无需等待用户在控制台上输入?
此外,我的代码根据指定要获取多少用户输入的用户输入从用户那里获取多个输入。
我的代码:
def delicious_prize(n):
##N no of boxes
##K product number of chocklates in N boxes
##T total no of test cases
print("n = ", n)
if not isinstance(n, int):
print("Not integer type. Only int accepted. Aborting")
return False
elif not n <= 1000:
print("Inpute n: %s is not in range. Should be less than or equal to 1000"%(n))
exit
elif n < 0:
print("No of boxes cannot be negative. Taking positve magnitude as %s"%(abs(n)))
n = abs(n)
elif n == 0:
print("No chocklate boxes offered !")
exit
num_list = []
for i in range(n):
num = input("Enter no of chocklates in %sth box : "%(i))
num_list.append(int(num))
num_tuple = tuple(num_list)
print(num_tuple)
return tuple_count(num_tuple)
if __name__=='__main__':
print(delicious_prize(2))
print(delicious_prize(0))
print(delicious_prize(-3))
print(delicious_prize('wqete'))
最佳答案
您可以替换 input()
函数为您自己的函数。在测试期间执行此操作的专用包是 Python 标准库的一部分:unittest.mock
.
在您的测试中,您将模拟 input()
并让它返回特定值或完全随机的值:
if __name__=='__main__':
from unittest import mock
with mock.patch('__main__.input', create=True) as mocked_input:
mocked_input.side_effect = ['first input', 'second input', 'third input']
delicious_prize(3)
在上面的代码中,一个新的 input
对象被插入到您的模块中,屏蔽了内置的 input()
函数。当它被 delicious_prize
中的代码调用时,每次来自 side_effect
attribute list 的另一个值被退回。
在此特定测试中,字符串不是有效数字;您的实际测试将使用可以转换为整数的值。
测试时,始终传入可预测值;您希望您的单元测试可靠且可重复,而不是偶尔失败。
关于python - 在没有用户干预的情况下实用地向 python input() 提供随机值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25946903/