25

The question is how to patch an attribute of an instance within a with statement. I tried with following example which doesn't work. It prints as in the comment.

from mock import patch, PropertyMock

class Foo(object):
    f = {'a': 1}

new_foo = Foo()

with patch.object(new_foo, 'f', new_callable=PropertyMock) as mock:
    mock.return_value = {'b': 2}
    print new_foo.f
    # <PropertyMock name='f' id='4474801232'>

2 Answers 2

35

There's an example in the documentation. You need to provide the class to patch.object, not the instantiated object.

from mock import patch, PropertyMock

class Foo(object):
    f = {'a': 1}

new_foo = Foo()

with patch.object(Foo, 'f', new_callable=PropertyMock) as mock:
    mock.return_value = {'b': 2}
    print new_foo.f

print new_foo.f

Outputs:

{'b': 2}
{'a': 1}
Sign up to request clarification or add additional context in comments.

1 Comment

Actually the documentation you linked to uses patch, not patch.object. It's not really clear from that documentation when patch should be used vs. patch.object.
9

config.py

class myClass(object):
    def __init(self):
        self.greeting = "hola"

test_first_test.py

from config import myClass

@patch.object(myClass, "greeting", "what up homie")
def test_one(self):
    print (myClass.greeting)

Output:

what up homie

1 Comment

This one worked for me and it's very simple to implement. I think there should be an example like this in the documentation. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.