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?
How can I make sure that the unittests are not going to pollute the real application?
Thanks in advance
PS: My question is almost a duplicate of Django test FileField using test fixtures but it doesn't have an accepted answer. Just want to re-ask if something new on this topic.
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
)