我尝试使用Django rest框架测试文件上传,但是request.data
为空
测试:
def test_update_story_cover(self):
auth_token, story_id = self.create_story()
image_path = os.path.join(os.path.dirname(__file__), 'book.jpg')
url = reverse('story_modify', kwargs={'pk': story_id})
with open(image_path) as cover:
response = self.client.patch(
url, data={'cover': cover, 'title': 'test title'},
content_type='multipart/form-data',
HTTP_AUTHORIZATION=auth_token)
self.assertEqual(response.status_code, status.HTTP_200_OK)
视图:
class StoryModifyView(RetrieveUpdateDestroyAPIView):
...
def update(self, request, *args, **kwargs):
print(request.data)
print(request.FILES)
print(request.body)
...
输出为
<QueryDict: {}> {}
<MultiValueDict: {}>
b"{'cover': <_io.TextIOWrapper name='/some-path/stories/tests/test_stories/books.jpg' mode='r' encoding='UTF-8'>, 'title': 'test title'}"
真正的前端可以成功上传图像,并且request.data
不为空,因此我认为测试中有问题。
答案 0 :(得分:1)
这应该有效
from rest_framework.test import APIClient
def test_update_story_cover(self):
client = APIClient()
auth_token, story_id = self.create_story()
image_path = os.path.join(os.path.dirname(__file__), 'book.jpg')
url = reverse('story_modify', kwargs={'pk': story_id})
with open(image_path, 'rb') as cover:
response = client.patch(
path=url, data={'cover': cover, 'title': 'test title'},
format='multipart',
HTTP_AUTHORIZATION=auth_token)
self.assertEqual(response.status_code, status.HTTP_200_OK)