【问题标题】:How to mock a builtin method like 'open' in python? [duplicate]如何在python中模拟像'open'这样的内置方法? [复制]
【发布时间】:2013-12-27 23:09:47
【问题描述】:
def file_handling():
    temp_file = open("/root/temp.tmp", 'w')
    temp_file.write("a")
    temp_file.write("b")

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

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

【问题讨论】:

  • 欢迎来到Stack Overflow。您所说的“模拟”是什么意思?您允许自己使用哪些方法?
  • 我认为“mock”在编程方面的定义相当明确且明确 - en.wikipedia.org/wiki/Mock_object
  • @Tim ,dm03514 , Qantas 94 Heavy 谢谢你们。

标签: python unit-testing mocking


【解决方案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()

【讨论】:

  • 感谢您的回复。 assert_has_calls() 至少需要 2 个参数(给定 1 个)这里的 mock.call 值应该是多少?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-21
  • 1970-01-01
  • 2019-05-01
  • 2021-08-05
相关资源
最近更新 更多