title: Python mock: wrap instance method
body: <p><strong>What I would like:</strong>
  Ensure that all instances of <code>Foo</code> that are created inside the <code>with</code> statement have their <code>foo</code> instance method wrapped in a MagicMock via <code>wraps=Foo.foo</code>. The reason I want this is so that I can track <code>call_count</code> on the method <code>foo</code> for all instances of <code>Foo</code> that are created. Now that I say it like that it seems kind of impossible...</p>
  
  <pre><code>&gt;&gt;&gt; from mock import patch
  ...
  ... class Foo(object):
  ...
  ...     def foo(self):
  ...         return "foo"
  ...
  ... with patch("__main__.Foo.foo", wraps=Foo.foo) as m:
  ...     foo = Foo()
  ...     print(foo.foo())
  
  Traceback (most recent call last):
    File "a.py", line 12, in &lt;module&gt;
      print(foo.foo())
    File "/disk/software/lib/python27/mock/mock.py", line 1062, in __call__
      return _mock_self._mock_call(*args, **kwargs)
    File "/disk/software/lib/python27/mock/mock.py", line 1132, in _mock_call
      return self._mock_wraps(*args, **kwargs)
  TypeError: unbound method foo() must be called with Foo instance as first argument (got nothing instead)
  </code></pre>
  
  <p><strong>The problem</strong>
  The mocked <code>foo</code> method isn't bound to the <code>foo</code> instance created via <code>foo = Foo()</code> because it's wrapping the unbound method <code>Foo.foo</code>. Does anyone know how to ensure that the mocked method is bound to an instance?</p>
  
  <p><strong>What I already know:</strong></p>
  
  <pre><code>&gt;&gt;&gt; foo = Foo()
  ... with patch.object(foo, "foo", wraps=foo.foo) as m:
  ...     print(foo.foo())
  "foo"
  </code></pre>
  
  <p>But this doesn't satisfy my constraint that the object must be instantiated inside the <code>patch</code> context.</p>