Python 测试函数是否已应用于集合的每个项的干净方法?
我想测试一个类似于以下内容的函数:Python 测试函数是否已应用于集合的每个项的干净方法?,python,unit-testing,pytest,python-unittest,Python,Unit Testing,Pytest,Python Unittest,我想测试一个类似于以下内容的函数: 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_functi
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)
如何独立于其实现来测试此函数,即不将测试绑定到
映射
函数?您可以通过使用仅调用原始函数的模拟来断言对每个元素调用了其他函数
,例如:
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()