![]() |
open(file, 'rb') raises UnicodeDecodeError - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: open(file, 'rb') raises UnicodeDecodeError (/thread-29956.html) |
open(file, 'rb') raises UnicodeDecodeError - binnybit - Sep-27-2020 I'm creating a project with Django that involves user uploading images. To test for an image and how it's stored in Django's default storage, I'm using the combination of SimpleUploadedFile, io.BytesIO(), and the Pillow Image class. When I test for the successful creation of a Django model instance (Photo) a UnicodeDecodeError is raised. I've gone over the Python docs and read content on other forums that dealt with similar problems creating a mock image for testing purposes. I have had zero luck resolving this. What can be done to resolve this so that open() reads the BytesIO file successfully?
from io import BytesIO from unittest.mock import Mock, patch from django.test import TestCase from django.db.models import ImageField from django.core.files.uploadedfile import SimpleUploadedFile from PIL import Image from ..models import Photo class TestPhotoModel(TestCase): @classmethod def setUpTestData(cls): file = BytesIO() image = Image.new("RGB", (50, 50), 'red') image.save(file, "png") file.seek(0) data = { 'title': "Title", 'image': SimpleUploadedFile( 'test_image.png', content=open(file.read(), 'rb') ) } cls.new_photo = Photo.objects.create(**data) def test_photo_instance_created(self): total_photos = Photo.objects.count() self.assertEqual(total_photos, 1) RE: open(file, 'rb') raises UnicodeDecodeError - Gribouillis - Sep-28-2020 Perhaps you mean content=file.getvalue()
|