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.
Asked
Active
Viewed 1.5k times
18

approxiblue
- 6,982
- 16
- 51
- 59

user1454693
- 347
- 2
- 5
- 13
4 Answers
36
This is exactly what StringIO
/cStringIO
(renamed to io.StringIO
in Python 3) is for.

approxiblue
- 6,982
- 16
- 51
- 59

Danica
- 28,423
- 6
- 90
- 122
-
The solution has to be compatible with Python 2.7.3 – user1454693 Aug 06 '12 at 18:02
-
6@user1454693 The StringIO version is... or are you using a different 2.7.3 than the rest of the world? – Jon Clements Aug 06 '12 at 18:03
-
2@user1454693 StringIO is compatible with 2.7.3 and above. – Sagar Hatekar Aug 06 '12 at 18:05
5
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.

Ash Singh
- 3,921
- 2
- 25
- 30

Joran Beasley
- 110,522
- 12
- 160
- 179
3
In Python3
import io
fake_file = io.StringIO("your text goes here") # takes string as arg
fake_file.read() # you can use fake_file object to do whatever you want
In Python2
import io
fake_file = io.StringIO(u"your text goes here") # takes unicode as argument
fake_file.read() # you can use fake_file object to do whatever you want
For more info check docs here

Ash Singh
- 3,921
- 2
- 25
- 30
0
It's easy using faker-file (supported formats BIN
, CSV
, DOCX
, ICO
, JPEG
, PDF
, PNG
, PPTX
, SVG
, TXT
, WEBP
and ZIP
).
Installation
pip install faker-file[common]
Usage
from faker import Faker
from faker_file.providers.txt_file import TxtFileProvider
FAKER = Faker()
FAKER.add_provider(TxtFileProvider)
file = FAKER.txt_file()
Check the quick start and recipes for more.

Artur Barseghyan
- 12,746
- 4
- 52
- 44