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

vwr*_*bel 5 django django-testing django-rest-framework

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

#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)
Run Code Online (Sandbox Code Playgroud)

#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))
Run Code Online (Sandbox Code Playgroud)

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

由于未上载文件,测试失败.在def putviews.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上提出了与此问题相近的问题,但我对提议的答案没有成功.

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

vwr*_*bel 6

现在好了!从APIRequestFactory切换到APIClient,我设法让我的测试运行.

我的新test.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))
Run Code Online (Sandbox Code Playgroud)