lundi 4 septembre 2023

Question for the PRO's. Understand Python's Unittest Mock Library code

Context. After applying a patch mocking a method inside a class I was trying to understand the content of the resulting mock object and started to explore Python's Unittest Mock Library code.

My question is more strutural, if this is the right expression. I want to understand why I can't understand this. Do I lack some concept?

Printing my_mock_object.call_args_list.__repr__() resulted in [call('foo', 'bar')] Checking the type type(my_mock_object.call_args_list) resulted in <class 'unittest.mock._CallList'>

Ok, cool. Them I followed the implementation the declaration of the call_args_list and here is where I started to not understand the code I was seeing:

Endup inside class NonCallableMock(Base) with the atribute declared as call_args_list = _delegating_property('call_args_list'). My confusion stars here as the _delegating_property is a function that is outside of the class (NonCallableMock), but calls a self:

def _delegating_property(name):
    _allowed_names.add(name)
    _the_name = '_mock_' + name
    def _get(self, name=name, _the_name=_the_name):
        sig = self._mock_delegate
        if sig is None:
            return getattr(self, _the_name)
        return getattr(sig, name)
    def _set(self, value, name=name, _the_name=_the_name):
        sig = self._mock_delegate
        if sig is None:
            self.__dict__[_the_name] = value
        else:
            setattr(sig, name, value)

    return property(_get, _set)

What is happening here? Is this some kind o pattern I should be aware?

If any of you could also explain the line of thought I should follow to find the solution myself, that would be the best.

Aucun commentaire:

Enregistrer un commentaire