【问题标题】:Can't upload image file while testing Django测试 Django 时无法上传图像文件
【发布时间】:2016-10-17 14:39:03
【问题描述】:

我正在使用 Django REST 框架开发 API。 我有一个具有models.ImageField 的 Django 模型,它工作得很好。 但是当我想对创建模型对象进行单元测试时,我得到了错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

我的代码:

class PlacesTest(APITestCase):

    . . .

    def test_create_place_full(self):
        . . .
        image = SimpleUploadedFile(name='test.jpg',
                                   content=open('test.png', 'rb').read(),
                                   content_type='image/jpeg')

        request = self.factory.post(reverse('place-list'),
                                    {'name': 'test_place_1',
                                     'picture': image,  
                                     })

我尝试将string 与图像路径一起传递,并尝试使用Django testing model with ImageField 中的方法进行测试,但没有成功。

添加图像时我应该将什么类型传递给 Django REST 框架:文件对象或带路径的字符串?

如何将真实文件添加到我的测试中?

【问题讨论】:

    标签: django unit-testing python-3.x


    【解决方案1】:

    如果有人感兴趣,找到我的问题的解决方案:

    我只需要在请求参数中指定format='multipart'

    request = self.factory.post(reverse('place-list'),
                                    {'name': 'test_place_1',
                                     'picture': self.image},
                                    format='multipart')
    

    在我的项目中是:

    REST_FRAMEWORK = {
        ...
        'TEST_REQUEST_DEFAULT_FORMAT': 'json'
    }
    

    因此无法将图像添加到 POST 请求中。

    【讨论】:

      猜你喜欢
      • 2014-10-16
      • 2017-03-31
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多