python - 模拟文件句柄

标签 python unit-testing

There's a couple of stack overflow posts out there talking about mocking the open call in Python.这很好,但如果函数接受文件句柄或流对象而不是文件路径,它并没有真正帮助我。

到目前为止我一直在使用的一个解决方案是cStringIO 对象。但是我遇到了一个问题。

如果我想测试在某种失败时是否正确记录文件名(例如文件/流是否为空并且您期望某种数据)

cStringIO
fd = cStringIO("")
fd.name = "testing/path" # Throws an AttributeError

我无法设置 name 属性,因为 cStringIOStringIO 是开槽类。

如果切换到使用open_mock

with mock.patch('__main__.open', mock.mock_open(read_data=''), create=True) as m:

我遇到了

AttributeError: Mock object has no attribute 'tell'

此时感觉我必须使用临时文件,但如果可能的话我想避免实际调用文件系统。

如何测试接受文件句柄的函数,而无需在文件系统上创建实际文件?

最佳答案

您可以使用 Mock.return_value 为模拟对象显式设置 tell 属性:

import mock

def function_under_test(f):
    f.tell()  # => 0
    f.read()
    f.tell()  # => 0
    return f.name

with mock.patch('__main__.open', mock.mock_open(read_data=''), create=True) as m:
    with open('/tmp/1') as f:
        f.name = '/tmp/1'
        f.tell.return_value = 0
        assert function_under_test(f) == '/tmp/1'

关于python - 模拟文件句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34056856/

相关文章:

python - 禁止(状态代码 : 403) Can't send messages to this user

python - SVN 服务和 PySVN 错误消息 : Expected FS format between '1' and '3' ; found format '4'

python - mysql 查询函数在 python shell 中工作,但在 python 中运行时出现 ImproperlyConfigured 错误

java - 领域驱动设计 - 可测试性和 "new"关键字

java - 如何使用内存数据库编写测试用例?

python - 如何将列表转换为具有多列的数据框?

python 3有向图,带有文件中的标签

c# - 单元测试 SqlFunctions

node.js - Mocha 列表只跳过测试

c# - 在不创建单独项目的情况下使用 Nunit