How can I mock object with nested attributes in Python?

冷暖自知 提交于 2021-02-08 03:57:15

问题


I want to mock the method is_room_member where invitee is a string and occupants is a list of string.

If invitee = 'batman' and occupants = ['batman', 'superman'] the method is_room_member returns True.

class Foo:
    @staticmethod
    def is_room_member(invitee, msg):
        return invitee in msg.frm.room.occupants

msg is the object which needs to be mocked so that I can test this method.

How can I test this method since it'll require this msg object which has nested attributes ?

I want the test to be something like:

class Testing(unittest.TestCase):
    def test_is_room_member(self):
        occupants = ['batman', 'superman']
        # mocking 
        # msg = MagicMock()
        # msg.frm.room.occupants = occupants
        self.assertTrue(Foo.is_room_member('batman', msg))

回答1:


There is an existing answer for your question: Mocking nested properties with mock

import unittest
import mock

class Foo:
    @staticmethod
    def is_room_member(invitee, msg):
        return invitee in msg.frm.room.occupants

class Testing(unittest.TestCase):
    def test_is_room_member(self):
        occupants = ['batman', 'superman']

        # mocking
        mocked_msg = mock.MagicMock()
        mocked_msg.frm.room.occupants = occupants

        self.assertTrue(Foo.is_room_member('batman', mocked_msg))

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



回答2:


Since MagicMock is so magical...it is exactly what you wrote.

class Testing(unittest.TestCase):
    def test_is_room_member(self):
    occupants = ['batman', 'superman']
    msg = MagicMock()
    msg.frm.room.occupants = occupants
    print(msg.frm.room.occupants) # >>> ['batman', 'superman']
    self.assertTrue(Foo.is_room_member('batman', msg))

From the unittest docs:

Mock and MagicMock objects create all attributes and methods as you access them and store details of how they have been used.

Unless you say otherwise, everything returns a MagicMock!



来源:https://stackoverflow.com/questions/50690373/how-can-i-mock-object-with-nested-attributes-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!