A readable Python patching technique

Yothin Muangsommuk
3 min readSep 22, 2018

One thing that we definitely met after we write a unit test for a while is that “There always something we can not control” something I mention could be randomness, time, file IO, database connection, etc.

When we met one of these cases the question will arise immediately that “How could we test it if the value changes all the time?” The answer to this question is we need to Mock and Python already have a standard library to let us do this at unittest.mock.patch.

There are multiple patching techniques and I was once covering on the case where we patching multiple modules effectively which using ExitStack() to help managing context manager you can find out more here.

But in this article, we will cover the use case of a patch on different situation.

patch decorator

The first use case is where we using the patch as a decorator. This use case is a very simple use case and mostly suite when we patching a small amount of function which is still easy to read and understand the test case function signature.

patch context

The second use case you might saw from the Tricks above. This case we will use a patch along with the context manager. This way, we don’t need to worry about patch decorator will hiding the test case function signature, because the patch itself will be used inside the test case function. The only downfall from this method is we will lose some of the indentations when we act on the function that we will test.

patch manually

The last use case we will start the patch function itself via method start() and stop via the method stop(). When we do patching this way it opens up many new possibilities to manage a patch. For example, we could add a patch inside a setUp method of test suite when every test case in this suit needs the same patch. Which allow us to reduce duplication of a patch in the code a lot. Or on the other hand, We can reduce the test case indentation from the second use case via this method too.

With great power comes with great responsibility, When we do patch manually we need to remember that we need to do stop patching ourselves. As we can see when we using the patch as a decorator or context manager we don’t need to worry about stop patching because these two methods manage to stop patch for us after we left the current context it will stop the patch automatically

To summarize, When and where we want to use which patching technique:

  • patch decorator When we want to patch only one function/method
  • patch as context manager When we want to patch multiple function/method
  • patch manually start/stop When we patch the same function/method every test case and we want to reduce duplication in our test code



Yothin Muangsommuk

Pythonista @ProntoTools ♥ Python, Django, Vim and Star Trek 🖖