简体   繁体   English

python mock_open断言几个写调用

[英]python mock_open assert several write calls

I am trying to test some code that does logging. 我正在尝试测试一些记录日志的代码。

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

I'd like to assert that both blah1 and blah2 get written. 我想断言blah1和blah2都是写的。 My test function looks like this: 我的测试功能如下所示:

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

But it gives me an error: 但这给了我一个错误:

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

How can I properly test multiple calls to the write function? 如何正确测试对写入功能的多次调用?

Versions: Python 2.7.6 mock==1.0.1 版本:Python 2.7.6 mock == 1.0.1

According to the docs, assert_called_with and assert_called_once_with only pass if the call is the most recent one 1 . 根据文档,只有在调用是最近的一次1时assert_called_withassert_called_once_with才通过。 The trick us to use assert_any_call , or assert_has_calls . 我们使用assert_any_callassert_has_calls

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

1 It's kinda hidden in the docs for assert_any_call , so we can't really blame you for missing it... 1它有点儿隐藏在assert_any_call的文档中,所以我们不能真正责怪您错过它...

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

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