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?
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.
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.
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.
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.
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
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