Python Mock函数返回始终为False

时间:2016-02-17 15:42:25

标签: python unit-testing mocking

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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