0

I have test.py


from rest_framework.test import APITestCase
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse

class PostImageTest(APITestCase):
    def setUp(self) -> None:
        self.product = Product.objects.create(...)
        self.sampleImage = SimpleUploadedFile("test_image.jpg", b"binary data", content_type="image/jpeg")

    def test_with_valid_data(self) -> None:
        data = { "image":self.sampleImage, "is_featured":true }
        response = client.post(reverse('images'), data, format='multipart')

I want to pass query params like images?product=id to the client.post() method. Also i'm not getting as to how to encode the image and send a POST request.

When i tried like this

response = client.post(reverse('images'), {'product' : self.product.id}, data=data, format='multipart')

It gives me this error

TypeError: Client.post() got multiple values for argument 'data'

4
  • How is your request look alike in your dev tools? Commented May 3, 2023 at 18:17
  • {{baseUrl}}/images?product=1 . This is the request i'm sending via postman where it works. Also i'm selecting an image via the form-data option in postman to hit the request Commented May 3, 2023 at 18:26
  • What is the payload? Commented May 3, 2023 at 19:43
  • payload = { "image" : some_image, "is_featured" : true } Commented May 3, 2023 at 19:50

1 Answer 1

0

Solved like this

from io import BytesIO
from PIL import Image as img

def get_url(self, paramKey=None, paramValue=None):
    url = reverse('images') + f"?{paramKey}={paramValue}"
    return url

def create_valid_image(self):
    image_file = BytesIO()
    image = img.new('RGBA', size=(50, 50), color=(155, 0, 0))
    image.save(image_file, 'png')
    image_file.name = 'test_image.png'
    image_file.seek(0)
    return image_file

def test_with_valid_data(self) -> None:
    self.myImage = self.create_valid_image()
    expectedStatusCode = status.HTTP_201_CREATED

    url = self.get_url('product', self.product.id)
    data = { 'image' : self.myImage, 'is_featured' : True }
    response = client.post(url, data)
    receivedStatusCode = response.status_code

    self.assertEqual(receivedStatusCode, expectedStatusCode)

So, it looks like if we pass query_params in client.post(), it will consider it as request data. So we have to concatenate the query_params to the original url.

Can further go through this document

Sign up to request clarification or add additional context in comments.

Comments

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.