I would like to test the following statement
with open('test.txt', 'w') as f:
print(['abc', 20], end='', file=f)
I tried
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]))
It complains that write is never called, which makes sense. In this case, what is the proper way to check the content for writing?
I also tried to use f.write(str(['abc', 20])) instead of the print statement, which passes the test. Is it just a bad idea to use print?
f.tell()is not zero; though it is a bit of a work-aroundopenwould need to emulate a context manager and return an instance of a mock file - then it would be the mock file that has the.writeassertion(s).openmethod, and his assert is matching withprintfunction. That is the error.