Python mock: mocking base class for inheritance(Python mock:模拟继承的基类)
问题描述
我正在测试一个从另一个非常复杂的类继承的类,具有数据库连接方法和一堆依赖项.我想模拟它的基类,以便我可以很好地使用子类中定义的方法,但是在我从模拟类继承的那一刻,对象本身变成了模拟并丢失了它的所有方法.
I am testing a class that inherits from another one very complex, with DB connection methods and a mess of dependences. I would like to mock its base class so that I can nicely play with the method defined in the subclass, but in the moment I inherit from a mocked class, the object itself turns a mock and loses all its methods.
如何模拟超类?
这种情况或多或少可以概括为:
More or less the situation can be summed up in this:
import mock
ClassMock = mock.MagicMock()
class RealClass(ClassMock):
def lol(self):
print 'lol'
real = RealClass()
real.lol() # Does not print lol, but returns another mock
print real # prints <MagicMock id='...'>
这是一个简化的案例.实际发生的是 RealClass
扩展了 AnotherClass
,但我设法拦截了 AnotherClass
并将其替换为模拟.
This is a simplified case. What is actually happening is that RealClass
extends AnotherClass
, but I managed to intercept the AnotherClass
and replace it with a mock.
推荐答案
这应该适合你.
import mock
ClassMock = mock.MagicMock # <-- Note the removed brackets '()'
class RealClass(ClassMock):
def lol(self):
print 'lol'
real = RealClass()
real.lol() # Does not print lol, but returns another mock
print real # prints <MagicMock id='...'>
您不应该像以前那样传递类的实例.mock.MagicMock
是一个类,所以你直接传递它.
You should'nt pass an instance of the class as you did. mock.MagicMock
is a class, so you pass it directly.
In [2]: inspect.isclass(mock.MagicMock)
Out[2]: True
这篇关于Python mock:模拟继承的基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python mock:模拟继承的基类
基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01