Search code examples
djangounit-testingmime-types

Django unit testing - is it possible to specify a mime-type for file upload?


I have a Django (1.11) site that allows media file uploads. I have some basic checking against mime types (eg. to just accept 'video/m4v' files).

This checking works fine when I use the site on my browser (through the web UI) - running through python manage.py runserver.

I'm now writing some unit tests, but am finding that whatever file type I post, it's always picked up as an application/octet-stream mime type.

My unit test code is as follows:

media_file = open('sample_video.m4v','rb') 
self.client.login(username='admin', password='password')
response = self.client.post(reverse('oppia_av_upload'), {'media_file': media_file })
self.assertEqual(response.status_code, 200)

In the self.client.post command, is there a way I can specify the mime type so that it's picked up correctly?

For info, I'm aware that mime types can be 'fiddled' with, so it won't be a guarantee that the file is of the type it claims.

Any help much appreciated.

Edit: Just to include the file upload checking code in the form validation, in case there is something I'm doing incorrectly here:

def clean(self):
        cleaned_data = super(UploadMediaForm, self).clean()
        media_file = cleaned_data.get("media_file")
        print(media_file.content_type)
        if media_file is not None and media_file.content_type not in settings.OPPIA_MEDIA_FILE_TYPES:
            raise forms.ValidationError(_(u"You may only upload a media file which is one of the following types: %s" % ', '.join(settings.OPPIA_MEDIA_FILE_TYPES)))

Solution

  • You could perhaps make use of Django's SimpleUploadedFile. That allows you to attach the content type to the file. For example:

    from django.core.files.uploadedfile import SimpleUploadedFile
    
    filename = 'sample_video.m4v'
    with open(filename,'rb') as f:
        media_file =  SimpleUploadedFile(filename, f, content_type="video/m4v")
        self.client.login(username='admin', password='password')
        response = self.client.post(reverse('oppia_av_upload'), {'media_file': media_file })
        self.assertEqual(response.status_code, 200)