Python 模拟函数 return 始终为 False

Python Mock function return always False

我尝试在 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())

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

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 总是 return False 但该函数至少被调用了一次。

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

(python 版本 2.7.6)

您需要导入定义函数的模块并为您的函数分配一个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

您所做的只是创建一个新的 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)