gpt4 book ai didi

django - 如何使用 Django REST Framework 的 APIRequestFactory 生成文件上传(测试)请求?

转载 作者:行者123 更新时间:2023-12-02 05:14:22 26 4
gpt4 key购买 nike

我开发了一个 API(Python 3.5、Django 1.10、DRF 3.4.2),当我从 UI 请求视频文件时,该 API 会将视频文件上传到我的媒体路径。那部分工作正常。我尝试为此功能编写测试,但无法使其成功运行。

#views.py

import os
from rest_framework import views, parsers, response
from django.conf import settings


class FileUploadView(views.APIView):
parser_classes = (parsers.FileUploadParser,)
def put(self, request, filename):
file = request.data['file']
handle_uploaded_file(file, filename)
return response.Response(status=204)

def handle_uploaded_file(file, filename):
dir_name = settings.MEDIA_ROOT + '/scene/' + filename + '/cam1'
new_filename = 'orig.mp4'
if not os.path.exists(dir_name):
os.makedirs(dir_name)
file_path = os.path.join(dir_name, new_filename)
with open(file_path, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)

#test.py

import tempfile
import os
from django.test import TestCase
from django.conf import settings
from django.core.files import File
from django.core.files.uploadedfile import SimpleUploadedFile
from rest_framework.test import APIRequestFactory
from myapp.views import FileUploadView


class UploadVideoTestCase(TestCase):
def setUp(self):
settings.MEDIA_ROOT = tempfile.mkdtemp(suffix=None, prefix=None, dir=None)

def test_video_uploaded(self):
"""Video uploaded"""
filename = 'vid'
file = File(open('media/testfiles/vid.mp4', 'rb'))
uploaded_file = SimpleUploadedFile(filename, file.read(), 'video')
factory = APIRequestFactory()
request = factory.put('file_upload/'+filename,
{'file': uploaded_file}, format='multipart')
view = FileUploadView.as_view()
response = view(request, filename)
print(response)

dir_name = settings.MEDIA_ROOT + '/scene/' + filename + '/cam1'
new_filename = 'orig.mp4'
file_path = os.path.join(dir_name, new_filename)
self.assertTrue(os.path.exists(file_path))

在此测试中,我需要使用现有的视频文件('media/testfiles/vid.mp4')并上传它,因为我需要在之后测试视频数据的一些处理:这就是我重置MEDIA_ROOT的原因使用mkdtemp .

由于文件未上传,测试失败。在 def put我的views.py ,当我打印request时我得到<rest_framework.request.Request object at 0x10f25f048>当我打印request.data时我什么也没得到。但是如果我删除 FileUploadParser在我看来并使用request = factory.put('file_upload/' + filename, {'filename': filename}, format="multipart")在我的测试中,我得到 <QueryDict: {'filename': ['vid']}>当我打印request.data时.

所以我的结论是我用 APIRequestFactory 生成的请求是不正确的。 FileUploadParser无法从中检索原始文件。

因此我的问题是:如何使用 Django REST Framework 的 APIRequestFactory 生成文件上传(测试)请求?

有几个人在 SO 上提出了与此类似的问题,但我对建议的答案没有成功。

任何有关此事的帮助将不胜感激!

最佳答案

现在没事了!从 APIRequestFactory 切换到 APIClient,我成功地运行了测试。

我的新测试.py:

import os
import tempfile
from django.conf import settings
from django.core.files import File
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
from rest_framework.test import APITestCase, APIClient
from django.contrib.auth.models import User

class UploadVideoTestCase(APITestCase):
def setUp(self):
settings.MEDIA_ROOT = tempfile.mkdtemp()
User.objects.create_user('michel')

def test_video_uploaded(self):
"""Video uploaded"""
filename = 'vid'
file = File(open('media/testfiles/vid.mp4', 'rb'))
uploaded_file = SimpleUploadedFile(filename, file.read(),
content_type='multipart/form-data')
client = APIClient()
user = User.objects.get(username='michel')
client.force_authenticate(user=user)
url = reverse('file_upload:upload_view', kwargs={'filename': filename})
client.put(url, {'file': uploaded_file}, format='multipart')
dir_name = settings.MEDIA_ROOT + '/scene/' + filename + '/cam1'
new_filename = 'orig.mp4'
file_path = os.path.join(dir_name, new_filename)
self.assertTrue(os.path.exists(file_path))

关于django - 如何使用 Django REST Framework 的 APIRequestFactory 生成文件上传(测试)请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40453947/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com