How do I make fun of a class property with mox?

I have a class:

class MyClass(object):
    @property
    def myproperty(self):
        return 'hello'

Using moxand py.testhow do I mock myproperty?

I tried:

mock.StubOutWithMock(myclass, 'myproperty')
myclass.myproperty = 'goodbye'

and

mock.StubOutWithMock(myclass, 'myproperty')
myclass.myproperty.AndReturns('goodbye')

but both with an error AttributeError: can't set attribute.

+5
source share
2 answers

When zeroing class attributes is moxused setattr. In this way,

mock.StubOutWithMock(myinstance, 'myproperty')
myinstance.myproperty = 'goodbye'

equivalently

# Save old attribute so it can be replaced during teardown
saved = getattr(myinstance, 'myproperty')
# Replace the existing attribute with a mock
mocked = MockAnything()
setattr(myinstance, 'myproperty', mocked)

Note that since it mypropertyis a property getattr, it setattrwill refer to the methods of the properties __get__and __set__, rather than actually "mock" the property itself.

, , .

mock.StubOutWithMock(myinstance.__class__, 'myproperty')
myinstance.myproperty = 'goodbye'

, , MyClass myproperty.

+9

property? , "getter".

, .

getter, setter, .

class MyClass(object): # Upper Case Names for Classes.
    @property
    def myproperty(self):
        return 'hello'
    @myproperty.setter
    def myproperty(self,value):
        self.someValue= value

class MyClass(object): # Upper Case Names for Classes.
    def getProperty(self):
        return 'hello'
    def setProperty(self,value):
        self.someValue= value
    myproperty= property( getProperty, setProperty )
+3

All Articles