# 1. Import necessary modules
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.files import File
from django.core.files.storage import default_storage
from django.core.management import call_command
from django.test import TestCase
from PIL import Image
import tempfile
import os
# 2. Create a TestCase class for testing
class YourTestCase(TestCase):
def setUp(self):
# 3. Create a temporary directory for media files
self.media_dir = tempfile.mkdtemp()
self.media_root = default_storage.base_location
default_storage.base_location = self.media_dir
# 4. Generate a mock image file
image = Image.new('RGB', (100, 100), 'white')
image_path = os.path.join(self.media_dir, 'mock_image.jpg')
image.save(image_path)
# 5. Create a SimpleUploadedFile using the mock image file
self.mock_image = SimpleUploadedFile(
name='mock_image.jpg',
content=open(image_path, 'rb').read(),
content_type='image/jpeg'
)
# 6. Optionally, call the `collectstatic` management command
call_command('collectstatic', interactive=False)
def tearDown(self):
# 7. Remove the temporary media directory
default_storage.base_location = self.media_root
shutil.rmtree(self.media_dir)
# 8. Use `self.mock_image` in your test methods to simulate an uploaded image