Beispiel #1
0
    def validate(self, value):
        """
        Validate that the file is of supported extension and/or type.
        """
        super(TypedFileField, self).validate(value)
        if value in self.empty_values:
            return None

        # make sure the extension is correct
        ext = pathlib.Path(value.name).name.split('.', 1)[-1]
        if self.ext_whitelist and ext not in self.ext_whitelist:
            raise forms.ValidationError(self.error_messages['extension'])

        # getting mimetype of a file could use some resources
        # so if we don't need to check mimetype, we can return faster
        if not self.type_whitelist:
            return value

        # get the mimetype from the UploadedFile
        if self.use_magic:
            try:
                mimetype = get_content_type(value)
            except Exception:
                raise forms.ValidationError(self.error_messages['invalid'])

        else:
            try:
                mimetype = value.content_type
            except AttributeError:
                raise forms.ValidationError(self.error_messages['invalid'])

        # make sure the mimetype is correct
        if mimetype not in self.type_whitelist:
            raise forms.ValidationError(self.error_messages['mimetype'])

        return value
def test_get_content_type_file(mock_get_content_type_from_binary, mock_get_content_type_from_file):
    actual = get_content_type(mock.sentinel.file)

    assert actual == mock_get_content_type_from_file.return_value
    mock_get_content_type_from_file.assert_called_once_with(mock.sentinel.file)
    assert not mock_get_content_type_from_binary.called
def test_get_content_type_binary(mock_get_content_type_from_binary, mock_get_content_type_from_file):
    actual = get_content_type(b'foo')

    assert actual == mock_get_content_type_from_binary.return_value
    mock_get_content_type_from_binary.assert_called_once_with(b'foo')
    assert not mock_get_content_type_from_file.called