I'm using Python's mock
library. I know how to mock a class instance method by following the document:
>>> def some_function():
... instance = module.Foo()
... return instance.method()
...
>>> with patch('module.Foo') as mock:
... instance = mock.return_value
... instance.method.return_value = 'the result'
... result = some_function()
... assert result == 'the result'
However, tried to mock a class instance variable but doesn't work (instance.labels
in the following example):
>>> with patch('module.Foo') as mock:
... instance = mock.return_value
... instance.method.return_value = 'the result'
... instance.labels = [1, 1, 2, 2]
... result = some_function()
... assert result == 'the result'
Basically I want instance.labels
under some_function
get the value I want. Any hints?
This version of some_function()
prints mocked labels
property:
def some_function():
instance = module.Foo()
print instance.labels
return instance.method()
My module.py
:
class Foo(object):
labels = [5, 6, 7]
def method(self):
return 'some'
Patching is the same as yours:
with patch('module.Foo') as mock:
instance = mock.return_value
instance.method.return_value = 'the result'
instance.labels = [1,2,3,4,5]
result = some_function()
assert result == 'the result
Full console session:
>>> from mock import patch
>>> import module
>>>
>>> def some_function():
... instance = module.Foo()
... print instance.labels
... return instance.method()
...
>>> some_function()
[5, 6, 7]
'some'
>>>
>>> with patch('module.Foo') as mock:
... instance = mock.return_value
... instance.method.return_value = 'the result'
... instance.labels = [1,2,3,4,5]
... result = some_function()
... assert result == 'the result'
...
...
[1, 2, 3, 4, 5]
>>>
For me your code is working.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With