Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python mock class instance variable

Tags:

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?

like image 717
clwen Avatar asked Jul 18 '13 18:07

clwen


1 Answers

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.

like image 147
twil Avatar answered Oct 20 '22 00:10

twil