Skip to content

Unit testing file uploads does not populate request.FILES #1347

@w00kie

Description

@w00kie

Hi, I'm having issues with my unit-testing on file uploads.

I have the following unit-test using the APIClient provided by APITestCase:

@override_settings(MEDIA_ROOT='/tmp/django_test')
def test_attach_file_to_deed(self):
    self._require_login()
    response = self.client.post(
        '/api/deeds/%s/attach_file/' % (self.test_deed.pk, ),
        {
            'file': self.dummyfile,
        },
    )
    self.assertqual(response.status_code, status.HTTP_201_CREATED, 'Error on create.')

But it fails to populate the request.FILES['file'] in the view and gives me the following error:

django.utils.datastructures.MultiValueDictKeyError: "'file'"

My view looks like this:

@action()
def attach_file(self, request, pk=None):
    deed = self.get_object()
    serializer = AttachmentSerializer(
        data={
            'parent': deed.pk,
            'file': request.FILES['file'],
            'original_filename': request.FILES['file'].name,
        },
    )
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

I could really use a little help debugging this one.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions