如何使用PUT在Django rest框架中测试文件上传?

时间:2017-06-15 12:09:30

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

我想为Django REST Framework应用程序的视图编写单元测试。测试应该使用PUT上传文件,本质上相当于

  

http -a malkarouri PUT http://localhost:8000/data-packages/upload/ka @ tmp / hello.py

到目前为止我写的代码是

factory = APIRequestFactory()
request = factory.put(                                                                                                                                                                '/data-packages/upload/ka',
    data,
    content_type='application/octet-stream',
    content_disposition="attachment; filename=data.dump")
force_authenticate(request, user)
view = PackageView.as_view()
response = view(request, "k.py")
显然,

不上传文件。运行测试时的具体错误是400:

  

{u'detail':u'Missing filename。请求应包含带有文件名参数的Content-Disposition标头。'}

值得注意的是,我正在使用请求工厂来测试视图而不是完整的客户端。这就是使this question中的解决方案不适合我的原因。

设置内容处置标题的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

您好需要使用SimpleUploadedFile包装器:

from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.files import File

data = File(open('path/bond-data.dump', 'rb'))
upload_file = SimpleUploadedFile('data.dump', data.read(),content_type='multipart/form-data')
request = factory.put( '/data-packages/upload/ka',
   {'file':upload_file,other_params},
    content_type='application/octet-stream',
    content_disposition="attachment; filename=data.dump")

Ps:我正在使用APITestCase

答案 1 :(得分:0)

from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase

from rest_framework.test import APIClient


class MyTest(TestCase):
    client_class = APIClient

    def test_it(self):
        file = SimpleUploadedFile("file.txt", b"abc", content_type="text/plain")
        payload = {"file": file}
        response = self.client.post("/some/api/path/", payload, format="multipart")
        self.assertEqual(response.status_code, 201)

        # If you do more calls in this method with the same file then seek to zero
        file.seek(0)