【问题标题】:python mock_open assert several write callspython mock_open 断言几个写调用
【发布时间】:2015-01-14 23:05:41
【问题描述】:

我正在尝试测试一些记录日志的代码。

logfile = open(file_name, 'w')
logfile.write("blah1")
logfile.write("blah2")

我想断言 blah1 和 blah2 都被写入。我的测试函数如下所示:

def test_it(self):
    logger.open = mock_open()
    logger.time.time = Mock(return_value=12345)

    logger.run_me()

    logger.open.assert_called_once_with('test_12345.log', 'w');
    file_handle_mock = logger.open()
    file_handle_mock.write.assert_called_with("blah1")
    file_handle_mock.write.assert_called_with("blah2")

但它给了我一个错误:

AssertionError: Expected call: write('blah1')
Actual call: write('blah2')

如何正确测试对 write 函数的多次调用?

版本: Python 2.7.6 模拟==1.0.1

【问题讨论】:

    标签: python unit-testing python-2.7 mocking


    【解决方案1】:

    根据文档,assert_called_withassert_called_once_with 仅在调用是最近调用时才通过1。我们使用assert_any_callassert_has_calls 的技巧。

    file_handle_mock.write.assert_has_calls([
        mock.call('blah1'),
        mock.call('blah2'),
    ])
    

    1它有点隐藏在assert_any_call 的文档中,所以我们不能真的责怪你错过它...

    【讨论】:

    • 没问题。乐于助人。
    猜你喜欢
    • 2014-12-08
    • 1970-01-01
    • 2015-12-25
    • 2018-02-25
    • 1970-01-01
    • 2014-06-26
    • 2020-08-24
    • 2021-12-04
    • 1970-01-01
    相关资源
    最近更新 更多