如何在Python中测试random.choice?

Gau*_*aut 4 python testing random

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

例如:

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
Run Code Online (Sandbox Code Playgroud)

你会如何测试它?

Enr*_*aez 5

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

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

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

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

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