为Django测试生成内存图像

13 投票
6 回答
6339 浏览
提问于 2025-04-17 08:53

有没有办法生成一个内存中的图像来做测试呢?

这是我现在的代码:

  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)

6 个回答

14

Jason的答案在我使用Django 1.5时不管用。

假设我生成的文件是要保存在一个模型的ImageField里,并且是在单元测试中进行的,我需要进一步操作,创建一个ContentFile才能让它正常工作:

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')
15

要生成一个200x200像素的纯红色测试图像:

import Image
size = (200,200)
color = (255,0,0,0)
img = Image.new("RGBA",size,color)

接下来,要把它转换成一个像文件一样的对象,可以这样做:

import StringIO
f = StringIO.StringIO(img.tostring())

http://effbot.org/imagingbook/image.htm

1

多亏了Eduardo的帮助,我终于找到了一个可行的解决方案。

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)

撰写回答