使用 UploadedFile 测试视图集
Testing viewsets with UploadedFile
我正在尝试测试一个特定的视图集视图,它采用 formData
,其中包含一个 csv
文件。我的测试如下所示:
@staticmethod
def _create_file(rows: List[List[Any]], content_type: str = 'text/csv') -> UploadedFile:
f = StringIO()
csv.writer(f).writerows(rows)
return UploadedFile(file=f.read(), name='test.csv', content_type=content_type)
def test_upload_valid(self):
""" Asserts that the upload view works correctly with valid information. """
response = self.client.post(reverse('core_api:upload-upload'), {
'file_type': self.file_type,
'file': self._create_file([['Test', 'Test', 'Test', 'Test'], [1, 'Test', 'tokyo', 2]])
})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.content['process_status'], DemoConsumerDataParser.SUCCESS_STATUS)
self.assertEqual(len(response.content['errors']), 0)
但是这里失败了:
'file': self._create_file([self.header, self.acceptable_row])
出现以下错误:
AttributeError: 'str' object has no attribute 'read'
如何修改 post 以使其正确发送此文件?
所以我通过使用 SimpleUploadedFile
解决了这个问题,但我不确定为什么会这样:
@staticmethod
def _create_file(rows: List[List[Any]]) -> SimpleUploadedFile:
f = StringIO()
csv.writer(f).writerows(rows)
file = SimpleUploadedFile('test.csv', f.getvalue().encode(), content_type='text/csv')
f.close()
return file
我正在尝试测试一个特定的视图集视图,它采用 formData
,其中包含一个 csv
文件。我的测试如下所示:
@staticmethod
def _create_file(rows: List[List[Any]], content_type: str = 'text/csv') -> UploadedFile:
f = StringIO()
csv.writer(f).writerows(rows)
return UploadedFile(file=f.read(), name='test.csv', content_type=content_type)
def test_upload_valid(self):
""" Asserts that the upload view works correctly with valid information. """
response = self.client.post(reverse('core_api:upload-upload'), {
'file_type': self.file_type,
'file': self._create_file([['Test', 'Test', 'Test', 'Test'], [1, 'Test', 'tokyo', 2]])
})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.content['process_status'], DemoConsumerDataParser.SUCCESS_STATUS)
self.assertEqual(len(response.content['errors']), 0)
但是这里失败了:
'file': self._create_file([self.header, self.acceptable_row])
出现以下错误:
AttributeError: 'str' object has no attribute 'read'
如何修改 post 以使其正确发送此文件?
所以我通过使用 SimpleUploadedFile
解决了这个问题,但我不确定为什么会这样:
@staticmethod
def _create_file(rows: List[List[Any]]) -> SimpleUploadedFile:
f = StringIO()
csv.writer(f).writerows(rows)
file = SimpleUploadedFile('test.csv', f.getvalue().encode(), content_type='text/csv')
f.close()
return file