Ejemplo n.º 1
0
    def test_attachment_tile(self):
        """This persistent tile renders a link pointing to a file stored in the
        tile data itself.

        """
        annotations = IAnnotations(self.page)
        annotations['plone.tiles.data.test'] = PersistentDict({
            'files': [
                NamedFile(u'Hello World!', 'text/plain', u'hello_world.txt'),
                NamedFile(u'Foobar!', 'text/plain', u'foobar.txt')
            ]
        })

        transaction.commit()

        self.browser.open(self.pageURL +
                          '/@@plone.app.standardtiles.attachment/test')

        self.assertIn(u'hello_world.txt', self.browser.contents)
        self.assertIn(u'foobar.txt', self.browser.contents)

        root = fromstring(self.browser.contents)
        nodes = root.xpath('//body//a')
        self.assertEqual(len(nodes), 2)

        self.browser.getLink(index=1).click()
        self.assertEqual(self.browser.contents, u'Foobar!')
Ejemplo n.º 2
0
 def createFile(self, path, title=None):
     obj = self._createObject('File', path, title=title)
     named_file = NamedFile()
     named_file.data = pdf_data
     named_file.filename = u'test.pdf'
     named_file.contentType = u'application/pdf'
     obj.file = named_file
     obj.reindexObject()
Ejemplo n.º 3
0
 def createFile(self, path, title=None):
     obj = self._createObject('File', path, title=title)
     named_file = NamedFile()
     named_file.data = pdf_data
     named_file.filename = u'test.pdf'
     named_file.contentType = u'application/pdf'
     obj.file = named_file
     obj.reindexObject()
Ejemplo n.º 4
0
    def test_validate_image(self):
        result = validate_image(None)
        self.assertEqual(None, result)

        image = NamedFile('dummy test data', filename=u'test.txt')
        self.assertRaises(Invalid, validate_image, image)

        image_path = path.join(path.dirname(__file__), 'data', 'test.png')
        image = open(image_path)
        image_data = image.read()
        image.close()
        image = NamedImage(image_data, filename=u'test.png')
        self.assertEqual(None, result)
Ejemplo n.º 5
0
    def test_xml_binary(self):

        from plone.namedfile import NamedFile

        img_data = open(os.path.join(os.path.dirname(__file__), 'sample.jpg'), 'rb').read()
        named_file = NamedFile()
        named_file.data = img_data
        named_file.filename = u'test.jpg'
        named_file.contentType = 'image/jpg'
        self.doc.xml_set('xml_binary', named_file)

        named_file2 = self.doc.xml_get('xml_binary')
        self.assertEqual(named_file2.data, img_data)
        self.assertEqual(named_file2.filename, u'test.jpg')
        self.assertEqual(named_file2.contentType, 'image/jpg')
Ejemplo n.º 6
0
    def test_xml_binary(self):

        from plone.namedfile import NamedFile

        img_data = open(os.path.join(os.path.dirname(__file__), 'sample.jpg'),
                        'rb').read()
        named_file = NamedFile()
        named_file.data = img_data
        named_file.filename = u'test.jpg'
        named_file.contentType = 'image/jpg'
        self.doc.xml_set('xml_binary', named_file)

        named_file2 = self.doc.xml_get('xml_binary')
        self.assertEqual(named_file2.data, img_data)
        self.assertEqual(named_file2.filename, u'test.jpg')
        self.assertEqual(named_file2.contentType, 'image/jpg')
    def get_attachment_as_namedfile(self, pos):
        """Return a namedfile extracted from the attachment in
        position `pos`.
        """

        # get attachment at position pos
        attachment = None
        for i, part in enumerate(self.context.msg.walk()):
            if i == pos:
                attachment = part
                continue

        if not attachment:
            return None

        # decode when it's necessary
        filename = get_filename(attachment)
        if not isinstance(filename, unicode):
            filename = filename.decode('utf-8')

        # remove line breaks from the filename
        filename = re.sub('\s{1,}', ' ', filename)

        return NamedFile(data=attachment.get_payload(decode=1),
                         contentType=attachment.get_content_type(),
                         filename=filename)
