你如何测试一个可能导致随机选择的函数?在
例如:
from random import shuffle
def getMaxIndices(lst):
'''
:lst: list of int
Return indices of max value. If max value appears more than once,
we chose one of its indices randomly.
'''
index_lst = [(i, j) for i, j in enumerate(lst)]
shuffle(index_lst)
index_lst.sort(key=lambda x: x[1])
max_index = index_lst.pop()[0]
return max_index
你会如何测试它?在
由于您没有测试洗牌本身,您应该修补
shuffle
以返回您设置的输出,以便进行确定性测试。在在这种情况下,它可能是这样的:
从测试中,您可以意识到返回值仅仅取决于输入列表的长度。在
您可以在文档中阅读有关修补程序的更多信息:https://docs.python.org/dev/library/unittest.mock.html#unittest.mock.patch
如果你想测试它,你可以写一些类似的东西:
测试结果是否为4或5。在
如果你想测试它可以同时是随机的,运行1000次,测试你得到的4次和5次大致相同:
^{pr2}$相关问题 更多 >
编程相关推荐