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

2024-05-20 23:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为Django REST框架应用程序的视图编写一个单元测试。测试应该使用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. Request should include a Content-Disposition header with a filename parameter.'}

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

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


Tags: 文件djangopyview视图httpdataput
2条回答

嗨,您需要使用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

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)

相关问题 更多 >