Ejemplo n.º 8
0
    def _delete_attachments(self, attachments):
        if not attachments:
            return

        attachment_names = [
            attachment.get('filename', '[no filename]').decode('utf-8')
            for attachment in attachments]
        positions = [attachment['position'] for attachment in attachments]

        # Flag the `message` attribute as having changed
        desc = Attributes(IAttachmentsDeletedEvent, "message")
        notify(AttachmentsDeleted(self, attachment_names, desc))

        # set the new message file
        msg = remove_attachments(self.msg, positions)
        self.message = NamedFile(
            data=msg.as_string(),
            contentType=self.message.contentType,
            filename=self.message.filename)
Ejemplo n.º 9
0
    def test_should_provide_inline_diff_for_file_list_field(self):
        self.portal.invokeFactory(
            testing.TEST_CONTENT_TYPE_ID,
            'obj1',
            files=None,
        )
        obj1 = self.portal['obj1']

        self.portal.invokeFactory(
            testing.TEST_CONTENT_TYPE_ID,
            'obj2',
            files=[NamedFile(data='data', filename=u'a.txt')],
        )
        obj2 = self.portal['obj2']

        diffs = DexterityCompoundDiff(obj1, obj2, 'any')
        for d in diffs:
            if d.field == 'files':
                inline_diff = d.inline_diff()
                self.assertTrue(inline_diff)
                self.assertTrue(obj2.files[0].filename in inline_diff)
Ejemplo n.º 10
0
 def __init__(self, files):
     """`files` is a sequence of (data, filename) tuples."""
     self.files = files and [
         NamedFile(data=d, filename=fn) for (d, fn) in files
     ]
Ejemplo n.º 11
0
 def _parseField(self, value, filename=None):
     return [
         '' if (value is None) else named_file_as_str(
             NamedFile(data=value, filename=filename))
     ]
Ejemplo n.º 12
0
class ISolution(BaseModel):
    """Base Solution schema fields
    """
    solution_name = schema.TextLine(
        title=_(u"Solution Name"),
        description=_(u"Solution Name"),
        required=True,
    )

    batch_number = schema.TextLine(
        title=_(u"Batch Number"),
        description=_(u"Batch Number"),
        required=True,
    )

    make_date = schema.Date(
        title=_(u"Date Made"),
        description=_(u"Date Made"),
        required=True,
    )

    expiration_date = schema.Date(
        title=_(u"Expiration Date"),
        description=_(u"Expiration Date"),
        required=True,
    )

    initial_amount = Amount(
        title=_(u"Initial amount made"),
        description=_(u"Enter a decimal number"),
        required=True,
    )

    remaining_amount = Amount(
        title=_(u"Amount remaining"),
        description=_(u"You should not need to edit this value"),
    )

    unit = schema.TextLine(
        title=_(u"Unit"),
        description=_("Enter the unit in which the amounts are measured"),
        required=True,
    )

    made_by = schema.Choice(
        title=_(u"Made By"),
        description=_(u"The operator created the material lot"),
        source=UserVocabulary,
        required=True)

    materials_used = schema.Dict(title=_(u"Materials Used"),
                                 key_type=schema.Choice(
                                     title=_(u"Material"),
                                     source=MaterialsVocabulary,
                                     required=False),
                                 value_type=Amount(title=u"Amount Used",
                                                   required=False),
                                 required=False)

    solutions_used = schema.Dict(
        title=_(u"Solution(s) Used"),
        key_type=schema.Choice(title=_(u"Solution"),
                               source=SolutionBatchesForTestRunsVocabulary,
                               required=False),
        value_type=Amount(title=u"Amount Used", required=False),
        required=False)

    viability = schema.Int(
        title=_(u"Solution Viability"),
        description=_(u"Viability of solution in hours. "
                      u"Leave blank if solution does not expire."),
        required=False,
    )

    completed_solution_prep_form = NamedFile(
        title=_(u"Completed Solution Preperation Form"),
        required=False,
    )
