1

I have a DRF POST endpoint that accepts some data + image, my question is how can I test this endpoint using something like Pytest, I'm facing a prob with sending images as a JSON, I tried to use PIL but didn't work.

serializer

class CreateCategorySerializer(serializers.Serializer):
    title = serializers.CharField(max_length=255)
    description = serializers.CharField(max_length=500, required=False)
    priority = serializers.IntegerField(default=0)
    image = serializers.ImageField()

test

@pytest.mark.django_db
def test_name_exist(authenticate_superuser, category):
    data = {
        "title": "CAT 1",
        "description": "Description", 
        "priority": 20,
        "image": "??" 
    }

    response = authenticate_superuser.post(reverse('category_admin:create'), data=data)

    assert response.status_code == status.HTTP_400_BAD_REQUEST
    assert response.data['detail'] == 'This title already exists'
Mohamed Hamza
  • 945
  • 1
  • 5
  • 15
  • That begs a question... why would the endpoint receive images as JSON in the first place? That would be 33% inneficient. – Haroldo_OK May 26 '22 at 10:04
  • What might be possible is to store the image as Base64 encoded, and then decode the image within the test. – Micheal J. Roberts May 26 '22 at 10:04
  • Yeah, but keep in mind that encoding as Base64 would be 33% inneficient. There seems to be a design problem at the endpoint itself. It's not wise to send images as JSON. – Haroldo_OK May 26 '22 at 10:05
  • @Haroldo_OK Why is this inefficient? actually, it works fine with the react as a front-end, anyway I would like to hear your suggestion. – Mohamed Hamza May 26 '22 at 10:08
  • 1
    Does this answer your question? [Django Rest Framework - Unit test image file upload](https://stackoverflow.com/questions/40641595/django-rest-framework-unit-test-image-file-upload) – 2293980990 May 26 '22 at 10:10
  • It's because JSON is a text format, while images are binary; that means that, in order to send images in a JSON, you would need to use some encoding to safely encode the binary to string; the most common way to encode a binary into a string is Base64, that works well, but increases the data's size by 33%. – Haroldo_OK May 26 '22 at 10:15
  • See a list of pros and cons of sending images inside a JSON: https://stackoverflow.com/questions/33279153/rest-api-file-ie-images-processing-best-practices – Haroldo_OK May 26 '22 at 10:16
  • @2293980990 No, it's not – Mohamed Hamza May 26 '22 at 10:28
  • What went wrong when you used PIL? How did you try uploading the image? can you update the code? – John S John May 26 '22 at 14:00

0 Answers0