unit testing – Python mock class instance variable

unit testing – Python mock class instance variable

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.

unit testing – Python mock class instance variable

Leave a Reply

Your email address will not be published. Required fields are marked *