简体   繁体   English

如何 mock.patch 在另一个模块中导入的类

[英]How to mock.patch a class imported in another module

I have a python class with such a module:我有一个带有这样一个模块的python类:

xy.py xy.py

from a.b import ClassA

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

then I have ClassA defined as:然后我将 ClassA 定义为:

b.py 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?现在在这段代码中,在为 xy.py 编写测试时我想模拟.patch ClassC,有没有办法在 python 中实现它?

obviously I tried:显然我试过:

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

and

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

None of these worked.这些都没有奏效。

You need to patch where ClassC is located so that's ClassC in b :您需要修补ClassC所在的位置,以便在b ClassC

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.或者,换句话说, ClassC被导入到模块b ,因此这就是ClassC需要修补的范围。

Where to patch : 在哪里打补丁

patch() works by (temporarily) changing the object that a name points to with another one. patch() 通过(临时)将名称指向的对象更改为另一个对象。 There can be many names pointing to any individual object, so for patching to work you must ensure that you patch the name used by the system under test.可以有许多名称指向任何单个对象,因此要使修补工作,您必须确保修补被测系统使用的名称。

The basic principle is that you patch where an object is looked up , which is not necessarily the same place as where it is defined .基本原则是在查找对象的位置打补丁,该位置不一定与定义对象的位置相同

In your case, the lookup location is abClassC since you want to patch ClassC used in ClassA .在您的情况下,查找位置是abClassC因为您想修补ClassA使用的ClassC

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
    

Each time the method ClassA().method2() is called, the method looks up ClassC as a global, thus finding ClassC in the ab module.每次调用方法ClassA().method2() ,该方法都会将ClassC作为全局查找,从而在ab模块中找到ClassC You need to patch that location:您需要修补位置:

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

See the Where to patch section section.请参阅修补位置部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM