12

I am attempting to write a unit test for a class's __init__:

def __init__(self, buildNum, configFile = "configfile.txt"):
        super(DevBuild, self).__init__(buildNum, configFile)

        if configFile == "configfile.txt":
            self.config.MakeDevBuild()

The config attribute is set by the super's __init__. I'm using mock, and I want the config attribute to be a mock object. However, I haven't been able to figure out how to actually make that happen. Here's the best I could come up with for the test:

def test_init(self):
        with patch('DevBuild.super', create=True) as mock_super:
            mock_MakeDevBuild = MagicMock()
            mock_super.return_value.config.MakeDevBuild = mock_MakeDevBuild

            # Test with manual configuration
            self.testBuild = DevBuild("42", "devconfigfile.txt")
            self.assertFalse(mock_MakeDevBuild.called)

            # Test with automated configuration
            self.testBuild = DevBuild("42")
            mock_MakeDevBuild.assert_called_once_with()

However, this doesn't work--I get an error:

Error
Traceback (most recent call last):
  File "/Users/khagler/Projects/BuildClass/BuildClass/test_devBuild.py", line 17, in test_init
    self.testBuild = DevBuild("42")
  File "/Users/khagler/Projects/BuildClass/BuildClass/DevBuild.py", line 39, in __init__
    self.config.MakeDevBuild()
AttributeError: 'DevBuild' object has no attribute 'config'

Clearly I'm not setting the config attribute correctly, but I have no idea where exactly I should be setting it. Or for that matter, if what I want to do is even possible. Can anyone tell me what I need to do to make this work?

2
  • An observation: the return value of super is not an object that has a config attribute, but rather an object that has a method __init__ that will add a config attribute to its argument.
    – chepner
    Commented Jan 26, 2013 at 17:23
  • Is that the entire __init__? If it is, it will only add self.config.MakeDevBuild if no configuration file name is passed, which you do in your test.
    – jlujan
    Commented Jan 26, 2013 at 20:26

2 Answers 2

23
+50

You can't mock __init__ by setting it directly - see _unsupported_magics in mock.py.

As for what you can do, you can mock __init__ by passing it to patch, like so:

mock_makeDevBuild = MagicMock()
def mock_init(self, buildNum, configFile):
    self.config = MagicMock()
    self.config.MakeDevBuild = mock_makeDevBuild

with patch('DevBuild.SuperDevBuild.__init__', new=mock_init):
    DevBuild("42")
    mock_makeDevBuild.assert_called_once_with()

where SuperDevBuild is a base class of DevBuild.

If you really want to mock super(), you can perhaps make a class and then bind __init__ to object manually, like

mock_makeDevBuild = MagicMock()
def get_mock_super(tp, obj):
    class mock_super(object):
        @staticmethod
        def __init__(buildNum, configFile):
            obj.config = MagicMock()
            obj.config.MakeDevBuild = mock_makeDevBuild
    return mock_super
with patch('DevBuild.super', create=True, new=get_mock_super):
    DevBuild("42")
    mock_makeDevBuild.assert_called_once_with()

which works, but is quite ugly..

1
  • The link to unsupported_magics is broken, alas.
    – AdamC
    Commented Jun 23, 2023 at 20:44
1

I do it this way, mocking the inherited class init:

    from unittest import mock

    @mock.patch.object(HierarchicalConf, "__init__")
    def test_super_init(self, mock_super_init):
        # act
        ConfigurationService('my_args')

        # assert
        mock_super_init.assert_called_once_with(args)

Given the class:

class ConfigurationService(HierarchicalConf):
    def __init__(self, dag_name) -> None:
        """Wrapper of Hierarchical Conf."""
        # ... my code    
        super().__init__(args)

And if you want to also mock the ConfigurationService init, you can do quite the same:

    @mock.patch.object(ConfigurationService, "__init__")
    def test_init(self, mock_init):

        # act
        ConfigurationService('my_args')

        # assert
        mock_init.assert_called_once_with('my_args')
1
  • This solution does work, at least with Python 3. This answer contradicts the accepted one; the link provided in the other answer about unsupported magics is a dead link.
    – Mike C
    Commented Sep 28, 2022 at 22:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.