Django REST框架FileField PUT测试用例

时间:2018-09-17 12:10:01

标签: django-rest-framework filefield django-unittest

我有一个包含FileField的模型,该FileField不能为空。在为此模型创建测试时,我遇到了一个问题,即使用PUT进行测试时会出错,而执行POST时完全相同。 作为视图,我只是将generics.ListCreateAPIView用作POST目标,将generics.RetrieveUpdateDestroyAPIView用作PUT目标,当在浏览器中使用API​​时,两者都可以正常工作。

POST和PUT的有效负载创建如下:

uploaded_file = SimpleUploadedFile('TestCode4.c', "Testcode", content_type='text/plain')
self.valid_payload = {
    'name': 'TestValid',
    'test_file': uploaded_file
}

然后正常工作的POST测试如下:

client = Client()
response = client.post(
    reverse('code-list'),
    self.valid_payload,
    format='json'
)

和PUT:

client = Client()
response = client.put(
    reverse('code-detail', kwargs={'pk': 1}),
    self.valid_payload,
    format='json'
)

POST返回204并创建一个新对象,而PUT返回415,但出现以下错误:

{u'detail': u'Unsupported media type "application/octet-stream" in request.'}

我不确定这是怎么回事,似乎post和put都以相同的方式传递SimpleUploadedFile数据,尽管put某种程度上变成了八位位组流。

1 个答案:

答案 0 :(得分:0)

我发现Django的django.test.Client类不支持'PUT'方法的问题。相反,REST框架提供了类rest_framework.test.APIClient,该类确实支持PUT(和PATCH等)。

client.put()函数现在需要以一些不同的方式填充(我无法使其与SimpleUploadedFile一起使用),如下所示:https://fodra.github.io/2017/05/31/testing-django-rest-api-with-image-field.html