Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock.patch a class imported in another module

I have a python class with such a module:

xy.py

from a.b import ClassA  class ClassB:   def method_1():     a = ClassA()     a.method2() 

then I have ClassA defined as:

b.py

from c import ClassC  class ClassA:   def method2():       c = ClassC()       c.method3() 

Now in this code, when writing test for xy.py I want to mock.patch ClassC, is there a way to achieve that in python?

obviously I tried:

mock.patch('a.b.ClassA.ClassC') 

and

mock.patch('a.b.c.ClassC') 

None of these worked.

like image 589
Ankit Avatar asked Jun 19 '15 19:06

Ankit


People also ask

How do you mock an entire class in Python?

To mock an entire class you'll need to set the return_value to be a new instance of the class. @mock.

How do you import mocks in Python?

Rather than hacking on top of Python's import machinery, you can simply add the mocked module into sys. path , and have Python prefer it over the original module. Now, when the test suite is run, the mocked-lib subdirectory is prepended into sys. path and import A uses B from mocked-lib .

Can we mock a class in Python?

Once you patch a class, references to the class are completely replaced by the mock instance. mock. patch is usually used when you are testing something that creates a new instance of a class inside of the test.

What is the difference between mock and patch?

Mock is a type, and patch is a context. So you are going to pass or receive Mock instances as parameters, and apply patch contexts to blocks of code. (Lowercase 'mock' is just the name of the package.) Tests and test classes are often decorated with calls to patch.


1 Answers

You need to patch where ClassC is located so that's ClassC in b:

mock.patch('b.ClassC') 

Or, in other words, ClassC is imported into module b and so that's the scope in which ClassC needs to be patched.

like image 103
Simeon Visser Avatar answered Sep 19 '22 06:09

Simeon Visser