Pytest -在嵌套对象中发送图像



我有一个接收表单数据的端点,其中一个键是包含图像的对象数组。

我正在尝试对端点

进行以下测试
file_horizontal = BytesIO()
image_horizontal = Image.new('RGBA', size=(244, 100), color=(155, 0, 0))
image_horizontal.save(file_horizontal, 'png')
file_horizontal.name = 'teste_horizontal.png'
file_horizontal.seek(0)
file_vertical = BytesIO()
image_vertical = Image.new('RGBA', size=(138, 100), color=(155, 0, 0))
image_vertical.save(file_vertical, 'png')
file_vertical.name = 'teste_vertical.png'
file_vertical.seek(0)
self.data = {
'part_id': 123
'logo': [
{
'logo_type': 'HORIZONTAL',
'document_type': [1, 2],
'image': file_horizontal
},
{
'logo_type': 'VERTICAL',
'document_type': [3, 4],
'image': file_vertical
},
]
}
def test_diff_create(self):
response = self.client.post(self.url_create, self.data, format='multipart', HTTP_ACCEPT='application/json; version=1.0')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)

这样,端点接收到标识数据为"{'logo_type': 'VERTICAL', 'document_type': [3, 4], 'image': <_io.BytesIO object at 0x7fc4deadf8b0>}"

标识数据不是作为数组发送的,它只发送数组的最后一个对象。在json格式中,数据作为数组发送,但我不能以json发送图像,因为它们不是json序列化的。

端点期望接收一个像这样的数组

[{'logo_type': 'HORIZONTAL', 'document_type': [1, 2], 'image': <InMemoryUploadedFile: test_horizontal.png (image/png)>}, {'logo_type': 'VERTICAL', 'document_type': [3, 4], 'image': <InMemoryUploadedFile: test_vertical.png (image/png)>}]
from django.core.files.uploadedfile import SimpleUploadedFile
from six import BytesIO
from PIL import Image
image = BytesIO()
Image.new('RGB', (100, 100)).save(image, 'JPEG')
image.seek(0)
self.image_1 = SimpleUploadedFile('image.JPG', image.getvalue())

现在取决于您在设置方法或每个测试函数中使用它

最新更新