Search code examples
pythondjangodjango-testing

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)

Solution

  • Thanks to help from Eduardo, I was able to get a working solution.

    from StringIO import StringIO
    import Image
    
    file = StringIO()
    image = Image.new("RGBA", size=(50,50), color=(256,0,0))
    image.save(file, 'png')
    file.name = 'test.png'
    file.seek(0)