Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock class instance attributes?

Tags:

python

mocking

class MyClass:
    def __init__(self, a, b):
        self.a = a
        self.b = b
 
def myFunc():
    myClass = MyClass(1, 2)
    print(myClass.a, myClass.b)

In my test, I want to run myFunc() but inside myFunc() I want myClass to return 'test1' and 'test2' as its a and b attributes.

So I did this:

with patch('__main__.MyClass') as MockClass:
    instance = MockClass.return_value
    instance.a.return_value = 'test1'
    instance.b.return_value = 'test2'
    myFunc()

However, the result is <MagicMock name=MyClass().a' id='2938383'>..... Instead of simply 'test1' and 'test2'.

What am I doing wrong? What am I misunderstanding about how to use mock?

like image 424
user1008636 Avatar asked Jan 31 '18 22:01

user1008636


1 Answers

return_value is for callables, just write:

with patch('__main__.MyClass') as MockClass:
   instance = MockClass.return_value
   instance.a = 'test1'
   instance.b = 'test2'
   myFunc()

# test1 test2

And you have to patch the class in the with-statement, note the capital letter of Class in '__main__.MyClass'.

like image 131
Darkonaut Avatar answered Sep 28 '22 09:09

Darkonaut