2

I have a Python method called Pippo that during its execution it calls other methods which return the Dataframes to be processed.

I want to mock every single method return with a custom Dataframe, but I can not understand how to patch them automatically.

Example:

module1.py

  import module2
  import module3

      def Pippo():

      returnPluto = module2.Pluto() <---- Wanna mock this Dataframe
      ....
      ....
      ....
      returnPaperino = module3.Paperino() <---- Wanna mock this Dataframe


 Pluto()

In the flow of the Pippo method I call Pluto and Paperino method of another module.

How can I indicate in my testClass when I test Pippo that the method to be called is the one with the mocked Dataframe?

I use Python 2.7 with Cassandra.

For the test I use unittest.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Mauro
  • 21
  • 3
  • Possible duplicate of [Python Mocking a function from an imported module](https://stackoverflow.com/questions/16134281/python-mocking-a-function-from-an-imported-module) – Thom Wiggers Feb 02 '18 at 15:36

1 Answers1

0

The problem is that you're instantiating class in your function, that makes it harder to mock because when you mock the constructor you lose track of the object that is created. So you have to mock the constructor and figure out how to set the return_value to another mock. An easier approach is to use dependency injection.

def Pippo(pluto=None, paperino=None):
  pluto = pluto or Pluto()
  paperino = paperino or Paperino()

Now in you test you can inject your mocks. This change won't break the code as the injected params are only used for testing.

Dan
  • 1,874
  • 1
  • 16
  • 21