How can I create a fake file object in Python that contains text? I'm trying to write unit tests for a method that takes in a file object and retrieves the text via readlines()
then do some text manipulation. Please note I can't create an actual file on the file system. The solution has to be compatible with Python 2.7.3.
如何在Python中创建包含文本的伪文件对象?我正在尝试为一个方法编写单元测试,该方法接收文件对象并通过readlines()检索文本然后进行一些文本操作。请注意我无法在文件系统上创建实际文件。该解决方案必须与Python 2.7.3兼容。
2 个解决方案
#1
27
This is exactly what StringIO
/cStringIO
(renamed to io.StringIO
in Python 3) is for.
这正是StringIO / cStringIO(在Python 3中重命名为io.StringIO)的用途。
#2
3
Or you could implement it yourself pretty easily especially since all you need is readlines()
:
或者你可以很容易地自己实现它,特别是因为你只需要readlines():
def FileSpoof:
def __init__(self,my_text):
self.my_text = my_text
def readlines(self):
return self.my_text.splitlines()
then just call it like:
然后就像这样称呼它:
somefake = FileSpoof("This is a bunch\nOf Text!")
print somefake.readlines()
That said the other answer is probably more correct.
那说另一个答案可能更正确。
#1
27
This is exactly what StringIO
/cStringIO
(renamed to io.StringIO
in Python 3) is for.
这正是StringIO / cStringIO(在Python 3中重命名为io.StringIO)的用途。
#2
3
Or you could implement it yourself pretty easily especially since all you need is readlines()
:
或者你可以很容易地自己实现它,特别是因为你只需要readlines():
def FileSpoof:
def __init__(self,my_text):
self.my_text = my_text
def readlines(self):
return self.my_text.splitlines()
then just call it like:
然后就像这样称呼它:
somefake = FileSpoof("This is a bunch\nOf Text!")
print somefake.readlines()
That said the other answer is probably more correct.
那说另一个答案可能更正确。