使用UploadedFile测试视图集

时间:2019-05-03 14:36:10

标签: python django django-rest-framework python-unittest

我正在尝试测试一个包含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'

如何修改帖子,以使其正确发送此文件?

1 个答案:

答案 0 :(得分:0)

所以我已经通过使用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