使用不同的参数值从方法中模拟多个 returns 和多个调用?
simulate multiple returns from method with multiple calls using different parameter values?
我想测试是否只将有效文件添加到有效文件计数中,如下所示:
self.n_valid_files = 0
for file in self.list_of_files:
n_paras = self.count_paras(file)
if n_paras != None:
self.n_valid_files += 1
其中 count_paras
returns None
如果出现问题。
有没有办法修补和测试:即在 self.list_of_files
中提供多个给定文件,然后说,对于每个文件,count_paras
应该 return具体值?
即类似于:
my_test_dict = {'filename1': 3, 'filename2': 30, 'filename3': None}
with mock.patch.object(project, 'count_paras') as mock_count:
mock_count.return_value = my_test_dict[what-might-go-here?] # this doesn't work of course
project.process_files(my_test_dict.keys())
...
...问题是多次调用 count_paras
而只有一次调用 process_files
.
如果你想在后续调用中 return 来自模拟函数的不同值,你可以使用 side_effect。在这种情况下,side_effect
获取用作 return 值的值列表(也可以使用可调用的 side_effect
然后将被调用,但这是不相关的用例)。
在您的示例中,您已经有了要用作 return 值的示例字典的值:
def test_count_paras():
project = Project()
my_test_dict = {'filename1': 3, 'filename2': 30, 'filename3': None}
with mock.patch.object(project, 'count_paras') as mock_count:
mock_count.side_effect = my_test_dict.values()
project.process_files(my_test_dict.keys())
assert project.n_valid_files == 2
这里发生的是每次调用模拟的 count_paras
returns 列表中的下一个值传递给 side_effect
,所以在你的情况下 3、30 和 None
.
我想测试是否只将有效文件添加到有效文件计数中,如下所示:
self.n_valid_files = 0
for file in self.list_of_files:
n_paras = self.count_paras(file)
if n_paras != None:
self.n_valid_files += 1
其中 count_paras
returns None
如果出现问题。
有没有办法修补和测试:即在 self.list_of_files
中提供多个给定文件,然后说,对于每个文件,count_paras
应该 return具体值?
即类似于:
my_test_dict = {'filename1': 3, 'filename2': 30, 'filename3': None}
with mock.patch.object(project, 'count_paras') as mock_count:
mock_count.return_value = my_test_dict[what-might-go-here?] # this doesn't work of course
project.process_files(my_test_dict.keys())
...
...问题是多次调用 count_paras
而只有一次调用 process_files
.
如果你想在后续调用中 return 来自模拟函数的不同值,你可以使用 side_effect。在这种情况下,side_effect
获取用作 return 值的值列表(也可以使用可调用的 side_effect
然后将被调用,但这是不相关的用例)。
在您的示例中,您已经有了要用作 return 值的示例字典的值:
def test_count_paras():
project = Project()
my_test_dict = {'filename1': 3, 'filename2': 30, 'filename3': None}
with mock.patch.object(project, 'count_paras') as mock_count:
mock_count.side_effect = my_test_dict.values()
project.process_files(my_test_dict.keys())
assert project.n_valid_files == 2
这里发生的是每次调用模拟的 count_paras
returns 列表中的下一个值传递给 side_effect
,所以在你的情况下 3、30 和 None
.