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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With