gpt4 book ai didi

python - 如何在python中使用print语句测试文件写入

转载 作者:行者123 更新时间:2023-11-28 17:13:09 24 4
gpt4 key购买 nike

我想测试下面的语句

with open('test.txt', 'w') as f:
print(['abc', 20], end='', file=f)

我试过了

  from __future__ import print_function                                              
from mock import patch, mock_open


def f():
with open('test.txt', 'w') as f:

# f.write(str(['abc', 20]))
print(['abc', 20], end='', file=f)


@patch('__builtin__.open', new_callable=mock_open)
def test(mock_f):
f()
mock_f.assert_called_with('test.txt', 'w')
handle = mock_f()
handle.write.assert_called_once_with(str(['abc', 20]))

它提示从未调用过write,这是有道理的。在这种情况下,检查写作内容的正确方法是什么?

我也尝试用f.write(str(['abc', 20]))代替print语句,通过了测试。使用 print 只是个坏主意吗?

最佳答案

python 3.6:

如果您检查模拟对象,您可以看到您正在寻找的东西就在那里。

from unittest.mock import mock_open, patch

def f():
with open('test.txt', 'w') as f:

print(['abc', 20], end='', file=f)

@patch('__main__.__builtins__.open', new_callable=mock_open)
def test(mock_f):
f()
mock_f.assert_called_with('test.txt', 'w')
print('calls to open:\n', mock_f.mock_calls, end ='\n\n')
handle = mock_f()
print('calls to the file:\n', handle.mock_calls, end ='\n\n')
print('calls to write:\n', handle.write.mock_calls, end ='\n\n')
handle.write.assert_called_once_with(str(['abc', 20]))

>>> test()
calls to open:
[call('test.txt', 'w'),
call().__enter__(),
call().write("['abc', 20]"),
call().write(''),
call().__exit__(None, None, None)]

calls to the file:
[call.__enter__(),
call.write("['abc', 20]"),
call.write(''),
call.__exit__(None, None, None)]

calls to write:
[call("['abc', 20]"), call('')]

Traceback (most recent call last):
File "<pyshell#98>", line 1, in <module>
test()
File "C:\Python36\lib\unittest\mock.py", line 1179, in patched
return func(*args, **keywargs)
File "C:/pyProjects33/test_tmp.py", line 30, in test
handle.write.assert_called_once_with(str(['abc', 20]))
File "C:\Python36\lib\unittest\mock.py", line 824, in assert_called_once_with
raise AssertionError(msg)
AssertionError: Expected 'write' to be called once. Called 2 times.
>>>

.write()'' 第二次调用,因为您传递了 end 参数 - 您可以通过以下方式验证这一点玩那个参数。

如何测试?你可以使用 assert_any_call() :

    handle.write.assert_any_call(str(['abc', 20]))

或者,如果您想验证 end 参数,assert_has_calls() :

from unittest.mock import call

....
calls = [call(str(['abc', 20])), call('')]
handle.write.assert_has_calls(calls)

您问过使用打印只是个坏主意吗? |也许其他人可以插话,但以我有限的经验,我从未考虑过使用 print() 写入文件。

关于python - 如何在python中使用print语句测试文件写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46080376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com