3
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.
Nilesh
  • 19,323
  • 15
  • 83
  • 135
chinmay
  • 590
  • 3
  • 14

1 Answers1

1

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()
RemcoGerlich
  • 28,952
  • 5
  • 61
  • 78
  • Thank you for reply. assert_has_calls() takes at least 2 arguments (1 given) what should be the mock.call value here? – chinmay Dec 11 '13 at 11:58