11

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

http -a malkaouri 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'缺少文件名。请求应包含带有文件名参数的 Content-Disposition 标头。'}

值得注意的是,我使用的是请求工厂来测试视图,而不是完整的客户端。这就是使诸如此问题中的解决方案之类的解决方案对我不起作用的原因。

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

4

2 回答 2

9

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

于 2017-06-15T12:21:11.423 回答
5
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)
于 2019-08-07T18:31:51.597 回答