如何测试随机选择在Python中?

2024-09-30 01:27:14 发布

您现在位置:Python中文网/ 问答频道 /正文

你如何测试一个可能导致随机选择的函数?在

例如:

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

你会如何测试它?在


Tags: of函数fromimportindexvaluedefrandom
2条回答

由于您没有测试洗牌本身,您应该修补shuffle以返回您设置的输出,以便进行确定性测试。在

在这种情况下,它可能是这样的:

@patch('random.shuffle', lambda x: x)
def test_get_max_Indices():
    max_index = getMaxIndices([4,5,6,7,8])
    assert max_index == 4

从测试中,您可以意识到返回值仅仅取决于输入列表的长度。在

您可以在文档中阅读有关修补程序的更多信息:https://docs.python.org/dev/library/unittest.mock.html#unittest.mock.patch

如果你想测试它,你可以写一些类似的东西:

lst = [1,2,3,4,5,5]
assert getMaxIndices(lst) in (4,5)

测试结果是否为4或5。在

如果你想测试它可以同时是随机的,运行1000次,测试你得到的4次和5次大致相同:

^{pr2}$

相关问题 更多 >

    热门问题