如何模拟内置方法,如n#39; open'在python?

时间:2013-12-10 12:20:39

标签: python unit-testing mocking

def file_handling():
    temp_file = open("/root/temp.tmp", 'w')
    temp_file.write("a")
    temp_file.write("b")

如何在这里模拟'open'方法和后续的write语句?当我在线检查解决方案时,建议使用模拟库使用mock_open。我怎么能在这里使用它?

self.stubs.Set(__builtins__, "open", lambda *args: <some obj>) does not seem to work.

1 个答案:

答案 0 :(得分:1)

好吧,使用mock库,我认为这应该有效(未经测试):

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()