Django test FileField using test fixtures Django test FileField using test fixtures python python

Django test FileField using test fixtures


Django provides a great way to write tests on FileFields without mucking about in the real filesystem - use a SimpleUploadedFile.

from django.core.files.uploadedfile import SimpleUploadedFilemy_model.file_field = SimpleUploadedFile('best_file_eva.txt', b'these are the contents of the txt file')

It's one of django's magical features-that-don't-show-up-in-the-docs :). However it is referred to here.


You can override the MEDIA_ROOT setting for your tests using the @override_settings() decorator as documented:

from django.test import override_settings@override_settings(MEDIA_ROOT='/tmp/django_test')def test_post_solution_file(self):  # your code here


I've written unit tests for an entire gallery app before, and what worked well for me was using the python tempfile and shutil modules to create copies of the test files in temporary directories and then delete them all afterwards.

The following example is not working/complete, but should get you on the right path:

import os, shutil, tempfilePATH_TEMP = tempfile.mkdtemp(dir=os.path.join(MY_PATH, 'temp'))def make_objects():    filenames = os.listdir(TEST_FILES_DIR)    if not os.access(PATH_TEMP, os.F_OK):        os.makedirs(PATH_TEMP)    for filename in filenames:        name, extension = os.path.splitext(filename)        new = os.path.join(PATH_TEMP, filename)        shutil.copyfile(os.path.join(TEST_FILES_DIR, filename), new)        #Do something with the files/FileField heredef remove_objects():    shutil.rmtree(PATH_TEMP)

I run those methods in the setUp() and tearDown() methods of my unit tests and it works great! You've got a clean copy of your files to test your filefield that are reusable and predictable.