title: Mocking class properties while using 'autospec=True' in python
body: <p>I wish to mock a class with the following requirements:</p>
  
  <ul>
  <li>The class has public read/write properties, defined in its <code>__init__()</code> method</li>
  <li>The class has public attribute which is auto-incremented on object creation</li>
  <li>I wish to use <code>autospec=True</code>, so the class's API will be strictly checks on calls</li>
  </ul>
  
  <p>A simplified class sample: </p>
  
  <pre><code>class MyClass():
      id = 0
  
      def __init__(self, x=0.0, y=1.0):
          self.x = x
          self.y = y
          self.id = MyClass._id
          MyClass.id +=1
  
      def calc_x_times_y(self):
          return self.x*self.y
  
      def calc_x_div_y(self, raise_if_y_not_zero=True):
          try:
              return self.x/self.y
          except ZeroDivisionError:
              if raise_if_y_not_zero:
                  raise ZeroDivisionError
              else:
                  return float('nan')
  </code></pre>
  
  <p>I need for the mock object to behave as the the original object, as far as properties are concerned:</p>
  
  <ul>
  <li>It should auto-increment the id assigned to each newly-created mock object</li>
  <li>It should allow access to its <code>x,y</code> properties
  But the mock method calls should be intercepted by the mock, and have its call signature validated</li>
  </ul>
  
  <p>What's the best way to go on about this?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I've already tried several approaches, including subclassing the <code>Mock</code> class, use <code>attach_mock()</code>, and <code>mock_add_spec()</code>, but always ran into some dead end.</p>
  
  <p>I'm using the standard <a href="http://www.voidspace.org.uk/python/mock/index.html#mock-mocking-and-testing-library" rel="noreferrer">mock</a> library.</p>