m_cht
m_cht

Reputation: 419

How do I patch the values of a dictionary that belongs to a class with the Python unittest module?

Let me provide an example:

class Devices:
    the_dict = {'apple': some_class(), 'android': some_class()}

In this example, I want to patch some_class().

I cannot mock the class itself (which would be Devices, in this example), because that would be the class I want to test in the first place.

I have attempted this issue with patching the dictionary itself, but the mock does not recognize the discrepancy between the different keys and values. For example, suppose I have created a mock called mocked_dict, the test does not see the difference between, say, mocked_dict['alpha'] and mocked_dict['beta']. I have also tried patch.dict, but to no avail. I only get an attribute error when using return_value.

Any help is greatly appreciated. Thank you!

Upvotes: 0

Views: 1784

Answers (1)

jfaccioni
jfaccioni

Reputation: 7519

Not sure if this is what you're looking for, but consider adding a helper method mock_device_dict to monkey-patch the dictionary of a given Devices instance:

import unittest
from unittest.mock import Mock


class some_class:
    pass


class Devices:
    the_dict = {'apple': some_class(), 'android': some_class()}


class MyTest(unittest.TestCase):
    def mock_device_dict(self, devices_instance):
        devices_instance.the_dict = {k: Mock() for k in devices_instance.the_dict}
        return devices_instance
    
    def test_device(self):
        devices = Devices()
        self.mock_device_dict(devices)
        # continue with your test here ...


if __name__ == '__main__':
    unittest.main()

Upvotes: 1

Related Questions