我该如何模拟open(…).write()而不会出现“没有这样的文件或目录”错误? - python

我的解决方案基于:

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.open(或moduleWriteData =包含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!')

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

如何用'-'解析字符串到节点js本地脚本? - python

我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…

TypeError:'str'对象不支持项目分配,带有json文件的python - python

以下是我的代码import json with open('johns.json', 'r') as q: l = q.read() data = json.loads(l) data['john'] = '{}' data['john']['use…