gpt4 book ai didi

python - 如何模拟 open(...).write() 而不会出现 'No such file or directory' 错误?

转载 作者:行者123 更新时间:2023-12-04 16:59:24 24 4
gpt4 key购买 nike

我的解决方案基于:

  • How do I mock an open used in a with statement (using the Mock framework in Python)? ,
  • AttributeError: <module '__main__' from [..] does not have the attribute 'open' ,
  • http://www.voidspace.org.uk/python/mock/helpers.html#mock.mock_open

  • 我有一个可以实例化的类,它写入文件。我正在尝试对其进行测试,但在模拟 open() 时遇到问题.我使用以下代码作为最小的一段代码,它可以
    import os
    import unittest
    from unittest.mock import mock_open, patch

    __author__ = 'drews'


    class MockPathExists(object):
    def __init__(self, return_value):
    self.received_args = None
    self.return_value = return_value

    def __call__(self, *args, **kwargs):
    self.received_args = args
    return self.return_value


    class WriteData:
    def __init__(self, dir, name='World'):
    self.name = name
    self.dir = dir

    def dump(self):
    if os.path.exists(self.dir):
    with open('{0}/output.text'.format(self.dir), 'w+') as fp:
    fp.write('Hello, {0}!'.format(self.name))


    class TestListWindowsPasswords(unittest.TestCase):
    def setUp(self):
    self._orig_pathexists = os.path.exists
    os.path.exists = MockPathExists(True)

    def test_dump(self):
    m = mock_open()
    with patch.object(WriteData, 'open', m, create=True):
    data_writer = WriteData(
    dir='/my/path/not/exists',
    name='Foo'
    )
    data_writer.dump()

    self.assertEqual(os.path.exists.received_args[0], '/my/path/not/exists/output.text')
    m.assert_called_once_with('/my/path/not/exists/output.text', 'w+')
    handle = m()
    handle.write.assert_called_once_with('Hello, Foo!')



    def tearDown(self):
    os.path.exists = self._orig_pathexists

    当我运行它时,我收到以下错误:
    Error
    Traceback (most recent call last):
    File "/Users/drews/Development/tool/tests/test_mockopen.py", line 41, in test_dump
    data_writer.dump()
    File "/Users/drews/Development/tool/tests/test_mockopen.py", line 25, in dump
    with open('{0}/output.text'.format(self.dir), 'w+') as fp:
    FileNotFoundError: [Errno 2] No such file or directory: '/my/path/not/exists/output.text'

    如何模拟 open(),使其只返回一个 file_pointer,而根本不尝试与文件系统交互?

    最佳答案

    模拟 builtins.open (或 module.openmodule = 包含 WriteData 的模块名称)与 mock_open :

    import builtins

    class TestListWindowsPasswords(unittest.TestCase):
    def setUp(self):
    self._orig_pathexists = os.path.exists
    os.path.exists = MockPathExists(True)

    def test_dump(self):
    with patch('builtins.open', unittest.mock.mock_open()) as m:
    data_writer = WriteData(
    dir='/my/path/not/exists',
    name='Foo'
    )
    data_writer.dump()

    self.assertEqual(os.path.exists.received_args[0], '/my/path/not/exists') # fixed
    m.assert_called_once_with('/my/path/not/exists/output.text', 'w+')
    handle = m()
    handle.write.assert_called_once_with('Hello, Foo!')

    关于python - 如何模拟 open(...).write() 而不会出现 'No such file or directory' 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33184342/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com