python - unittesting super() calls

谁都会走 提交于 2019-12-11 09:03:09

问题


class A(object):

    def get_value(self):
        return "foo"


class B(A):

    def get_value(self):
        value = super(B, self).get_value()
        value + "bar"
        return value

Given the above classes, when I wanted to write a testsuite for the B() class, how do I go about mocking that super() call to A()'s get_value() method? The pseudo-ish code for what I want would be:

class BTestCase(TestCase):

    def setUp(self):
        self.b = B()

    def test_get_value(self):
        # This won't work, attribute error- "super" object has
        # no attribute get_value
        super(B, self.b).get_value = Mock()
        super(B, self.b).get_value.assert_called_once_with()

but obviously that won't work. But I'm wondering whether there is a way to test for the call, and if patching is the way to go about it.


回答1:


From docs (http://docs.python.org/2/library/functions.html#super)

super(type[, object-or-type])
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped. <...>

There are two typical use cases for super.

  • In a class hierarchy with single inheritance, super can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable. <...>

  • The second use case is to support cooperative multiple inheritance in a dynamic execution environment. <...>

__

In other words, super is a class for getting methods and properties, and not for setting them.

If You want to monkey-patch something, use instances or classes directly:

class A(object): ...
class B(A): ...
b = B()

super(B, b).get_value = Something()  # no
b.get_value = Something()  # ok
B.get_value = Something()  # ok
A.get_value = Something()  # ok


来源:https://stackoverflow.com/questions/20539769/python-unittesting-super-calls

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