Python 测试上传Excel文件和JSONField Django REST
MyPython 测试上传Excel文件和JSONField Django REST,python,django,excel,Python,Django,Excel,Mymodels.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
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
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
拍摄时,就像给定的那样。它将因此错误而失败
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.
然而,据我所知,由于文件
,我不得不使用多部分
发布
问题:是否可以对同时具有
JSONField
和FileField
的端点进行单元测试
参考资料:在使用解析器之后。
我发现配置中没有任何错误。我只错过了一件事。我必须在
{“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)
您可以将文件解码为字符串,然后将对象作为format=json发送吗?文件里有什么?这里讨论的是正确的解析器吗?@SamRedway我从来没有这样做过。谢谢你的回复。这应该是一个古老的问题,但我找不到解决办法。@andi让我花时间阅读和消化一下。