I have a model with a FileField. I want to unittest it. django test framework has great ways to manage database and emails. Is there something similar for FileFields?
Ho
Django provides a great way to do this - use a SimpleUploadedFile
or a TemporaryUploadedFile
. SimpleUploadedFile
is generally the simpler option if all you need to store is some sentinel data:
from django.core.files.uploadedfile import SimpleUploadedFile
my_model.file_field = SimpleUploadedFile(
"best_file_eva.txt",
b"these are the file contents!" # note the b in front of the string [bytes]
)
It's one of django's magical features-that-don't-show-up-in-the-docs :). However it is referred to here and implemented here.
Note that you can only put bytes
in a SimpleUploadedFile
since it's implemented using BytesIO
behind the scenes. If you need more realistic, file-like behavior you can use TemporaryUploadedFile
.
If you're stuck on python 2, skip the b
prefix in the content:
my_model.file_field = SimpleUploadedFile(
"best_file_eva.txt",
"these are the file contents!" # no b
)