Reputation: 472
I'm trying to test multiple image upload to my server. Here is the serializer:
class ImageSerializer(serializers.ModelSerializer):
image = serializers.ListField(
child=serializers.ImageField(allow_empty_file=True)
)
ImageFactory:
def get_image():
image = Image.new("RGB", (2000, 2000))
file = tempfile.NamedTemporaryFile(suffix=".jpg")
image.save(file)
return file
Test:
def test_upload_multiple_images(self):
self.image = get_image()
with open(self.image.name, "rb") as file:
payload = {
"image": [file, file]
}
response = self.client.post(
reverse("gallery-list", args=[self.item.pk]),
data=payload,
format="multipart"
)
When testing via Postman, images from the array are saved correctly. However when using the test case, I get the following message from the response:
{'image': [{'message': 'The submitted file is empty.', 'code': 'empty'}]}
Before adding allow_empty_file=True, there were two of those messages being returned. Has anyone got any idea why that would happen?
Upvotes: 1
Views: 380
Reputation: 76
The problem here is that you're sending the same Image object to the database to be saved twice. Once the first Image object has been decoded to a file to be saved in the database, the Image object will become unreadable, and since its the same object as the second, an error will be thrown.
So if you send the same Image object as two different items, only the first one will be readable. To avoid this you'll have to send two different image objects.
Your ImageFactory can be refactored to:
def get_image(count=1):
images = []
for i in range(count):
file = io.BytesIO()
image = Image.new('RGBA', size=(100, 100), color=(155, 0, 0))
image.save(file, 'png')
file.name = 'test.png'
file.seek(0)
images.append(file)
return images[0] if count == 1 else images
and your Test:
def test_upload_multiple_images(self):
self.images = get_image(2)
payload = {
"image": self.images
}
response = self.client.post(
reverse("gallery-list", args=[self.item.pk]),
data=payload,
format="multipart"
)
Upvotes: 1