Generating an in memory image for tests in Python

Published: 27 February 2014

When writing tests for Django models that use ImageFields, it is often cumbersome to create a real file on the disk for every test case. Instead, it is much cleaner to generate an in-memory image.

You can achieve this using the Python io library and the PIL (Pillow) library. Here is a common pattern for generating a simple placeholder image:

from io import BytesIO
from PIL import Image
from django.core.files.base import File

def get_test_image():
    file = BytesIO()
    image = Image.new('RGBA', size=(100, 100), color=(155, 0, 0))
    image.save(file, 'png')
    file.name = 'test.png'
    file.seek(0)
    return File(file)

By using this helper in your setUp methods or factories, you avoid cluttering your repository with temp files that are only used during the test suite execution.