'Mocking and testing the python io.BufferedWriter
I'm trying to mock the io.BufferedWrite.write method with @patch using pytest/unittest.mock.
The questions arises withing the error cited bellow, saying that the write method is not mutable. That can cannot be override.
For the following function:
def write_file_contents(destination_file, encoding, contents):
write_file = io.BufferedWriter(open(destination_file, "r", encoding=encoding), buffer_size=len(contents))
try:
writed = write_file.write(contents)
wirte_file.close()
return writed
except IOError:
pprint("Cannot write to the destination %s", destination_file)
raise IOError
One test example can be:
def test_function_write(mocker):
io_write_mock = mocker.patch("io.BufferedWriter.write", create=True)
assert io.BufferedWriter.write.called == True
The method was called on the other side of the test, failing with the following error message.
"TypeError: cannot set 'write' attribute of immutable type '_io.BufferedWriter'"
Somebody have more information on this(how to mock, how to work with streams and unit tests) or even the solution?
I've tried to mock the hole io.BufferedWriter(including the side effect) and injecting the .write function with a mock, but both is mark as not called when doing the assertion.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|