【问题标题】:Test Upload Excel File and JSONField Django REST测试上传 Excel 文件和 JSONField Django REST
【发布时间】:2017-09-29 15:14:04
【问题描述】:

我的models.py 有3个字段。其中之一是JSONField()

attribute = JSONField(null=True, blank=True)  # Free to add any note to here
type = models.CharField(max_length=30, choices=FileType.choices, default=FileType.zipcode)
file = models.FileField(upload_to='import_files')

为了方便,我通常设置JSONField(null=True, blank=True)

def test_upload_and_process_data_complete_case(self):
    from soken_web.apps.imported_files.models import ImportFile
    with open(str(settings.BASE_DIR) + '/apps/zipcodes/complete.xlsx', 'rb') as uploaded_file:
        data = {
            'attribute': {'author': 'Singh'},
            'type': ImportFile.FileType.zipcode,
            'file': uploaded_file
        }
        response = self.client.post(reverse('api:import_file-list'), data, format='multipart')
        response.render()

        self.assertEqual(status.HTTP_201_CREATED, response.status_code)

而且我的测试运行良好,无需使用 JSONField 进行拍摄

实验:
当我像给定的那样使用JSONField 拍摄时。它将因此错误而失败

AssertionError: Test data contained a dictionary value for key 'attribute', but multipart uploads do not support nested data. You may want to consider using format='json' in this test case.

但是,据我了解,由于file,我必须使用multipart 发帖。

问题:
是否可以同时对具有JSONFieldFileField 的端点进行单元测试?

参考:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 14: invalid start byte

【问题讨论】:

  • 您可以将文件解码为字符串,然后将对象作为 format=json 发送吗?文件里有什么?
  • 这里使用的解析器是否正确stackoverflow.com/questions/36881771/…
  • @SamRedway 我从来没有这样做过。感谢您的答复。这应该是一个古老的问题,但我找不到解决方案。
  • @andi 让我花点时间阅读并消化一下。

标签: python django excel


【解决方案1】:

在玩过解析器之后。
我发现配置中没有任何问题。我错过的只有一件事。我必须用单引号覆盖{"author": "Singh"}
因为 Web 浏览器确实在 str 而不是 python 对象中提交。

def test_upload_and_process_data_complete_case(self):
    from soken_web.apps.imported_files.models import ImportFile
    with open(str(settings.BASE_DIR) + '/apps/zipcodes/complete.xlsx', 'rb') as uploaded_file:
        data = {
            'attribute': '{"author": "Singh"}',
            'type': ImportFile.FileType.zipcode,
            'file': uploaded_file
        }
        response = self.client.post(reverse('api:import_file-list'), data, format='multipart')
        response.render()

        self.assertEqual(status.HTTP_201_CREATED, response.status_code)

【讨论】:

    猜你喜欢
    • 2014-10-16
    • 2014-04-21
    • 2017-03-31
    • 2016-02-16
    • 2021-05-13
    • 2018-10-05
    • 2017-07-17
    相关资源
    最近更新 更多