简体   繁体   English

如何在 Python 中模拟具有嵌套属性的对象?

[英]How can I mock object with nested attributes in Python?

Consider the following code:考虑以下代码:

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

I want to test the method is_room_member where invitee is a string and occupants is a list of string.我想测试is_room_member方法,其中invitee是一个字符串, occupants是一个字符串列表。

If invitee = 'batman' and occupants = ['batman', 'superman'] the method is_room_member returns True .如果invitee = 'batman'occupants = ['batman', 'superman']方法is_room_member返回True

msg is the object which needs to be mocked so that I can test this method. msg是需要msg的对象,以便我可以测试此方法。

How can I test this method, since it'll require this msg object which has nested attributes?我如何测试这个方法,因为它需要这个具有嵌套属性的msg对象?

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))

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()

Since MagicMock is so magical...it is exactly what you wrote.既然 MagicMock 太神奇了……这正是你写的。

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. Mock 和 MagicMock 对象在您访问它们时创建所有属性和方法,并存储它们如何使用的详细信息。

Unless you say otherwise, everything returns a MagicMock!除非你另有说明,否则一切都会返回一个 MagicMock!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM