示例#1
0
 def test_get_contenttype(self):
     self.assertEqual(
         get_contenttype(
             NamedImage(getFile('image.gif').read(),
                        contentType='image/gif')), 'image/gif')
     self.assertEqual(
         get_contenttype(
             NamedImage(getFile('image.gif').read(),
                        filename=u'image.gif')), 'image/gif')
     self.assertEqual(
         get_contenttype(
             NamedImage(getFile('notimage.doc').read(),
                        filename=u'notimage.doc')), 'application/msword')
    def test_namedimage_field_serialization_doesnt_choke_on_corrupt_image(
            self):
        """ In Plone >= 5.2 the original image file is not a "scale", so its url
            is returned as is and we need to check it, but the scales should be empty"""
        image_data = b"INVALID IMAGE DATA"
        fn = "test_namedimage_field"
        with patch.object(storage, "uuid4", return_value="uuid_1"):
            value = self.serialize(
                fn,
                NamedImage(data=image_data,
                           contentType=u"image/gif",
                           filename=u"1024x768.gif"),
            )

        obj_url = self.doc1.absolute_url()
        scale_url_uuid = "uuid_1"
        self.assertEqual(
            {
                u"content-type":
                u"image/gif",
                u"download":
                u"{}/@@images/{}.{}".format(obj_url, scale_url_uuid, "gif"),
                u"filename":
                u"1024x768.gif",
                u"height":
                -1,
                u"scales": {},
                u"size":
                18,
                u"width":
                -1,
            },
            value,
        )
    def test_namedimage_field_serialization_doesnt_choke_on_corrupt_image(
            self):
        """ Original image url will be None because the original image is corrupted
            and the created url should be an image scale """
        image_data = b"INVALID IMAGE DATA"
        fn = "test_namedimage_field"
        with patch.object(storage, "uuid4", return_value="uuid_1"):
            value = self.serialize(
                fn,
                NamedImage(data=image_data,
                           contentType=u"image/gif",
                           filename=u"1024x768.gif"),
            )

        self.assertEqual(
            {
                u"content-type": u"image/gif",
                u"download": None,
                u"filename": u"1024x768.gif",
                u"height": -1,
                u"scales": {},
                u"size": 18,
                u"width": -1,
            },
            value,
        )
示例#4
0
 def afterSetUp(self):
     data = getFile('image.gif').read()
     item = DummyContent()
     item.image = NamedImage(data, 'image/gif', u'image.gif')
     self.app._setOb('item', item)
     self.item = self.app.item
     self.scaling = ImageScaling(self.app.item, None)
示例#5
0
    def test_namedimage_field_serialization_returns_dict(self):
        image_file = os.path.join(os.path.dirname(__file__), u'1024x768.gif')
        with open(image_file, 'rb') as f:
            image_data = f.read()
        fn = 'test_namedimage_field'
        with patch.object(storage, 'uuid4', return_value='uuid_1'):
            value = self.serialize(
                fn,
                NamedImage(
                    data=image_data,
                    contentType=u'image/gif',
                    filename=u'1024x768.gif'
                )
            )
            self.assertTrue(isinstance(value, dict), 'Not a <dict>')

            scale_url_uuid = 'uuid_1'
            obj_url = self.doc1.absolute_url()
            download_url = u'{}/@@images/{}.{}'.format(
                obj_url, scale_url_uuid, GIF_SCALE_FORMAT
            )
            scales = {
                u'listing': {
                    u'download': download_url,
                    u'width': 16,
                    u'height': 12},
                u'icon': {
                    u'download': download_url,
                    u'width': 32,
                    u'height': 24},
                u'tile': {
                    u'download': download_url,
                    u'width': 64,
                    u'height': 48},
                u'thumb': {
                    u'download': download_url,
                    u'width': 128,
                    u'height': 96},
                u'mini': {
                    u'download': download_url,
                    u'width': 200,
                    u'height': 150},
                u'preview': {
                    u'download': download_url,
                    u'width': 400,
                    u'height': 300},
                u'large': {
                    u'download': download_url,
                    u'width': 768,
                    u'height': 576},
            }
            self.assertEqual({
                u'filename': u'1024x768.gif',
                u'content-type': u'image/gif',
                u'size': 1514,
                u'download': download_url,
                u'width': 1024,
                u'height': 768,
                u'scales': scales},
                value)
    def create_demo_content(self):
        """Create a portal structure which we can test against.
        Plone (portal root)
        |-- image
        |-- about
            |-- team
            `-- contact
        """
        portal = self.layer["portal"]

        self.about = api.content.create(
            container=portal,
            type="Folder",
            id="about",
            title=u"About",
        )
        self.team = api.content.create(
            container=self.about,
            type="Document",
            id="team",
            title=u"Team",
        )
        self.contact = api.content.create(
            container=self.about,
            type="Document",
            id="contact",
            title=u"Contact",
        )
        self.image = api.content.create(
            container=portal,
            type="Image",
            title=u"Image",
            id="image",
            image=NamedImage(dummy.Image(), "image/gif", u"test.gif"),
        )
    def _makeDummyContent(self):
        from OFS.SimpleItem import SimpleItem

        class DummyContent(SimpleItem):
            def __init__(self, id):
                self.id = id

            def UID(self):
                return 'foo'

            allowedRolesAndUsers = ('Anonymous', )

        if HAS_NAMEDFILE:

            class DummyContent2(NFDummyContent):
                id = __name__ = title = 'foo2'

                def UID(self):
                    return 'foo2'

        dummy = DummyContent('foo')
        self.portal._setObject('foo', dummy)
        self.portal.portal_catalog.catalog_object(self.portal.foo)

        if HAS_NAMEDFILE:
            dummy2 = DummyContent2('foo2')
            data = open(join(PREFIX, 'image.jpg'), 'rb').read()
            dummy2.image = NamedImage(data, 'image/jpeg', u'image.jpeg')
            self.portal._setObject('foo2', dummy2)
            self.portal.portal_catalog.catalog_object(self.portal.foo2)
    def test_lead_image_render(self):
        from collective.geo.kml.browser import kmldocument
        from plone.namedfile.file import NamedBlobImage, NamedImage
        from plone.namedfile.tests.test_blobfile import registerUtilities
        from mock import Mock

        # get NamedBlobImage/NamedImage to work in this test
        registerUtilities()

        # so we don't need collective.contentleadimage for the test
        kmldocument.HAS_LEADIMAGE = True

        # we could use ATImage, but since that is deprecated, we just mock it
        class ATImage(object):
            def get_size(self, obj):
                return 1

            def tag(self, obj, scale, css_class):
                return '<img>'

        placemark = kmldocument.Placemark(self.portal, self.request)
        placemark.context.getField = Mock(return_value=ATImage())

        self.assertEqual(placemark.lead_image(), '<img>')

        # now let's try with NamedBlobImage and NamedImage
        placemark.context.getField = Mock(return_value=NamedImage())
        self.assertEqual(placemark.lead_image(), None)

        placemark.context.getField = Mock(return_value=NamedBlobImage())
        self.assertEqual(placemark.lead_image(), None)

        # or anything else really
        placemark.context.getField = Mock(return_value=object())
        self.assertEqual(placemark.lead_image(), None)
示例#9
0
    def setUp(self):

        self.portal = self.layer['portal']
        setRoles(self.portal, TEST_USER_ID, ['Manager'])
        self.portal.invokeFactory('Folder', 'media')
        self.folder = self.portal.media
        self.folder.invokeFactory(
            'Image',
            'image',
            title='Test Image')
        self.image_type = self.folder['image']
        self.image_type.image = NamedImage(
            getData('data/plone-app-caching.jpg'),
            'image/jpg',
            u'plone-app-caching.jpg')
        self.folder.invokeFactory(
            'File',
            'file',
            title=u'Töst File')
        self.file = self.folder['file']
        self.file.file = NamedFile(
            getData('data/testfile.csv'),
            'text/csv',
            u'data/töstfile.csv')

        setRoles(self.portal, TEST_USER_ID, TEST_USER_ROLES)
示例#10
0
    def test_namedimage_field_serialization_returns_dict(self):
        image_file = os.path.join(os.path.dirname(__file__), u'1024x768.gif')
        image_data = open(image_file, 'rb').read()
        fn = 'test_namedimage_field'
        value = self.serialize(
            fn,
            NamedImage(data=image_data,
                       contentType=u'image/gif',
                       filename=u'1024x768.gif'))
        self.assertTrue(isinstance(value, dict), 'Not a <dict>')

        obj_url = self.doc1.absolute_url()
        download_url = u'{}/@@images/{}'.format(obj_url, fn)
        scales = {
            u'listing': {
                u'download': u'{}/@@images/{}/listing'.format(obj_url, fn),
                u'width': 16,
                u'height': 12
            },
            u'icon': {
                u'download': u'{}/@@images/{}/icon'.format(obj_url, fn),
                u'width': 32,
                u'height': 24
            },
            u'tile': {
                u'download': u'{}/@@images/{}/tile'.format(obj_url, fn),
                u'width': 64,
                u'height': 48
            },
            u'thumb': {
                u'download': u'{}/@@images/{}/thumb'.format(obj_url, fn),
                u'width': 128,
                u'height': 96
            },
            u'mini': {
                u'download': u'{}/@@images/{}/mini'.format(obj_url, fn),
                u'width': 200,
                u'height': 150
            },
            u'preview': {
                u'download': u'{}/@@images/{}/preview'.format(obj_url, fn),
                u'width': 400,
                u'height': 300
            },
            u'large': {
                u'download': u'{}/@@images/{}/large'.format(obj_url, fn),
                u'width': 768,
                u'height': 576
            },
        }
        self.assertEqual(
            {
                u'filename': u'1024x768.gif',
                u'content-type': u'image/gif',
                u'size': 1514,
                u'download': download_url,
                u'width': 1024,
                u'height': 768,
                u'scales': scales
            }, value)
示例#11
0
 def setUp(self):
     data = getFile('image.png').read()
     item = DummyContent()
     item.image = NamedImage(data, 'image/png', u'image.png')
     self.layer['app']._setOb('item', item)
     self.item = self.layer['app'].item
     self.scaling = ImageScaling(self.item, None)
示例#12
0
 def addPersonsAndHeldPositions(self, person_descriptors, source):
     '''Creates persons and eventual held_positions.'''
     own_org = get_own_organization()
     container = own_org.aq_inner.aq_parent
     intids = getUtility(IIntIds)
     for person_descr in person_descriptors:
         # create the person
         person = api.content.create(container=container,
                                     type='person',
                                     **person_descr.getData())
         # person.photo is the name of the photo to use stored in /images
         if person.photo:
             photo_path = '%s/images/%s' % (source, person.photo)
             data = self.find_binary(photo_path)
             photo_file = NamedImage(data, filename=person.photo)
             person.photo = photo_file
             validate_fields(person, raise_on_errors=True)
         for held_pos_descr in person_descr.held_positions:
             # get the position
             data = held_pos_descr.getData()
             org = container.restrictedTraverse(data['position'])
             data['position'] = RelationValue(intids.getId(org))
             held_position = api.content.create(container=person,
                                                type='held_position',
                                                **data)
             validate_fields(held_position, raise_on_errors=True)
示例#13
0
    def testImageValidation(self):
        from plone.namedfile.field import InvalidImageFile
        from plone.namedfile.field import validate_image_field
        from plone.namedfile.interfaces import INamedImageField
        from zope.interface import implementer

        @implementer(INamedImageField)
        class FakeField(object):
            __name__ = 'logo'

        # field is empty
        validate_image_field(FakeField(), None)

        # field has an empty file
        image = self._makeImage()
        self.assertRaises(InvalidImageFile, validate_image_field, FakeField(),
                          image)

        # field has an image file
        image._setData(zptlogo)
        validate_image_field(FakeField(), image)

        notimage = NamedImage(getFile('notimage.doc'),
                              filename=u'notimage.doc')
        self.assertRaises(InvalidImageFile, validate_image_field, FakeField(),
                          notimage)
示例#14
0
    def _makeDummyContent(self):
        from OFS.SimpleItem import SimpleItem

        class DummyContent(SimpleItem):
            def __init__(self, id):
                self.id = id

            def UID(self):
                return 'foo'

            allowedRolesAndUsers = ('Anonymous', )

        class DummyContent2(NFDummyContent):
            id = __name__ = 'foo2'
            title = u'Schönes Bild'

            def UID(self):
                return 'foo2'

        dummy = DummyContent('foo')
        self.portal._setObject('foo', dummy)
        self.portal.portal_catalog.catalog_object(self.portal.foo)

        dummy2 = DummyContent2('foo2')
        with open(join(PREFIX, self.image_id), 'rb') as fd:
            data = fd.read()
            fd.close()
        dummy2.image = NamedImage(data, 'image/jpeg', u'image.jpeg')
        self.portal._setObject('foo2', dummy2)
        self.portal.portal_catalog.catalog_object(self.portal.foo2)
示例#15
0
 def afterSetUp(self):
     data = getFile('image.gif').read()
     item = DummyContent()
     item.image = NamedImage(data, 'image/gif', u'image.gif')
     self.app._setOb('item', item)
     self.item = self.app.item
     self.view = self.item.unrestrictedTraverse('@@images')
     self._orig_sizes = ImageScaling._sizes
示例#16
0
 def setUp(self):
     self.app = self.layer['app']
     data = getFile('image.png').read()
     item = DummyContent()
     item.image = NamedImage(data, 'image/png', u'image.png')
     self.app._setOb('item', item)
     self.item = self.app.item
     self._orig_sizes = ImageScaling._sizes
示例#17
0
 def uwo_logo(self):
     uwo_logo_data = api.portal.get_registry_record(
         'oiestudyabroadstudent.uwo_logo', )
     if uwo_logo_data is None or len(uwo_logo_data) == 0:
         return None
     filename, data = b64decode_file(uwo_logo_data)
     image = NamedImage(data=data, filename=filename)
     return image
 def get_attachment(self, filename, type):
     file_path = os.path.join(os.path.dirname(__file__), filename)
     with open(file_path, 'rb') as f:
         if api.env.plone_version() < '5.0':
             return f
         if type == 'image':
             return NamedImage(data=f, filename=filename)
         return NamedFile(data=f, filename=filename)
示例#19
0
    def __init__(self, context, request):
        super(FallBackImageView, self).__init__(context, request)

        record = ISocialLikeSettings.__identifier__ + '.fallback_image'
        fallback_image = api.portal.get_registry_record(record, default=None)

        if fallback_image is not None:
            # set fallback image data for download
            filename, data = b64decode_file(fallback_image)
            data = NamedImage(data=data, filename=filename)
            self.filename, self.data = filename, data
            # enable image caching for 2 minutes
            self.request.RESPONSE.setHeader('Cache-Control',
                                            'max-age=120, public')
        else:
            # resource no longer available
            self.data = NamedImage(data='')
            self.request.RESPONSE.setStatus(410)  # Gone
示例#20
0
    def with_dummy_image(self):
        dummy_image = StringIO(
            'GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00'
            '\x00!\xf9\x04\x04\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00'
            '\x01\x00\x00\x02\x02D\x01\x00;')

        self.arguments["image"] = NamedImage(dummy_image.read(),
                                                 filename=u"image.gif")
        return self
