Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test random.choice in Python?

How would you test a function which could lead to a random choice?

For instance:

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

How would you test it?

like image 444
Gaut Avatar asked Oct 31 '25 20:10

Gaut


1 Answers

Since you are not testing the shuffling itself, you should patch shuffle to return an output set by you in order to have a deterministic test.

In this case it could be something along the lines of:

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

From the test, you can realise that the return value will simply be dependent on the length of the input list.

You can read more about patch in the docs: https://docs.python.org/dev/library/unittest.mock.html#unittest.mock.patch

like image 121
Enrique Saez Avatar answered Nov 02 '25 10:11

Enrique Saez