2

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'
9
  • That begs a question... why would the endpoint receive images as JSON in the first place? That would be 33% inneficient. Commented May 26, 2022 at 10:04
  • What might be possible is to store the image as Base64 encoded, and then decode the image within the test. Commented May 26, 2022 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. Commented May 26, 2022 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. Commented May 26, 2022 at 10:08
  • 1
    Does this answer your question? Django Rest Framework - Unit test image file upload Commented May 26, 2022 at 10:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.