Skip to content
Advertisement

How to mock imported library methods with unittest.mock in Python 3.5?

Is it possible to mock methods of imported modules with unittest.mock in Python 3.5?

JavaScript

I expected that the the os.listdir method returns the specified side_effect “a” on the first call, but inside of my_function the unpatched os.listdir is called.

Advertisement

Answer

unittest.mock have two main duties:

  • Define Mock objects: object designed to follow your screenplay and record every access to your mocked object
  • patching references and recover the original state

In your example, you need both functionalities: Patching os.listdir reference used in production code by a mock where you can have complete control of how it will respond. There are a lot of ways to use patch, some details to take care on how use it and cavelets to know.

In your case you need to test my_function() behaviour and you need to patch both os.listdir() and os.getcwd(). Moreover what you need is control the return_value (take a look to the pointed documentation for return_value and side_effect differences).

I rewrote your example a little bit to make it more complete and clear:

JavaScript

I used the decorator syntax because I consider it the cleaner way to do it; moreover, to avoid the introduction of too many details I didn’t use autospecing that I consider a very best practice.

Last note: mocking is a powerful tool but use it and not abuse of it, patch just you need to patch and nothing more.

Advertisement