Skip to content
Advertisement

How to mock an attribute variable that returns a class instance

So I have this class located in folder/layer/base.py which has something like this in it:

JavaScript

I need to add unit tests to already existing functions within that class. My problem is, the function load_plugin() returns an instance of a class located in folder/tileindex/base.py. Because of that, it happens multiple times and in multiple different functions that a line looks like this:

JavaScript

And I have no clue how to mock that. At first I was mocking load_plugin and returning whatever value so I could assert it afterwards. But now that I’ve seen these functions that use self.tileindex as an instance of another class I don’t know what to do. For example:

JavaScript

When I mocked load_plugin, the code failed at the last line saying TypeError: 'Mock' object is not subscriptable.

I tried to import the class that is instanciated and mock that directly. But then for some reason I get the error AttributeError: <Group tileindex> does not have the attribute 'base' as soon as I put @patch('folder.tileindex.base').

Is there some way I can mock self.tileindex itself so I can test the rest of the code?

Thanks!

Advertisement

Answer

Make sure that to not use unittest.mock.Mock but instead unittest.mock.MagicMock for the reasons stated here. You can follow this documentation about Mocking Classes (all of this will use MagicMock).

For your case, here are 3 options to mock the object returned by load_plugin(). You can choose what best fits your needs.

  • mock_plugin_return_values – Mocks via return_value
  • mock_plugin_side_effect – Mocks via side_effect
  • mock_plugin_stub – Mocks via stubbing the class

File tree

JavaScript

folder/layer/base.py

JavaScript

folder/plugin.py

JavaScript

folder/tileindex/base.py

JavaScript

test/test_layer.py

JavaScript

Output

JavaScript
Advertisement