【问题标题】:Python Mock function return always FalsePython Mock 函数总是返回 False
【发布时间】:2016-02-17 15:42:25
【问题描述】:

我尝试在 python 中将单元测试添加到将统计信息保存在文件中的函数中

这里是保存功能

def save_file_if_necessary(file_path, content, current_time, mode="w", delta_time=60, force=False):
    if file_path not in file_save or current_time - file_save[file_path] >= delta_time or force:
        with codecs.open(file_path, mode, encoding="utf-8") as written_file:
            written_file.write(content)
            file_save[file_path] = time.time()
            print "yes"
            return True
    else:
        print "not necessary"
        return False

我这样调用这个函数

def test_function():
    bot_url_dic = {"seven1": 10,
                   "seven2": 20
                  }
    save_file_if_necessary(os.path.join("./", "recipients.bots"),json.dumps(bot_url_dic, ensure_ascii=False, indent=4), time.time())

我用 mock 做了一些单元测试来测试函数是否被调用

from test import save_file_if_necessary, test_function

    def test_call_save_file_if_necessary(self):
        """test function to test add in list."""
        ip_dic = ["seven1", "seven2", "seven3"]
        save_file_if_necessary = Mock()

        test_function()
        self.assertTrue(save_file_if_necessary.called)

但问题是 Mock 总是返回 False 但该函数至少被调用一次。

self.assertTrue(save_file_if_necessary.called)
AssertionError: False is not true

(python 版本 2.7.6)

【问题讨论】:

    标签: python unit-testing mocking


    【解决方案1】:

    您所做的只是创建一个新的 Mock 对象,巧合地称为“save_file_if_necessary”。您没有做任何事情来用您的模拟替换实际功能。

    您需要使用patch 功能才能真正做到这一点:

    @mock.patch('my_test_module.save_file_if_necessary')
    def test_call_save_file_if_necessary(self, mock_function):
        ip_dic = ["seven1", "seven2", "seven3"]
    
        test_function()
        self.assertTrue(mock_file.called)
    

    【讨论】:

      【解决方案2】:

      您需要导入定义函数的模块并为您的函数分配Mock

      import test
      
      def test_call_save_file_if_necessary(self):
          """test function to test add in list."""
          ip_dic = ["seven1", "seven2", "seven3"]
          test.save_file_if_necessary = Mock()
      
          test.test_function()
          self.assertTrue(test.save_file_if_necessary.called)
      

      或者,改用patching function

      【讨论】:

      • 谢谢你,你拯救了我的一天 :) 但为什么会这样:从测试导入 save_file_if_necessary,test_function 不起作用?
      • 请不要鼓励在没有任何上下文控制的情况下修补引用:他稍后会回来提出一些其他琐碎的问题。
      猜你喜欢
      • 2011-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多