简体   繁体   中英

Python mock.patch autospec a class with properties

I have a class that defines some properties with the @property decorator. When I patch that class and set autospec=True, i expect the property to behave as as it is spec'd

class MyClass(object):

    def __init__(self):
        self.will_not_be_mocked = 'not mocked'

    @property
    def will_be_mocked(self):
        return 'mocked property'

Expected Behavior:

When I access the will_be_mocked property on an instance, it behaves like a string attribute.

>>> my_obj = MyClass()
>>> my_obj.will_be_mocked
'mocked property'

and it is not callable

>>> my_obj.will_be_mocked()
TypeError: 'str' object is not callable

So this test should pass:

with self.assertRaises(TypeError):
    my_obj.will_be_mocked()

Observed Behavior:

When I patch the class, and set autospec=True, The property is included in the mock's spec as expected, however, it becomes a MagicMock, and is callable. So any code which tried to execute that property could pass the unittest and fail in production

@patch('__main__.MyClass', autospec=True)
def test_MyClass(self, MyClass):
    my_obj = MyClass()
    with self.assertRaises(TypeError):
        my_obj.will_be_mocked()

AssertionError: TypeError not raised

Objective:

I want to define the class in such a way that it is easy to mock with autospec. This is why I'm trying to define properties instead of just adding attributes in __init__ .

I want to define the class in such a way that it is easy to mock with autospec

The autospec is normally used in situations where everything about a class is to be mocked or faked. It is not the case in your example, patching or fake 1 and only one class attribute is needed.

Here is an example:

class Base(object):

@property
def cls_property(self):
    return 'cls_property'

class TestBase(unittest.TestCase):

def test_cls_property_with_property(self):
    """
    """
    with mock.patch('app.Base.cls_property', new_callable=mock.PropertyMock) as mock_cls_property:
        mock_cls_property.return_value = 'mocked_cls_property'
        base = Base()
        self.assertEqual(base.cls_property, 'mocked_cls_property')

        with self.assertRaises(Exception):
            base.cls_property()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM