I wish to mock a class with the following requirements:
- The class has public read/write properties, defined in its
__init__()
method - The class has public attribute which is auto-incremented on object creation
- I wish to use
autospec=True
, so the class's API will be strictly checks on calls
A simplified class sample:
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')
I need for the mock object to behave as the the original object, as far as properties are concerned:
- It should auto-increment the id assigned to each newly-created mock object
- It should allow access to its
x,y
properties But the mock method calls should be intercepted by the mock, and have its call signature validated
What's the best way to go on about this?
EDIT
I've already tried several approaches, including subclassing the Mock
class, use attach_mock()
, and mock_add_spec()
, but always ran into some dead end.
I'm using the standard mock library.