0

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 model instance (Photo) a UnicodeDecodeError is raised.

ERROR: setUpClass (photos.tests.test_models.TestPhotoModel)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\..\..\..\..\..\venv\lib\site-packages\django\test\testcases.py", line 1137, in setUpClass
    cls.setUpTestData()
  File "C:\..\..\..\..\..\photos\tests\test_models.py", line 23, in setUpTestData
    content=open(file.read(), 'rb')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

I cannot figure out why this error is being raised. How can this be addressed so the test can run properly?

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)
binny
  • 649
  • 1
  • 8
  • 22
  • You are trying to read a PNG as the file name? – Klaus D. Sep 27 '20 at 03:48
  • Yes. I'm modelling this after reading these topics. https://stackoverflow.com/questions/26298821/django-testing-model-with-imagefield https://stackoverflow.com/questions/26141786/django-1-7-imagefield-form-validation – binny Sep 27 '20 at 03:56
  • What do you think `open(file.read(), 'rb')` does? – Klaus D. Sep 27 '20 at 03:57
  • `file.read()` reads the bytes stored in the `io.BytesIO` instance. So is `open()` redundant then? – binny Sep 27 '20 at 04:19
  • `open()` take a file **name** as argument and returns a file descriptor. What do you have to supply to the `Photo` class? – Klaus D. Sep 27 '20 at 04:25

0 Answers0