示例#21
0
 def testScaleInvalidation(self):
     # first get the scale of the original image
     self.scaling.available_sizes = {'foo': (23, 23)}
     foo1 = self.scaling.scale('image', scale='foo')
     # now upload a new one and make sure the scale has changed
     data = getFile('image.jpg').read()
     self.item.image = NamedImage(data, 'image/jpeg', u'image.jpg')
     foo2 = self.scaling.scale('image', scale='foo')
     self.failIf(foo1.data == foo2.data, 'scale not updated?')
示例#22
0
 def _getFile(self):
     data = self.get_data()
     if data:
         try:
             data = self.scale_data(data)
         except ValueError:
             logger.info('Error scaling favicon data', exc_info=True)
             raise NotFound
         return NamedImage(data=data, filename=self.filename)
示例#23
0
def _load_image(slider):
    from plone.namedfile.file import NamedImage
    filename = os.path.join(
        os.path.dirname(__file__),
        'theme',
        'img',
        'slide-{0}.jpg'.format(slider),
    )
    return NamedImage(data=open(filename, 'r').read(),
                      filename=u'slide-{0}.jpg'.format(slider))
示例#24
0
def _make_namedfile(value, field, widget):
    """Return a NamedImage or NamedFile instance, if it isn't already one -
    e.g. when it's base64 encoded data.
    """
    if isinstance(value, basestring) and IASCII.providedBy(field):
        filename, data = b64decode_file(value)
        if INamedImageWidget.providedBy(widget):
            value = NamedImage(data=data, filename=filename)
        else:
            value = NamedFile(data=data, filename=filename)
    return value
示例#25
0
def _load_image(slider):
    from plone.namedfile.file import NamedImage
    import os
    filename = os.path.join(
        os.path.dirname(__file__),
        'browser',
        'static',
        'slide_{0}.jpg'.format(slider),
    )
    return NamedImage(data=open(filename, 'r').read(),
                      filename=u'slide_{0}.jpg'.format(slider))
示例#26
0
    def setUpContent(self):
        super(LinkIntegrityDXLayer, self).setUpContent()

        with ploneSite() as portal:
            # Create an object that does not provide the behavior to live along
            create(portal, 'News Item', id='news1', title='News 1')

            # create a DX NamedImage
            portal.invokeFactory('Image', 'image1')
            portal['image1'].image = NamedImage(GIF, 'image/gif',
                                                u'sample.gif')
    def setUp(self):
        data = getFile('image.png').read()
        item = DummyContent()
        item.image = NamedImage(data, 'image/png', u'image.png')
        self.layer['app']._setOb('item', item)
        self.item = self.layer['app'].item
        self.view = self.item.unrestrictedTraverse('@@images')
        self._orig_sizes = ImageScaling._sizes

        self.browser = Browser(self.layer['app'])
        self.browser.handleErrors = False
        self.browser.addHeader('Referer', self.layer['app'].absolute_url())
示例#28
0
    def __init__(self, context, request):
        super(Logo, self).__init__(context, request)
        self.filename = None
        self.data = None

        registry = getUtility(IRegistry)
        settings = registry.forInterface(IPloneThemeSettings)  # noqa
        if getattr(settings, 'site_logo', False):
            filename, data = b64decode_file(settings.site_logo)
            data = NamedImage(data=data, filename=filename)
            self.data = data
            self.filename = filename
示例#29
0
    def __init__(self, context, request):
        super(PublisherLogoDownload, self).__init__(context, request)
        self.filename, self.data = None, None

        publisher_logo = api.portal.get_registry_record(
            IAMPSettings.__identifier__ + '.publisher_logo')

        if publisher_logo is not None:
            # set publisher logo data for download
            filename, data = b64decode_file(publisher_logo)
            data = NamedImage(data=data, filename=filename)
            self.filename, self.data = filename, data
示例#30
0
 def _getFile(self):
     scale = None
     if 'scale' in self.request.form:
         try:
             scale = int(self.request.form['scale'])
         except:
             pass
     data = self.get_data()
     if data:
         if scale is not None:
             data = self.scale_data(data, scale)
         return NamedImage(data=data, filename=self.filename)