What is the clean way to unittest FileField in django?

luc picture luc · Nov 26, 2010 · Viewed 22.4k times · Source

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.

Answer

waterproof picture waterproof · Dec 11, 2013

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.

Limitations

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.

For Python 2

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
)