测试函数是否已应用于集合中的每个项目的简洁方法?

Clean way to test that a function has been applied to each item of a collection?

我想测试一个类似于下面的函数:

def some_function_under_test(some_list_type_arg: List):
    map(some_other_function, some_list_type_arg)

对此进行单元测试的好方法是什么?

我要模拟 map 函数

assert map_mock.called_once_with(...)

但是函数要是这样写呢

for i in some_list_type_arg:
    some_other_function(i)

如何独立于其实现测试此函数,即不将测试绑定到 map 函数?

您可以通过使用仅调用原始函数的模拟对其进行模拟来断言每个元素都调用了 some_other_function,例如:

import unittest

from mock import patch, Mock, call


def some_other_function(x):
    return 2 * x


def some_function_under_test(some_list_type_arg):
    return map(some_other_function, some_list_type_arg)


class Tests(unittest.TestCase):
    def test_thing(self):
        with patch('__main__.some_other_function', Mock(side_effect=some_other_function)) as other_mock:
            self.assertEqual(list(some_function_under_test([1, 2, 3])),
                             [2, 4, 6])
        self.assertEqual(other_mock.call_args_list,
                         [call(1), call(2), call(3)])


unittest.main()