2016-12-22 2 views
0

Как свойство класса можно было насмехаться? Издеваемое свойство не работает внутри класса.Python mock.patch.object для свойств

Код образца:

class Box(object): 
    def __init__(self, size): 
     self._size = size 

    @property 
    def size(self): 
     return self._size 

    def volume(self): 
     print(self.size) 
     return self.size**3 

def get_new_size(): 
    return 42 


box = Box(13) 
with mock.patch.object(Box, 'size', get_new_size): 
    print(box.volume()) 

Возвращает:

<bound method Box.get_new_size of <__main__.Box object at 0x10a8b2cd0>> 
Traceback (most recent call last): 
    File "<stdin>", line 2, in <module> 
    File "<stdin>", line 9, in volume 
TypeError: unsupported operand type(s) for ** or pow(): 'instancemethod' and 'int' 

ответ

1

Просто залатать его свойства:

with mock.patch.object(Box, 'size', property(get_new_size)): 
    print(box.volume()) 

Заметим, что вы также должны сделать так, чтобы get_new_size принимает аргумент:

def get_new_size(self): 
    return 42 
Смежные вопросы