title: isinstance and Mocking
body: <pre><code>class HelloWorld(object):
      def say_it(self):
          return 'Hello I am Hello World'
  
  def i_call_hello_world(hw_obj):
      print 'here... check type: %s' %type(HelloWorld)
      if isinstance(hw_obj, HelloWorld):
          print hw_obj.say_it()
  
  from mock import patch, MagicMock
  import unittest
  
  class TestInstance(unittest.TestCase):
      @patch('__main__.HelloWorld', spec=HelloWorld)
      def test_mock(self,MK):
          print type(MK)
          MK.say_it.return_value = 'I am fake'
          v = i_call_hello_world(MK)
          print v
  
  if __name__ == '__main__':
      c = HelloWorld()
      i_call_hello_world(c)
      print isinstance(c, HelloWorld)
      unittest.main()
  </code></pre>
  
  <p>Here is the traceback</p>
  
  <pre class="lang-none prettyprint-override"><code>here... check type: &lt;type 'type'&gt;
  Hello I am Hello World
  True
  &lt;class 'mock.MagicMock'&gt;
  here... check type: &lt;class 'mock.MagicMock'&gt;
  E
  ======================================================================
  ERROR: test_mock (__main__.TestInstance)
  ----------------------------------------------------------------------
  Traceback (most recent call last):
    File "/usr/local/lib/python2.7/dist-packages/mock.py", line 1224, in patched
      return func(*args, **keywargs)
    File "t.py", line 18, in test_mock
      v = i_call_hello_world(MK)
    File "t.py", line 7, in i_call_hello_world
      if isinstance(hw_obj, HelloWorld):
  TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
  
  ----------------------------------------------------------------------
  Ran 1 test in 0.002s
  </code></pre>
  
  <p><strong>Q1.</strong> Why is this error thrown? They are <code>&lt;class type='MagicMock&gt;</code></p>
  
  <p><strong>Q2.</strong> How do I pause the mocking so that the first line will pass if the error is fixed?</p>
  
  <p>From the <a href="http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.__class__" rel="noreferrer">docs</a>:</p>
  
  <blockquote>
    <p>Normally the <code>__class__</code> attribute of an object will return its type. For a mock object with a spec, <code>__class__</code> returns the spec class instead. This allows mock objects to pass <code>isinstance()</code> tests for the object they are replacing / masquerading as:</p>
  </blockquote>
  
  <pre><code>mock = Mock(spec=3)
  isinstance(mock, int)
  True
  </code></pre>