Please help me understand why the following doesn't work.
In particular - instance attributes of a tested class are not visible to Python's unittest.Mock.
In the example below bar instance attribute is not accessible.
The error returned is:
AttributeError: <class 'temp.Foo'> does not have the attribute 'bar'
import unittest
from unittest.mock import patch
class Foo:
def __init__(self):
super().__init__(self)
self.bar = some_external_function_returning_list()
def do_someting(self):
calculate(self.bar)
class TestFoo(unittest.TestCase):
@patch('temp.Foo.bar')
def test_do_something(self, patched_bar):
patched_bar.return_value = ['list_elem1', 'list_elem2']
Patching is used to modify name or attribute lookup. In this case, there is no bar attribute of the class temp.Foo.
If the intent is to patch the instance variable, you either need an existing instance to modify
def test(self):
f = Foo()
with patch.object(f, 'bar', 3):
self.assertEqual(f.bar, 3)
or you may want to patch the function call that initializes the instance attribute in the first place.
def test(self):
with patch('some_external_function_returning_list', return_value=3):
f = Foo()
self.assertEqual(f.bar, 3)
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