You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在DRF中测试基于Django Imagekit的图片字段问题

Testing Django Imagekit's ProcessedImageField with DRF Serializer

Hey there! Let’s break down how to properly test your ProcessedImageField setup alongside the DRF serializer you’ve written. I’ll cover both serializer-level validation tests and end-to-end API upload tests, plus key checks to ensure Imagekit’s processing is working as expected.

First, Prep a Test Image Generator

To avoid relying on real image files, you can generate a simple test image in-memory using Pillow (make sure it’s installed via pip install pillow):

from PIL import Image
import io

def generate_test_image(width=1000, height=1000):
    # Create a basic RGB image with a solid color
    img = Image.new('RGB', (width, height), color='blue')
    img_io = io.BytesIO()
    img.save(img_io, format='JPEG')
    img_io.seek(0)  # Reset the file pointer to the start
    img_io.name = 'test_image.jpg'  # Give it a proper filename
    return img_io

Test the Serializer Directly

Let’s write unit tests to verify the serializer handles valid/invalid images correctly, and that Imagekit processes the image as configured.

from django.test import TestCase
from .models import AltroUser
from .serializers import UserRegistrationSerializer

class UserRegistrationSerializerTests(TestCase):
    def test_serializer_accepts_valid_image_and_processes_it(self):
        test_img = generate_test_image()
        serializer_data = {
            'first_name': 'John',
            'image': test_img
        }

        # Validate the serializer data
        serializer = UserRegistrationSerializer(data=serializer_data)
        self.assertTrue(serializer.is_valid(), msg=serializer.errors)

        # Save the user instance
        user = serializer.save()

        # Verify the image field is populated
        self.assertTrue(user.image)
        self.assertIn('media/path', user.image.name)  # Match your upload_to path

        # Check that Imagekit resized the image to 640x640
        with Image.open(user.image.path) as processed_img:
            self.assertEqual(processed_img.size, (640, 640))
            self.assertEqual(processed_img.format, 'JPEG')

    def test_serializer_rejects_non_image_files(self):
        # Create a fake text file instead of an image
        non_image_file = io.BytesIO(b'This is not an image')
        non_image_file.name = 'fake_file.txt'

        serializer_data = {
            'first_name': 'Jane',
            'image': non_image_file
        }

        serializer = UserRegistrationSerializer(data=serializer_data)
        self.assertFalse(serializer.is_valid())
        self.assertIn('image', serializer.errors)  # Ensure the error is on the image field

Test Image Upload via API

If you’re exposing this serializer via an API endpoint, test the full upload flow using DRF’s APIClient:

from rest_framework.test import APIClient

class UserRegistrationAPITests(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.registration_url = '/api/auth/register/'  # Replace with your actual endpoint

    def test_api_accepts_image_upload_and_creates_user(self):
        test_img = generate_test_image()
        payload = {
            'first_name': 'API Test User',
            'image': test_img
        }

        # Send a multipart/form-data request (required for file uploads)
        response = self.client.post(
            self.registration_url,
            payload,
            format='multipart'
        )

        # Verify the request succeeded
        self.assertEqual(response.status_code, 201)  # Assuming 201 Created for successful registration

        # Check the response includes image data (if your serializer returns it)
        self.assertIn('image', response.data)

        # Fetch the user from the database to confirm Imagekit processing
        user = AltroUser.objects.get(first_name='API Test User')
        with Image.open(user.image.path) as img:
            self.assertEqual(img.size, (640, 640))

Key Notes for Testing

  • Media Root Setup: In your test settings, set MEDIA_ROOT to a temporary directory (e.g., MEDIA_ROOT = os.path.join(BASE_DIR, 'test_media')) to avoid cluttering your main media folder. You can use Django’s override_settings decorator to set this just for tests.
  • Cleanup: Test media files won’t be deleted automatically unless you use a temporary directory. Consider adding a tear-down method to delete the test media folder after tests run.
  • Dependencies: Ensure django-imagekit, djangorestframework, and Pillow are all installed in your test environment.

内容的提问来源于stack exchange,提问作者toothie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:49:57