gpt4 book ai didi

python - 在django单元测试中上传图片

转载 作者:太空宇宙 更新时间:2023-11-03 11:00:16 25 4
gpt4 key购买 nike

我试图在我的单元测试中将图像上传到 ImageField 无法找出错误

这是我的代码(这个在使用 FileField 的其他单元测试中工作正常)

request = self.factory.put(
'/api/1.0/accounts/artlover/',
{'profile_img': SimpleUploadedFile('foo.jpg', b'foo content')}
)
force_authenticate(request, self.artlover)
view = AccountViewSet.as_view({'put': 'update'})
resp = view(request, slug='artlover')
self.assertEqual(resp.status_code, 200)
self.assertFalse(resp.data.get('is_artist'))

遇到这个错误

Traceback (most recent call last):
File "/home/ben/aktweb/lib/python3.4/site-packages/PIL/ImageFile.py", line 100, in __init__
self._open()
File "/home/ben/aktweb/lib/python3.4/site-packages/PIL/TgaImagePlugin.py", line 62, in _open
depth = i8(s[16])
IndexError: index out of range

当我尝试使用真实图像时

img = ('/home/ben/aktweb/7.jpg')
with open(img) as infile:
request = self.factory.put(
'/api/1.0/accounts/artist/',
{'profile_img': SimpleUploadedFile('7.jpg', infile.read())}
)
force_authenticate(request, self.artist)
view = AccountViewSet.as_view({'put': 'update'})
resp = view(request, slug='artist')
self.assertEqual(resp.status_code, 200)
self.assertTrue(resp.data.get('is_artist'))

以此结束

Traceback (most recent call last):
File "/home/ben/aktweb/django/accounts/tests/test_views.py", line 163, in test_update
{'profile_img': SimpleUploadedFile('7.jpg', infile.read())}
File "/home/ben/aktweb/lib/python3.4/codecs.py", line 319, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

最佳答案

  1. 以二进制方式打开图像文件(b):
  2. 只需将文件对象作为字典的值传递即可。

img = '/home/ben/aktweb/7.jpg'
with open(img, 'rb') as infile:
request = self.factory.put(
'/api/1.0/accounts/artist/',
{'profile_img': infile}
)
...

关于python - 在django单元测试中上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34267406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com