Mock image raising error; invalid image or corrupt

I’m having difficulty successfully creating a mock image for my TestCase. I’ve referenced these topics in guiding my efforts to do so, but still failing creating it. The error exactly being raised is:

  • source
    • Upload a valid image. The file you uploaded was either not an image or a corrupted image.
  • .

    An alternative I tried was using io.BytesIO.getvalue() on the BytesIO object but got the same error when the content parameter was changed to content=f.getvalue()

    I’m hitting a wall as to what else I can do to fix this.

    from io import BytesIO
    
    from django.test import TestCase
    from django.contrib.auth.models import User
    from ..forms import PhotoForm
    
    from PIL import Image
    
    from ..models import Photo
    
    from django.core.exceptions import ValidationError
    from django.core.files.uploadedfile import SimpleUploadedFile
    
        @classmethod
        def setUpTestData(cls):
            f = BytesIO()
            image = Image.new("RGB", (100, 100))
            image.save(f, 'png')
            f.seek(0)
            test_image = SimpleUploadedFile(
                "test_image.png",
                content=open(f.read(), 'rb'),
            )
            user = User.objects.create_user("User")
            import pdb; pdb.set_trace()
            form = PhotoForm({'title': "Image Title"}, {'source': test_image})
            instance = form.save(commit=False)
            instance.photographer = user
            instance.save()
    
            cls.submitted_form = PhotoForm(
                {'title': "Image Title"}, {'source': test_image}
            )
    
    

    It seems to me that you need to change the way you’re reading the image.

    test_image = SimpleUploadedFile(
                "test_image.png",
    +            content=f.read(),
    -            content=open(f.read(), 'rb'),
            )
    

    I don’t know with certainty the explanation but I made some tests in the console just to be sure.

    Wrong

    In [39]: open(im_io.read(), 'rb')
    -----------------------------------------------------------------------                            
    Traceback (most recent call last)
    <ipython-input-39-653afec5dca6> in <module>
    ----> 1 open(im_io.read(), 'rb')
    
    ValueError: embedded null byte
    

    Correct

    In [18] f = BytesIO()
       ...: image = Image.new(mode='RGB', size=(100, 100))
       ...: image.save(f, 'png')
       ...: f.seek(0)
    Out[19]: 0
    
    In [20]: test_image = SimpleUploadedFile(
        ...: "image.png",
        ...: f.read(),
        ...: )
    
    In [21]: test_image
    Out[21]: <SimpleUploadedFile: image.png (text/plain)>