Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the "name" of a mock object (using a builtin method)

Tags:

python

mocking

The __repr__esentation of a Mock object that has been obtained as an attribute (or as the return of __call__) of another Mock shows what looks like a name attribute. This pseudoattribute however doesn't seem to exist in the class. For example:

>>> import mock
... x = mock.MagicMock()
... y = x.asdf
... z = y.hjkl
... a = z()

>>> a
<MagicMock name='mock.asdf.hjkl()' id='139706648472600'>

>>> 'name' in a.__dict__
False

In order to get this psuedoattribute, it seems that I can either parse the return of y.__repr__() or some sort of recursive function like this:

def get_mock_name(some_mock):
    if some_mock._mock_name:
        return f'{get_mock_name(some_mock._mock_parent)}.{some_mock._mock_name}'
    elif some_mock._mock_new_name:
        return f'{get_mock_name(some_mock._mock_new_parent)}{some_mock._mock_new_name}'
    else:
        return 'mock'                                                        

While both work, is there any standard and/or builtin way of doing this?

Edit: no, I am not asking how to override __repr__

like image 856
Christian Reall-Fluharty Avatar asked Sep 20 '25 20:09

Christian Reall-Fluharty


1 Answers

Thanks @chepner for setting me up with this answer!

The "name" psuedo-attribute can be obtained with the Mock._extract_mock_name() method of the version of mock that ships with python 3.7.

This method is actually used in the implementation of __repr__ to get this information encapsulating the behavior that was previously just a part the __repr__ function.

You can use it like so:

$ python
Python 3.7.3 (default, Jul 19 2019, 10:33:54) 
[GCC 7.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import unittest.mock as mock
>>> x = mock.MagicMock()
>>> y = x.asdf
>>> z = y.hjkl
>>> a = z()
>>> a._extract_mock_name()
'mock.asdf.hjkl()'
like image 192
Christian Reall-Fluharty Avatar answered Sep 22 '25 08:09

Christian Reall-Fluharty