About Dummy Files in Unit Tests
You can create uploaded files in unit tests using the SimpleUploadedFile
class:
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:
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
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.