Ejemplo n.º 13
0
def setUpApiTests(doctest):
    """
    set up some test data for api doctests as test user
    """
    layer = doctest.globs['layer']
    # layer: app, portal, request,
    #        configurationContext, host, port, zodbDB
    portal = layer['portal']
    # create a fake sdm experiment
    sdm = portal.experiments.invokeFactory('org.bccvl.content.sdmexperiment',
                                           id='sdm',
                                           title=u'Test SDM')
    sdm = portal.experiments[sdm]
    result = sdm.invokeFactory('Folder',
                               id='sdmresult')
    result = sdm[result]
    result.job_params = {
        'function': 'bioclim',
    }
    sdmds = result.invokeFactory('org.bccvl.content.dataset',
                                 id='sdmrds',
                                 title=u'Result Test SDM RData',
                                 file=NamedFile(filename=u'Result_file.Rdata'))
    sdmds = result[sdmds]
    md = IBCCVLMetadata(sdmds)
    md.update({
        'genre': 'DataGenreCP',
        'species': {
            'scientificName': u'Result species',
        }
    })
    sdmds.reindexObject()

    # create a fake projection experiment
    proj = portal.experiments.invokeFactory('org.bccvl.content.projectionexperiment',
                                            id='proj',
                                            title=u'Test Projection')
    proj = portal.experiments[proj]
    # create a result folder
    result = proj.invokeFactory('Folder',
                                id='projresult')
    result = proj[result]
    result.job_params = {
        'species_distribution_models': [IUUID(sdmds)],
    }
    # create a result dataset
    rds = result.invokeFactory('org.bccvl.content.dataset',
                               id='rds',
                               title=u'Result Test',
                               file=NamedFile(filename=u'Result_file.tiff'))
    rds = result[rds]
    # set metadata on rds
    md = IBCCVLMetadata(rds)
    md.update({
        'genre': 'DataGenreFP',
        'temporal': u"start=2014;",
        'gcm': 'cccma-cgcm31',
        'emsc': 'RCP3PD',
        'species': {
            'scientificName': u'Result species',
        }
    })
    # update index with data from graph
    rds.reindexObject()

    # we have to commit here because doctests run in a different
    # thread because they connect via test-broswer.
    transaction.commit()
Ejemplo n.º 14
0
    def extract_attachments(self, positions, delete_action):
        dossier = self.find_parent_dossier()

        attachments_to_extract = filter(
            lambda att: att.get('position') in positions,
            get_attachments(self.context.msg))

        # create documents from the selected attachments
        for att in attachments_to_extract:
            pos = att.get('position')
            filename = att.get('filename')

            # remove line breaks from the filename
            filename = re.sub('\s{1,}', ' ', filename)

            kwargs = {
                'title': filename[:filename.rfind('.')].decode('utf-8'),
                'file': self.get_attachment_as_namedfile(pos),
                'keywords': (),
                'digitally_available': True
            }

            doc = createContentInContainer(dossier,
                                           'opengever.document.document',
                                           **kwargs)

            for schemata in iterSchemata(doc):
                for name, field in getFieldsInOrder(schemata):
                    if name not in kwargs.keys():
                        default = queryMultiAdapter(
                            (
                                doc,
                                doc.REQUEST,  # request
                                None,  # form
                                field,
                                None,  # Widget
                            ),
                            IValue,
                            name='default')
                        if default is not None:
                            default = default.get()
                        if default is None:
                            default = getattr(field, 'default', None)
                        if default is None:
                            try:
                                default = field.missing_value
                            except:
                                pass
                        field.set(field.interface(doc), default)

            # add a reference from the attachment to the mail
            intids = getUtility(IIntIds)
            iid = intids.getId(self.context)

            # prevent circular dependencies
            from opengever.document.behaviors import IRelatedDocuments
            IRelatedDocuments(doc).relatedItems = [RelationValue(iid)]

            msg = _(u'info_extracted_document',
                    default=u'Created document ${title}',
                    mapping={'title': doc.Title().decode('utf-8')})
            IStatusMessage(self.request).addStatusMessage(msg, type='info')

            # reindex the new document to index also all the default values
            doc.reindexObject()

        # delete the attachments from the email message, if needed
        if delete_action in ('all', 'selected'):
            if delete_action == 'selected':
                pos_to_delete = positions
            else:
                # all
                pos_to_delete = [
                    int(att['position'])
                    for att in get_attachments(self.context.msg)
                ]

            # set the new message file
            msg = remove_attachments(self.context.msg, pos_to_delete)
            self.context.message = NamedFile(
                data=msg.as_string(),
                contentType=self.context.message.contentType,
                filename=self.context.message.filename)