Can I set "random" using unittest.mock.patch?

I am interested in testing some code that uses a "random" module, and I would like to be able to correct / insert my own fake version of random numbers when performing my tests, which returns a known value, and then return it to a normal random module. From the documentation, I can only see that I can patch classes. Is there a way to fix the features? Something like that:

def my_code_that_uses_random(): return random.choice([0, 1, 2, 3]) with patch.function(random.choice, return_value=3) as mock_random: choice = my_code_that_uses_random() assert choice == 3 

This code does not work, what do I need?

+6
source share
1 answer

patch.function does not seem to exist. You can use patch instead:

 with patch('random.choice', return_value=3) as mock_random: choice = my_code_that_uses_random() assert choice == 3 
+5
source

Source: https://habr.com/ru/post/952580/


All Articles