生成内存中图像以进行 Django 测试
是否可以生成内存中图像用于测试目的?
这是我当前的代码:
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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
要生成纯红色的 200x200 测试图像:
要将其转换为类似文件的对象,则:
http:// /effbot.org/imagingbook/image.htm
To generate a 200x200 test image of solid red:
To convert it to a file-like object, then:
http://effbot.org/imagingbook/image.htm
Jason 接受的答案在 Django 1.5 中对我不起作用
假设生成的文件要从单元测试中保存到模型的
ImageField
中,我需要通过创建一个来更进一步ContentFile
使其正常工作: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 aContentFile
to get it to work:因此,如果 client.post 需要一个类似对象的文件,您可以创建一个示例图像(如果您想在测试后直观地检查结果),或者只是制作一个 1px png 并从控制台中读出它,
在我的情况下,控制台将其转储出来,
然后您可以使用 StringIO 充当类似文件的对象,因此上面的图像将是
,并且您将拥有一个带有图像数据的类似文件的对象
So if client.post is expecting a file like object, you could create an example image (if you want to visually check result after tests) or just make a 1px png and read it out from console
which in my case dumped out
then you can use StringIO which acts as a file like object, so above, image would be
and you'll have a file like object with the image data
在Python 3中
In Python 3
感谢爱德华多的帮助,我找到了一个可行的解决方案。
Thanks to help from Eduardo, I was able to get a working solution.
你用过PIL模块吗?它可以让你操作图像 - 并且也应该允许创建。
事实上,这是一个博客条目,其中包含一些代码
http://bradmontgomery.blogspot.com/2008/07 /django-generate-image-with-pil.html
不知道你的测试机器是否有互联网连接,但你也可以从谷歌拉下随机图像来改变测试 数据?
Have you used the PIL module? It lets you manipulate images - and should allow creation as well.
In fact, here's a blog entry with some code that does it
http://bradmontgomery.blogspot.com/2008/07/django-generating-image-with-pil.html
Dont know whether you test machine has an internet connection, but you could also pull down random images from google to vary the test data?