Skip to main content
 首页 » 编程设计

python之如何在 Python 中测试 random.choice

2024年10月01日7xxx_UU

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

例如:

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