Like a mock.patch class imported into 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 a ClassA defined as:

b.py

from c import ClassC

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

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

Obviously I tried:

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

and

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

None of them worked.

+19
source share
3 answers

You need to plan, which ClassCis located so that ClassCin b:

mock.patch('b.ClassC')

Or, in other words, it is ClassCimported into the module band so that the area in which it ClassCneeds to be fixed.

+21
source

Where to patch :

patch() () , , . , , , , .

, , , , .

- a.b.ClassC, ClassC, ClassA.

import mock

with mock.patch('a.b.ClassC') as class_c:
    instance = class_c.return_value  # instance returned by ClassC()
    b = ClassB()
    b.method1()
    assert instance.method3.called == True
+10

Each time a method is called ClassA().method2(), the method scans ClassCas global, thereby being ClassCin the module a.b. You need to fix this location:

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

See section Where to place a section .

+1
source

All Articles