繁体   English   中英

python mock_open断言几个写调用

[英]python mock_open assert several write calls

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

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')

如何正确测试对写入功能的多次调用?

版本:Python 2.7.6 mock == 1.0.1

根据文档,只有在调用是最近的一次1时assert_called_withassert_called_once_with才通过。 我们使用assert_any_callassert_has_calls

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM