如何使用Mock库测试非纯包含副作用递归图遍历函数?

问题描述

我有一个“深度优先搜索”算法功能,可以递归地遍历DAG(有向图),以查找父节点和子节点之间的依存关系,然后最终返回这些依存关系的列表。

对于初始节点中的每个依赖项,我正在使用另一个类中的函数分别为依赖项分配下一个节点,以便能够“检查下一个”。

我正在使用Mock为此设置单元测试。但是我似乎无法使其正常工作,因为我正在测试的函数内部存在副作用(即,每次迭代都需要另一个函数调用)。请参见下面的示例代码

# Simplified version of the DFS algorithm to show necessary information
def recursive_function(other_class,object_to_check,list_to_return=None):
    if list_to_return is None:
        list_to_return = [object_to_check]

    dependencies = object_to_check.dependencies

    if dependencies :
        for dep in dependencies:

            # this is the function call thats making it problematic
            next_object = other_class.get_next_object_from_dep(dep)

            list_to_return.append(next_object)
            recursive_function(other_class,next_object,list_to_return)

    return list_to_return

如您所见,我正在遍历函数调用 other_class.get_next_object_from_dep(dep)。我曾尝试为此设置单元测试,但无法正常工作。

我知道Mock,Magicmock,设置修补程序,在Mock中设置return_value以及side_effects(如果有的话),但是我仍然无法将这些拼图拼凑在一起。

我当前测试的示例,已简化:

MOCK_PARENT= '''
{
    "id": 1337
}
'''

MOCK_CHILD= '''
{
    "id": 1,"parent_id": 1337
}
'''

# So testing on MOCK_CHILD should return both MOCK_CHILD 
# and MOCK_PARENT as MOCK_CHILD is dependent on MOCK_PARENT (preceding dependency).

class Test(unittest.TestCase):
    def setUp(self):
        self.mock_parent = MockParentClass(json.loads(MOCK_PARENT))
        self.mock_child = MockChildClass(json.loads(MOCK_CHILD))
        self.parent = ParentClass(self.mock_parent)
        self.child = ChildClass(self.mock_child)

        self.m = Mock()
        self.session = Session()
        self.other_class = OtherClass(self.session)

    # Do I need to add a @mock.patch decorator here?
    def test_graph_traversal(self):
        expected_results = [Childobject,ParentObject]

        # matches --> "def recursive_function(other_class,list_to_return=None)"
        objects_from_my_func = recursive_function(self.other_class,self.child,[self.child])
        assertEquals(objects_from_my_func,expected_results)

使用这种方法,我遇到类似“模拟对象没有属性功能...” 之类的错误

本质上,我应该如何考虑测试还具有副作用的递归函数我无法解决副作用,因为我需要遍历遍历外部函数来查找下一个要检查的节点。我对整个单元测试还很陌生,因此我非常想学习使用Mock库。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)