gpt4 book ai didi

python - 如何在 Python 中测试 random.choice?

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:43 24 4
gpt4 key购买 nike

您将如何测试可能导致随机选择的函数?

例如:

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 以返回您设置的输出,以便进行确定性测试。

在这种情况下,它可能类似于:

@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

关于python - 如何在 Python 中测试 random.choice?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42788644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com