0

I have a model that contains a FileField which may not be blank. When creating tests for this model, I've run into the problem that I get errors when testing with PUT, while the exact same thing works when doing a POST. As views I'm simply using generics.ListCreateAPIView for the POST destination and generics.RetrieveUpdateDestroyAPIView for the PUT destination, both work normally when using the API in browser.

The payload for the POST and PUT is created as follows:

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

Then the working POST test looks as follows:

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

And the PUT:

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

The POST returns 204 and creates a new object, while the PUT returns 415 with the following error:

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

I am unsure what is going wrong here, it seems that both the post and put are passing the SimpleUploadedFile data in the same way, though with put it somehow becomes an octet stream.

Nycrea
  • 1
  • 1

1 Answers1

0

I figured out the problem Django's django.test.Client class does not support the 'PUT' method. Instead the REST framework provides the class rest_framework.test.APIClient, which does support PUT (and PATCH, etc).

The client.put() function now needs to be filled in a little differently (I was unable to get it to work with SimpleUploadedFile) as explained here: https://fodra.github.io/2017/05/31/testing-django-rest-api-with-image-field.html

Nycrea
  • 1
  • 1
  • [django.test.Client.put documentation...](https://docs.djangoproject.com/en/3.1/topics/testing/tools/#django.test.Client.put) – djvg Sep 17 '20 at 19:46