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
        def setUpTestData(cls):
            f = BytesIO()
            image ="RGB", (100, 100))
  , 'png')
            test_image = SimpleUploadedFile(
                content=open(, 'rb'),
            user = User.objects.create_user("User")
            import pdb; pdb.set_trace()
            form = PhotoForm({'title': "Image Title"}, {'source': test_image})
            instance =
            instance.photographer = user
            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(
    +  ,
    -            content=open(, 'rb'),

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


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


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