I need to test the Photo model of my Django application. How can I mock the ImageField with a test image file?
tests.py
class PhotoT
You can do a few additional things to (1) avoid having to keep a dedicated test image around, and (2) ensure that all test files created during testing are deleted right after:
import shutil
import tempfile
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase, override_settings
MEDIA_ROOT = tempfile.mkdtemp()
@override_settings(MEDIA_ROOT=MEDIA_ROOT)
class MyTest(TestCase):
@classmethod
def tearDownClass(cls):
shutil.rmtree(MEDIA_ROOT, ignore_errors=True) # delete the temp dir
super().tearDownClass()
def test(self):
img = SimpleUploadedFile('test.jpg', b'whatevercontentsyouwant')
# ^-- this will be saved in MEDIA_ROOT
# do whatever ...