Django + solr.thumbnail:get_thumbnail() 在测试环境中失败

Mic*_*icE 5 python testing django sorl-thumbnail

我正在尝试找到一种在使用 Django 和 的sorl-thumbnail方法时测试缩略图生成的方法get_thumbnail()

环境:

Django==1.5.5
Pillow==2.1.0
sorl-thumbnail==11.12
Run Code Online (Sandbox Code Playgroud)

测试中的简化代码(在测试环境中运行):

from StringIO import StringIO
from PIL import Image

from django.conf import settings
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.db import models
from sorl.thumbnail import get_thumbnail

# simple class with ImageField
class User(models.Model):
    avatar = models.ImageField(upload_to='avatars', default=None, null=True, blank=True)

    def get_thumbnail_uri(self):
        avatar_thumbnail = get_thumbnail(self.avatar, '100x100')

        return avatar_thumbnail.url

# make sure we're using in-memory test env.
assert settings.THUMBNAIL_STORAGE  == 'inmemorystorage.InMemoryStorage'
assert settings.DEFAULT_FILE_STORAGE == 'inmemorystorage.InMemoryStorage'

# prepare image
fake_file = StringIO()

picture = Image.new(mode='RGBA', size=(500, 500), color=(255, 0, 0, 0))
picture.save(fake_file, 'JPEG')

fake_file.name = 'test.jpg'
fake_file.seek(0)

uploaded_image = InMemoryUploadedFile(fake_file, field_name=None, name='test.jpg',
                                      content_type='image/jpeg', size=fake_file.len,
                                      charset=None)

# add image to user
u = User()
u.avatar = uploaded_image

assert u.get_thumbnail_uri() is not None
Run Code Online (Sandbox Code Playgroud)

上面的代码总是在最后一行失败:

Traceback (most recent call last):
  File "/vagrant/path/to/file.py", line 1440, in test_stackprep
    assert u.get_thumbnail_uri() is not None
  File "/vagrant/path/to/file.py", line 1413, in get_thumbnail_uri
    avatar_thumbnail = get_thumbnail(self.avatar, '100x100')
  File "/home/vagrant/.virtualenv/appname/local/lib/python2.7/site-packages/sorl/thumbnail/shortcuts.py", line 8, in get_thumbnail
    return default.backend.get_thumbnail(file_, geometry_string, **options)
  File "/home/vagrant/.virtualenv/appname/local/lib/python2.7/site-packages/sorl/thumbnail/base.py", line 56, in get_thumbnail
    source_image = default.engine.get_image(source)
  File "/home/vagrant/.virtualenv/appname/local/lib/python2.7/site-packages/sorl/thumbnail/engines/pil_engine.py", line 13, in get_image
    return Image.open(buf)
  File "/home/vagrant/.virtualenv/appname/local/lib/python2.7/site-packages/PIL/Image.py", line 2008, in open
    raise IOError("cannot identify image file")
IOError: cannot identify image file
Run Code Online (Sandbox Code Playgroud)

inmemorystorage我假设 Django 或 sorl-thumbnail在运行测试时退出。我已经研究了很长时间,但除了直接在文件系统上测试东西(我想避免)之外,我找不到任何有效的配置。

请问有人设法让 sorl 的get_thumbnail()方法在测试中起作用吗?

谢谢。

Ond*_*ták 3

版本11.12是今天 PyPI 上的最新版本,已经有 2 岁了。存储库中有12.0可用的版本,应该可以工作。它不在 PyPI 上,因为维护者发生了变化,我猜他们还没有机会这样做。

我已经尝试过主版本,它与您的示例一起工作正常。