Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a builtin method like 'open' in python? [duplicate]

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.
like image 515
chinmay Avatar asked Apr 17 '26 02:04

chinmay


1 Answers

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()
like image 156
RemcoGerlich Avatar answered Apr 18 '26 16:04

RemcoGerlich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!