Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between mocking and monkey patching?

I work with python and I'm a bit new to testing. I often see tests replacing an external dependency with a local method like so:

import some_module  def get_file_data():   return "here is the pretend file data"  some_module.get_file_data = get_file_data  # proceed to test 

I see this referred to as "monkey patching" as in the question. I also see the word "mock" being used a lot alongside "monkey patching" or in what seem to be very similar scenarios.

Is there any difference between the two concepts?

like image 491
Jad S Avatar asked Jan 17 '17 15:01

Jad S


People also ask

What is the difference between mock and MagicMock?

Mock vs. So what is the difference between them? 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 is mock patch?

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.

Why is it called monkey patching?

The term monkey patch seems to have come from an earlier term, guerrilla patch, which referred to changing code sneakily – and possibly incompatibly with other such patches – at runtime. The word guerrilla, nearly homophonous with gorilla, became monkey, possibly to make the patch sound less intimidating.

Why do we need monkey patching?

Monkey patching is reopening the existing classes or methods in class at runtime and changing the behavior, which should be used cautiously, or you should use it only when you really need to. As Python is a dynamic programming language, Classes are mutable so you can reopen them and modify or even replace them.


1 Answers

Monkey patching is replacing a function/method/class by another at runtime, for testing purpses, fixing a bug or otherwise changing behaviour.

The unittest.mock library makes use of monkey patching to replace part of your software under test by mock objects. It provides functionality for writing clever unittests, such as:

  • It keeps record of how mock objects are being called, so you can test the calling behaviour of your code with asserts.
  • A handy decorator patch() for the actual monkey patching.
  • You can make mock objects to return specific values (return_value), raise specific exceptions (side_effect).
  • Mocking of 'magic methds' (e.g. __str__).

You can use mocking, for example, to replace network I/O (urllib, requests) in a client, so unittests work without depending on an external server.

like image 176
René Pijl Avatar answered Oct 11 '22 10:10

René Pijl