5

Why doesn't the "wraps" keyword work consistently for MagicMock objects? Normal methods are passed through to the wrapped object, but not "special" methods. In the test below, the first assertion passes, the second fails.

import mock
import unittest


class Foo(object):
    def bar(self):
        return 1

    def __len__(self):
        return 3


class TestWrap(unittest.TestCase):
    def test(self):
        foo = Foo()
        c = mock.MagicMock(wraps=foo)
        assert c.bar() == 1 # Passes
        assert len(c) == 3 # Fails

I cannot find anything in the docs that suggests this. Am I missing something?

double-beep
  • 5,031
  • 17
  • 33
  • 41
dgorur
  • 1,638
  • 4
  • 16
  • 26
  • Since MagicMock mocks all magic methods it might be clobbering your len method. Try using Mock. – Dan Apr 18 '17 at 04:27
  • That's the whole point of my question. MagicMock doesn't clobber the bar method, so why does it clobber the \_\_len\_\_ one? Also, if there are other magic methods you want to have mocked, you cannot use Mock. – dgorur Apr 18 '17 at 18:38
  • When does `len(c)` return? – Sam Hartman May 30 '17 at 16:49
  • _When_ does len(c) return? I don't know how to answer that. If you meant "What does len(c) return?" then the answer is 0. – dgorur Jun 05 '17 at 16:49

1 Answers1

1

Because magic methods are looked up differently from normal methods [1], this support has been specially implemented

It appears that the wraps functionality does not wrap the __len__ method for you and you'll have to do it by hand.

TomDotTom
  • 6,238
  • 3
  • 41
  • 39