Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 测试函数是否已应用于集合的每个项的干净方法?_Python_Unit Testing_Pytest_Python Unittest - Fatal编程技术网

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