How to create a fake text file in Python

How to create a fake file object in Python containing text? I am trying to write unit tests for a method that takes a file object and retrieves text via readlines() , and then does some text manipulation. Please note: I cannot create the actual file in the file system. The solution should be compatible with Python 2.7.3.

+6
source share
2 answers

This is exactly what StringIO / cStringIO (renamed io.StringIO in Python 3) is for.

+25
source

Or you could implement it yourself quite easily, because all you need is readlines() :

 def FileSpoof: def __init__(self,my_text): self.my_text = my_text def readlines(self): return self.my_text.splitlines() 

then just name it like this:

 somefake = FileSpoof("This is a bunch\nOf Text!") print somefake.readlines() 

However, another answer is probably more correct.

+2
source

Source: https://habr.com/ru/post/922235/


All Articles