def file_handling():
temp_file = open("/root/temp.tmp", 'w')
temp_file.write("a")
temp_file.write("b")
How to mock the 'open' method and subsequent write statements here? When i checked the solution online, suggestions were to use mock_open using the mock library. How can i make use of that here?
self.stubs.Set(__builtins__, "open", lambda *args: <some obj>) does not seem to work.
Well, using the mock library, I think this should work (not tested):
import mock
from unittest2 import TestCase
class MyTestCase(TestCase):
def test_file_handling_writes_file(self):
mocked_open_function = mock.mock_open():
with mock.patch("__builtin__.open", mocked_open_function):
file_handling()
mocked_open_function.assert_called_once_with('/root/temp.tmp', 'w')
handle = mocked_open_function()
handle.write.assert_has_calls()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With