2

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?

2
  • Have you tried accessing BaseClass.base_function directly, rather than via super? Commented Dec 11, 2013 at 22:11
  • This works. Why? I thought I needed to use a specific instance of the class. How does setting BaseClass.base_function to equal MagicMock make all derived instances mocked out as well? If you have a link to read explaining all this, much appreciated. Commented Dec 11, 2013 at 22:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.