Wildfish logo
Wildfish logo

GET IN TOUCH

27 February 2014Rolo Mawlabaux

Generating an in memory image for tests in Python

  • django test
  • in memory
  • python
Generating an in memory image for tests in Python

Sometimes it's handy to be able to generate an in memory image in your tests. This is faster than using an image from the filesystem, but the biggest benefit for me is not needing to spend ages wondering where exactly in your project you should store your single test image.

It wasn't obvious to me how to do this, but here's a snippet for anyone who wants it. I've tested this using Pillow (I guess it would work with PIL) with both Python 2.7 and Python 3 (3.3).

from io import BytesIO
from PIL import Image

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

In my WebTest Django form test, I'd use it something like this:

form = response.forms['some_form']
form['picture'] = ('picture', create_test_image().read())
form.submit()
You must accept cookies and allow javascript to view and post comments
Wildfish logo

GET IN TOUCH!

We really are quite an approachable bunch! Simply give us a call or email. Alternatively if you’d prefer, drop into the office for a chat!