About Dummy Files in Unit Tests

You can create uploaded files in unit tests using the SimpleUploadedFile class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from PIL import Image
from io import BytesIO
from django.core.files.uploadedfile import SimpleUploadedFile

image = Image.new("RGB", (1,1), color=(255, 0, 0))
image_content = BytesIO()
image.save(image_content, "JPEG")
image_content.seek(0)
self.media_file = MediaFile.objects.create(
    title="Photo of a Unicorn",
    image=SimpleUploadedFile(
        name="unicorn.jpg",
        content=image_content.read(),
        content_type="image/jpeg",
    ),
)

Don't forget to delete the files in tearDown(self) or tearDownClass(cls) method:

1
2
self.media_file.image.delete()
self.media_file.delete()

Tips and Tricks Programming Testing Django 4.2 Django 3.2 Django 2.2 Django 1.11 Django 1.8