如何在python中依次模拟对多次调用的多个方法的调用?

时间:2020-05-12 06:55:04

标签: python python-unittest python-mock

我需要测试以下代码,但不确定如何声明调用。 (此代码以更好的方式编写,在真实代码中没有重复的调用,仅作为示例,我在下面编写了Update类)

```
Class Update(Plan):
    # get_properties, get_res_dict, create_resource is defined in plan class
    def activate():
         #create first resource
         first_props = self.get_properties(self.properties['first'])
         first_res_dict = self.get_res_dict(first_props)
         first_res = self.create_resource(first_res_dict)
         self.first_id = first_res['id']

        #create_second_resource
        second_props = self.get_properties(self.properties['second'])   
        second_res_dict = self.get_res_dict(second_props)
        second_res = self.create_resource(second_res_dict)

那么,这是我的测试用例

Class ToTest(unittest.TestCase):
    def mock_get_res_dict(self, whatever):

         if whatever has value related to first:
              return first_res_dict
         if whatever has value related to second:
              return second_res_dict

    def mock_create_resource(self, res_dict):
        if res_dict has some value related to first:
             return first_res

        if res_dict has some value related to second:
             return second_res


    def test_activate_pass(self):
         some operations
         self.get_res_dict = \
            mock.MagicMock(side_effect=self.mock_get_res_dict)
        self.create_resource = \
            mock.MagicMock(side_effect=self.mock_create_resource)

如何断言对get_res_dict和create_res的调用以创建第一资源和第二资源

如果我执行以下类似操作会出错–错误: AssertionError:找不到模拟(some_value_1)调用

      inst.get_res_dict.assert_any_call(some_value_1)
      inst.create_resource.assert_any_call(some_value_based on get_res_dict_for_1)

      inst.get_res_dict.assert_any_call(some_value_2)
      inst.create_resource.assert_any_call(some_value_based on get_res_dict_for_2)

请帮助,如何依次调用assert来多次调用多个方法

0 个答案:

没有答案