问题
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.
回答1:
This is exactly what StringIO/cStringIO (renamed to io.StringIO in Python 3) is for.
回答2:
Or you could implement it yourself pretty easily especially since all you need is readlines()
:
class 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.
回答3:
In python3, it can be as simple as
import io
file = io.StringIO("your text goes here") # takes string as arg
file.read()
In python 2.7, it can be something like:
import io
file = io.StringIO(u"your text goes here") # takes unicode as argument
file.read()
You can use the file
object for testing purpose.
来源:https://stackoverflow.com/questions/11833428/how-to-create-fake-text-file-in-python