Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate in-memory image for Django testing

Is it possible to generate an in-memory image for testing purposes?

Here is my current code:

  def test_issue_add_post(self):
        url = reverse('issues_issue_add')
        image = 'cover.jpg'
        data = {
            'title': 'Flying Cars',
            'cover': image,
        }
        response = self.client.post(url, data)
        self.assertEqual(response.status_code, 302)
like image 992
Jason Christa Avatar asked Dec 23 '11 02:12

Jason Christa


2 Answers

Jason's accepted answer is not working for me in Django 1.5

Assuming the generated file is to be saved to a model's ImageField from within a unit test, I needed to take it a step further by creating a ContentFile to get it to work:

from PIL import Image
from StringIO import StringIO

from django.core.files.base import ContentFile

image_file = StringIO()
image = Image.new('RGBA', size=(50,50), color=(256,0,0))
image.save(image_file, 'png')
image_file.seek(0)

django_friendly_file = ContentFile(image_file.read(), 'test.png')
like image 96
dshap Avatar answered Oct 17 '22 13:10

dshap


In Python 3

from io import BytesIO
from PIL import Image

image = Image.new('RGBA', size=(50, 50), color=(155, 0, 0))
file = BytesIO(image.tobytes())
file.name = 'test.png'
file.seek(0)
#  + + + django_friendly_file = ContentFile(file.read(), 'test.png') # year 2019, django 2.2.1  -works 
like image 34
Marc Tudurí Avatar answered Oct 17 '22 11:10

Marc Tudurí