Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I patch 'random' using unittest.mock.patch?

I'm interested in testing some code that uses the 'random' module, and I'd like to be able to patch/insert my own fake version of random when my tests are running, that returns a known value, and put it back to the normal random module afterwards. From the documentation I can only see that I can patch classes. Is there a way to patch functions? Something like this:

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

That code doesn't work, what do I need instead?

like image 250
Emily Bache Avatar asked Aug 27 '13 10:08

Emily Bache


People also ask

What is the difference between mock and patch?

Patching vs Mocking: Patching a function is adjusting it's functionality. In the context of unit testing we patch a dependency away; so we replace the dependency. Mocking is imitating. Usually we patch a function to use a mock we control instead of a dependency we don't control.

What is Unittest mock patch?

patch() unittest. mock provides a powerful mechanism for mocking objects, called patch() , which looks up an object in a given module and replaces that object with a Mock . Usually, you use patch() as a decorator or a context manager to provide a scope in which you will mock the target object.

Should I use mock MagicMock?

Mock vs. MagicMock is a subclass of Mock . It contains all magic methods pre-created and ready to use (e.g. __str__ , __len__ , etc.). Therefore, you should use MagicMock when you need magic methods, and Mock if you don't need them.

What does Unittest mock do?

New in version 3.3. unittest.mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. unittest.mock provides a core Mock class removing the need to create a host of stubs throughout your test suite.


1 Answers

patch.function doesn't seem to exist. You can use patch itself instead:

with patch('random.choice', return_value=3) as mock_random:
    choice = my_code_that_uses_random()
    assert choice == 3
like image 174
Simeon Visser Avatar answered Sep 28 '22 08:09

Simeon Visser