【问题标题】:How do I mock an open(...).write() without getting a 'No such file or directory' error?如何模拟 open(...).write() 而不会出现“没有这样的文件或目录”错误?
【发布时间】:2016-01-16 00:35:52
【问题描述】:

我的解决方案基于:

我有一个可以实例化的类,它可以写入文件。我正在尝试对其进行测试,但在模拟 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,而根本不尝试与文件系统交互?

【问题讨论】:

    标签: python unit-testing python-3.x mocking filesystems


    【解决方案1】:

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

    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!')
    

    【讨论】:

    • 我的问题是没有使用“builtins.open”。谢谢!
    • test_dump 的第一行可能是多余的? 'm = mock_open()'
    • @YaroslavNikitenko,你是对的。相应地更新了答案。谢谢。
    • 请注意,handle = m() 会将空的call() 添加到m。
    • @kilgoretrout,它来自 OP 的代码。您可以将handle = m(); handle.write.... 替换为m.return_value.write....。
    【解决方案2】:

    您可以使用 __enter__ 魔术方法来模拟:

    from unittest.mock import patch, MagicMock, call, mock_open
    
    @patch('os')
    @patch('builtins.open', new_callable=mock_open())
    def test_dump(self, mock_open_file, mock_os):
        data_writer = WriteData(dir='/my/path/not/exists', name='Foo')
    
        mock_os.path.exists.assert_called_once_with('/my/path/not/exists')
        mock_open_file.assert_called_once_with('/my/path/not/exists/output.text', 'w+')
        mock_open_file.return_value.__enter__().write.assert_called_once_with('Hello, Foo!')
    

    希望这会有所帮助!

    【讨论】:

    • 你所做的也没有错。 __enter__() 是上下文输入的表示。如果您使用 open out of context,例如:file = open('filename.json') 您不在上下文中。仅当使用这种方式时:with open('filename.json') as file:
    猜你喜欢
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 2017-12-08
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 2013-01-14
    相关资源
    最近更新 更多