Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在django单元测试中上载图像_Python_Django - Fatal编程技术网

Python 在django单元测试中上载图像

Python 在django单元测试中上载图像,python,django,Python,Django,我正在尝试将图像上载到单元测试中的ImageField,但无法找出错误 这是我的代码(这一个在使用FileField的其他单元测试中运行良好) 获取此错误 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/pyth

我正在尝试将图像上载到单元测试中的ImageField,但无法找出错误

这是我的代码(这一个在使用FileField的其他单元测试中运行良好)

获取此错误

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
  • 以二进制模式(
    b
    )打开图像文件:
  • 只需将文件对象作为字典的值传递


  • 即使使用SimpleUploadedFile也能正常工作,非常感谢!
    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
    
    img = '/home/ben/aktweb/7.jpg'
    with open(img, 'rb') as infile:
        request = self.factory.put(
            '/api/1.0/accounts/artist/',
            {'profile_img': infile}
        )
        ...