Need to mock out some base class behavior in a python test case

孤街浪徒 提交于 2019-12-11 05:17:55

问题


My title is fairly descriptive, but here goes. Suppose I have this setup.

class BaseClass(object):
    def __init__(self):
        pass
    def base_function(self, param="Hello World"):
        print param

#multiple inheritance probably irrelevant but my problem deals with it
class DerivedClass(BaseClass, AnotherBaseClass):
    def __init__(self):
        pass
    def advanced_function(self):
        #blah blah blah
        #code code code
        self.base_function()

Now, I have a situation where I am testing a derived class, but in doing so, I need to ensure that it's base class methods are called. I tried doing something like this

from mock import MagicMock

d = DerivedClass()
super(DerivedClass, d).base_function = MagicMock()
d.advanced_function()
super(DerivedClass, d).base_function.assert_called()

I'm 100% sure this setup is wrong, because

AttributeError: 'super' object has no attribute 'base_function'

I know I'm doing something wrong with super, anyone have an idea?


回答1:


Access via BaseClass.base_function. As you don't overload the method, you just inherit it, the DerivedClass.base_function is the same object:

id(BaseClass.base_function) == id(DerivedClass.base_function)

When the instances are created, they inherit the mock.



来源:https://stackoverflow.com/questions/20530921/need-to-mock-out-some-base-class-behavior-in-a-python-test-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!