Exemple #1
0
 def _items(self, **query):
     adapter = IAdapter(self.context)
     sort_limit = adapter.get_feed_number(self.interface)
     if sort_limit:
         query['sort_limit'] = sort_limit
         if isinstance(self, BaseNewsEventFeedViewlet):
             query['sort_limit'] += adapter.get_feed_number(
                 ITopPageMainFeed)
     base = IBaseAdapter(self.context)
     res = []
     for item in base.get_content_listing(**query):
         obj = item.getObject()
         if not isinstance(self, BaseNewsEventFeedViewlet) or (
                 ISiteRoot.providedBy(self.context)
                 and not ITopPageFeed.providedBy(obj)) or (
                     not ISiteRoot.providedBy(self.context)
                     and INavigationRoot.providedBy(self.context)
                     and not IMicroSiteFeed.providedBy(obj)):
             parent = aq_parent(aq_inner(obj))
             res.append({
                 'title': item.Title(),
                 'url': item.getURL(),
                 'parent_title': parent.Title(),
                 'parent_url': parent.absolute_url(),
                 'date': self._date(item),
                 'image': self._image(item),
                 'description': self._description(item),
             })
     if sort_limit:
         return res[:sort_limit]
     return res
    def _get_collection(self, name):
        cid = self.data.collections
        if cid:
            collection = getUtility(ISearchEventCollection)(cid)
            if collection.get(name):

                checked = self.request.form.get(name, [])
                names = []

                attr = name
                if name == 'paths':
                    attr = 'folders'
                    adapter = IAdapter(self.context)
                    portal_path = adapter.portal_path()
                    for nam in collection.get(name):
                        path = '{}{}'.format(portal_path, nam)
                        title = adapter.get_brain(path=path, depth=0).Title
                        names.append({
                            'checked': nam in checked,
                            'key': path,
                            'title': title,
                        })
                else:

                    for nam in collection.get(name):
                        names.append({'checked': nam in checked, 'key': nam})

                return {'names': names, 'title': getattr(self.data, attr)}
Exemple #3
0
 def _items(self, **query):
     adapter = IAdapter(self.context)
     sort_limit = adapter.get_feed_number(self.interface)
     if sort_limit:
         query['sort_limit'] = sort_limit
         if isinstance(self, BaseNewsEventFeedViewlet):
             query['sort_limit'] += adapter.get_feed_number(ITopPageMainFeed)
     base = IBaseAdapter(self.context)
     res = []
     for item in base.get_content_listing(**query):
         obj = item.getObject()
         if not isinstance(self, BaseNewsEventFeedViewlet) or (
             ISiteRoot.providedBy(self.context) and not ITopPageFeed.providedBy(obj)) or (
                 not ISiteRoot.providedBy(self.context) and INavigationRoot.providedBy(self.context) and not IMicroSiteFeed.providedBy(obj)):
             parent = aq_parent(aq_inner(obj))
             res.append({
                 'title': item.Title(),
                 'url': item.getURL(),
                 'parent_title': parent.Title(),
                 'parent_url': parent.absolute_url(),
                 'date': self._date(item),
                 'image': self._image(item),
                 'description': self._description(item),
             })
     if sort_limit:
         return res[:sort_limit]
     return res
Exemple #4
0
    def events(self):
        """Return list of dictionary

        :rtype: list
        """
        res = []
        base = IAdapter(self.context)
        before_date = '{}/01/01'.format(self.year() + 1)
        for item in base.get_content_listing(IATEvent,
                                             sort_on='start',
                                             start={
                                                 'query': [
                                                     DateTime(before_date),
                                                 ],
                                                 'range': 'max'
                                             },
                                             end={
                                                 'query': [
                                                     DateTime(),
                                                 ],
                                                 'range': 'min'
                                             }):
            res.append({
                'datetime': base.event_datetime(item),
                'description': item.Description(),
                'title': item.Title(),
                'url': item.getURL(),
            })
        return res
    def __call__(self, paths=None, limit=0, b_start=0, b_size=10, b_orphan=1):
        """Returns limited number of brains.

        :param limit: Integer number.
        :type limit: int

        :param b_start: batching start.
        :type b_start: int

        :param b_size: batch size.
        :type b_size: int

        :param b_orphan: batch orphan.
        :type b_orphan: int

        :rtype: plone.app.contentlisting.contentlisting.ContentListing
        """
        form = self.request.form

        start = form.get('start')
        if start:
            start = DateTime(start)

        end = form.get('end')
        if end:
            end = DateTime(end) + 1

        if not (start or end):
            start = DateTime()

        adapter = IAdapter(self.context)

        query = dict(
            SearchableText=form.get('words', ''),
            sort_on='start',
            start={
                'query': [end, ],
                'range': 'max',
            },
            end={
                'query': [start, ],
                'range': 'min',
            },
            path=adapter.portal_path(),
        )
        Subject = form.get('tags', None)
        if Subject:
            query.update({'Subject': Subject})
        paths = form.get('paths', paths)
        if paths:
            query.update({'path': paths})
        if limit:
            query.update({'sort_limit': limit})
        # Add b_start and b_size to the query.
        if b_size:
            query['b_start'] = b_start
            query['b_size'] = b_size

        return adapter.get_content_listing(IATEvent, **query)
    def validate(self, value):
        super(ValidateSKUUniqueness, self).validate(value)

        if getattr(self.context, 'sku', u'') != value:
            adapter = IAdapter(self.context)
            brains = adapter.get_brains(IArticle, path=adapter.portal_path(), sku=value)

            if brains:
                raise Invalid(_(u'The SKU is already in use.'))
Exemple #7
0
    def obj(self):
        """Return ATDocument object

        :rtype: obj
        """
        adapter = IAdapter(self.context)
        if self.name:
            return adapter.get_object(IATDocument, depth=1, id=self.name)
        else:
            return adapter.get_object(IATDocument, depth=1)
Exemple #8
0
 def link(self):
     base = IBaseAdapter(self.context)
     path = '{}/{}'.format('/'.join(self.context.getPhysicalPath()),
                           self.records().path)
     query = {'path': {'query': path, 'depth': 0}}
     brain = base.get_brain(**query)
     if brain:
         return {
             'title': brain.Title,
             'url': brain.getURL(),
         }
Exemple #9
0
 def link(self):
     base = IBaseAdapter(self.context)
     path = '{}/{}'.format(
         '/'.join(self.context.getPhysicalPath()),
         self.records().path)
     query = {'path': {'query': path, 'depth': 0}}
     brain = base.get_brain(**query)
     if brain:
         return {
             'title': brain.Title,
             'url': brain.getURL(),
         }
Exemple #10
0
    def clear_interfaces(self):
        context = aq_inner(self.context)
        adapter = IAdapter(context)
        items = {}
        omits = [
            IVersioned, IATImage, IImageContent, IATFile, IFileContent,
            IATBlobImage, IATBlobFile
        ]
        for obj in adapter.get_objects():
            if obj.id == 'carousel':
                parent = aq_parent(aq_inner(obj))
                parent.manage_delObjects(['carousel'])
                message = 'Remove carousel folder from {}.'.format('/'.join(
                    parent.getPhysicalPath()))
                logger.info(message)
                IStatusMessage(self.request).addStatusMessage(message,
                                                              type='info')
            else:
                ifaces = [
                    iface for iface in directlyProvidedBy(obj)
                    if iface not in omits
                ]
                if ifaces:
                    for iface in ifaces:
                        annotations = IAnnotations(obj)
                        if annotations.get('collective.pfg.payment'):
                            del annotations['collective.pfg.payment']
                            message = 'Remove annotations collective.pfg.payment from {}.'.format(
                                '/'.join(obj.getPhysicalPath()))
                            logger.info(message)
                            IStatusMessage(self.request).addStatusMessage(
                                message, type='info')
                        noLongerProvides(obj, iface)
                        identifier = iface.__identifier__
                        if identifier not in items:
                            items[identifier] = 1
                        else:
                            items[identifier] += 1
                    obj.reindexObject(idxs=['object_provides'])

        for key in items:
            message = '{} objects providing {} are cleared.'.format(
                items[key], key)
            logger.info(message)
            IStatusMessage(self.request).addStatusMessage(message, type='info')
        if not items:
            message = 'No objects need to be cleared.'
            logger.info(message)
            IStatusMessage(self.request).addStatusMessage(message, type='info')
        url = self.context.absolute_url()
        return self.request.response.redirect(url)
    def __call__(self):
        super(SearchEventResultsView, self).__call__()
        if self.request.form.get("form.buttons.Export", None) is not None:
            defaults_name = [
                self.context.translate(PloneMessageFactory(u"Title")),
                self.context.translate(_(u"Date")),
                self.context.translate(PloneMessageFactory(u"Description")),
                self.context.translate(PloneMessageFactory(u"Text")),
                self.context.translate(PloneMessageFactory(u"URL")),
            ]
            extras = ["location", "attendees", "eventUrl", "contactName", "contactEmail", "contactPhone", "subject"]
            extras_name = [
                self.context.translate(ATCTMessageFactory(ATEvent.schema.get(extra).widget.label)) for extra in extras
            ]

            plone = getMultiAdapter((self.context, self.request), name="plone")
            encoding = plone.site_encoding()

            headers = tuple([header.encode(encoding) for header in (defaults_name + extras_name)])
            out = StringIO()
            writer = csv.writer(out, delimiter="|", quoting=csv.QUOTE_MINIMAL)
            writer.writerow(headers)

            adapter = IAdapter(self.context)
            for item in getMultiAdapter((self.context, self.request), ISearchEventResults)(b_size=None):
                values = [
                    item.Title(),
                    adapter.event_datetime(item).encode(encoding),
                    item.Description(),
                    IItemText(item)(),
                    item.getURL(),
                ]
                obj = item.getObject()
                for extra in extras:
                    if extra == "attendees" or extra == "subject":
                        value = u", ".join(getattr(obj, extra)).encode(encoding)
                    else:
                        value = getattr(obj, extra).encode(encoding)

                    values.append(value)

                writer.writerow(tuple(values))

            filename = "search-event-results-{}.csv".format(datetime.now().isoformat())
            cd = 'attachment; filename="{}"'.format(filename)
            self.request.response.setHeader("Content-Type", "text/csv")
            self.request.response.setHeader("Content-Disposition", cd)
            return out.getvalue()
        else:
            return self.template()
Exemple #12
0
    def services(self):
        """Return list of dictionary

        :rtype: list
        """
        res = []
        languages = getToolByName(self.context, 'portal_languages')
        code = languages.getPreferredLanguage()
        if 'Subject' not in self.request.form:
            for item in IAdapter(self.context).get_content_listing(
                    IATDocument,
                    depth=1,
                    sort_order='getObjPositionInParent',
                    Language=code):
                Subjects = item.Subject()
                if Subjects:
                    Subject = Subjects[0]
                    res.append({
                        'title':
                        item.Title(),
                        'description':
                        item.Description(),
                        'id':
                        item.id,
                        'url':
                        '{}?Subject={}'.format(self.context.absolute_url(),
                                               Subject),
                    })
        return res
Exemple #13
0
    def events(self):
        """Return list of dictionary

        :rtype: list
        """
        res = []
        base = IAdapter(self.context)
        before_date = '{}/01/01'.format(self.year() + 1)
        for item in base.get_content_listing(IATEvent, sort_on='start', start={'query': [DateTime(before_date), ], 'range': 'max'}, end={'query': [DateTime(), ], 'range': 'min'}):
            res.append({
                'datetime': base.event_datetime(item),
                'description': item.Description(),
                'title': item.Title(),
                'url': item.getURL(),
            })
        return res
Exemple #14
0
    def items(self):
        """Return brains"""
        query = {
            'sort_limit': 3,
            'sort_on': 'end',
            'sort_order': 'descending',
        }
        if self.view.subject():
            query['Subject'] = self.view.subject()

        res = []
        languages = getToolByName(self.context, 'portal_languages')
        code = languages.getPreferredLanguage()
        for item in IAdapter(self.context).get_content_listing(IATEvent,
                                                               Language=code,
                                                               **query):
            res.append({
                'client': item.contactName,
                'client_url': item.eventUrl,
                'description': item.Description(),
                'location': item.location,
                'subjects': self._subjects(item),
                'title': item.Title(),
                'url': item.getURL(),
                'year': IEventAdapter(item).year(),
            })
        return res
Exemple #15
0
    def _subjects(self, brain):
        """Return list of dictionary

        :rtype: list
        """
        res = []
        parent_brain = IAdapter(self.context).get_brain(IATFolder, path=self._path(), depth=0)
        parent_url = parent_brain.getURL()
        subjects = brain.Subject
        if hasattr(subjects, '__call__'):
            subjects = subjects()
        for subject in subjects:
            res.append({
                'title': subject,
                'url': '{}?Subject={}'.format(parent_url, subject),
            })
        return res
Exemple #16
0
    def items(self):
        """Returns list of dictionary of footer infos

        :rtype: list
        """
        res = []
        adapter = IAdapter(self.context)
        path = '{}/footer-info'.format(adapter.portal_path())
        for item in adapter.get_content_listing(IATDocument, path=path, depth=1, sort_on='getObjPositionInParent'):
            res.append({
                'id': item.id,
                'title': item.Title(),
                'url': item.getURL(),
                'description': item.Description(),
                'text': item.getObject().CookedBody(),
            })
        return res
Exemple #17
0
    def actions(self):
        """Returns content listing of actions

        :rtype: content listing
        """
        portal_state = self.context.restrictedTraverse('@@plone_portal_state')
        path = '{}/site-actions'.format(portal_state.navigation_root_path())
        return IAdapter(self.context).get_content_listing(IATFolder, path=path, depth=1, sort_on='getObjPositionInParent')
Exemple #18
0
    def doc(self):
        """Return instance of ATDocument"""
        languages = getToolByName(self.context, 'portal_languages')
        code = languages.getPreferredLanguage()

        if self.subject():
            return IAdapter(self.context).get_object(IATDocument, depth=1, Subject=self.subject(), sort_on="getObjPositionInParent", Language=code)
        return self.context.get(code)
Exemple #19
0
 def _brain(self):
     """Return brain"""
     languages = getToolByName(self.context, 'portal_languages')
     code = languages.getPreferredLanguage()
     return IAdapter(self.context).get_brain(IATNewsItem,
                                             path=self._path(),
                                             sort_on='effective',
                                             sort_order='descending',
                                             Language=code)
def upgrade_14_to_15(context, logger=None):
    """Set article attribute: vat_rate"""
    if logger is None:
        logger = logging.getLogger(__name__)
    from collective.base.interfaces import IAdapter
    from collective.cart.shopping.interfaces import IArticle
    from zope.lifecycleevent import modified
    adapter = IAdapter(context)
    for brain in adapter.get_brains(IArticle, path=adapter.portal_path()):
        obj = brain.getObject()
        setattr(obj, 'vat_rate', obj.vat)
        modified(obj)

    from collective.cart.shipping.interfaces import IShippingMethod
    for brain in adapter.get_brains(IShippingMethod, path=adapter.portal_path()):
        obj = brain.getObject()
        setattr(obj, 'vat', obj.vat)
        obj.reindexObject(idxs=['vat'])
def make_subarticles_private(context, logger=None):
    """Make subarticles private if article with use_subarticle is private"""
    if logger is None:
        logger = logging.getLogger(__name__)
    from Products.CMFCore.WorkflowCore import WorkflowException
    from collective.base.interfaces import IAdapter
    from collective.cart.shopping.interfaces import IArticle
    from collective.cart.shopping.interfaces import IArticleAdapter
    from zope.lifecycleevent import modified

    wftool = getToolByName(context, 'portal_workflow')
    portal = IAdapter(context).portal()
    adapter = IAdapter(portal)
    particles = adapter.get_objects(IArticle, use_subarticle=True, review_state="published")
    action = 'hide'

    if particles:
        obj = particles[0]
        for trans in wftool.getTransitionsFor(obj):
            tid = trans['id']
            if tid == 'retract' or tid == 'reject':
                action = tid

    articles = adapter.get_objects(IArticle, use_subarticle=True, review_state="private")
    count = 0

    for article in articles:
        aadapter = IArticleAdapter(article)
        subarticles = aadapter.get_objects(IArticle, review_state="published")
        for subarticle in subarticles:
            subarticle_path = '/'.join(subarticle.getPhysicalPath())
            try:
                wftool.doActionFor(subarticle, action)
                modified(subarticle)
                message = 'Successfully hid subarticle: {}'.format(subarticle_path)
                logger.info(message)
                count += 1
            except WorkflowException:
                message = 'Already hidden subarticle? {}'.format(subarticle_path)
                logger.info(message)

    if count:
        message = 'There are total of {} subarticles hidden.'.format(count)
        logger.info(message)
Exemple #22
0
    def _subjects(self, brain):
        """Return list of dictionary

        :rtype: list
        """
        res = []
        parent_brain = IAdapter(self.context).get_brain(IATFolder,
                                                        path=self._path(),
                                                        depth=0)
        parent_url = parent_brain.getURL()
        subjects = brain.Subject
        if hasattr(subjects, '__call__'):
            subjects = subjects()
        for subject in subjects:
            res.append({
                'title': subject,
                'url': '{}?Subject={}'.format(parent_url, subject),
            })
        return res
Exemple #23
0
    def _brain(self):
        """Return dicrionary

        :rtype: dict
        """
        languages = getToolByName(self.context, 'portal_languages')
        code = languages.getPreferredLanguage()
        return IAdapter(self.context).get_brain(IATEvent,
                                                path=self._path(),
                                                sort_on='end',
                                                sort_order='descending',
                                                Language=code)
Exemple #24
0
    def clear_interfaces(self):
        context = aq_inner(self.context)
        adapter = IAdapter(context)
        items = {}
        omits = [IVersioned, IATImage, IImageContent, IATFile, IFileContent, IATBlobImage, IATBlobFile]
        for obj in adapter.get_objects():
            if obj.id == 'carousel':
                parent = aq_parent(aq_inner(obj))
                parent.manage_delObjects(['carousel'])
                message = 'Remove carousel folder from {}.'.format('/'.join(parent.getPhysicalPath()))
                logger.info(message)
                IStatusMessage(self.request).addStatusMessage(message, type='info')
            else:
                ifaces = [iface for iface in directlyProvidedBy(obj) if iface not in omits]
                if ifaces:
                    for iface in ifaces:
                        annotations = IAnnotations(obj)
                        if annotations.get('collective.pfg.payment'):
                            del annotations['collective.pfg.payment']
                            message = 'Remove annotations collective.pfg.payment from {}.'.format('/'.join(obj.getPhysicalPath()))
                            logger.info(message)
                            IStatusMessage(self.request).addStatusMessage(message, type='info')
                        noLongerProvides(obj, iface)
                        identifier = iface.__identifier__
                        if identifier not in items:
                            items[identifier] = 1
                        else:
                            items[identifier] += 1
                    obj.reindexObject(idxs=['object_provides'])

        for key in items:
            message = '{} objects providing {} are cleared.'.format(items[key], key)
            logger.info(message)
            IStatusMessage(self.request).addStatusMessage(message, type='info')
        if not items:
            message = 'No objects need to be cleared.'
            logger.info(message)
            IStatusMessage(self.request).addStatusMessage(message, type='info')
        url = self.context.absolute_url()
        return self.request.response.redirect(url)
    def test_event_datetime(self):
        base = IAdapter(self.portal)

        from DateTime import DateTime
        self.create_event(id='event1', startDate=DateTime('2013/02/25'), endDate=DateTime('2013/02/25'))
        self.create_event(id='event2', startDate=DateTime('2013/02/26 20:00'), endDate=DateTime('2013/02/26 22:00'))
        self.create_event(id='event3', startDate=DateTime('2013/02/27'), endDate=DateTime('2013/02/28'))

        from Products.ATContentTypes.interfaces.event import IATEvent
        res = []
        for item in base.get_content_listing(IATEvent, sort_on='start'):
            res.append(base.event_datetime(item))
        try:
            self.assertEqual(res, [
                u'Feb 25, 2013 12:00 AM',
                u'Feb 26, 2013 08:00 PM - 10:00 PM',
                u'Feb 27, 2013 12:00 AM - Feb 28, 2013 12:00 AM'])
        except AssertionError:
            self.assertEqual(res, [
                u'2013-02-25 00:00',
                u'2013-02-26 20:00 - 22:00',
                u'2013-02-27 00:00 - 2013-02-28 00:00'])
Exemple #26
0
    def title(self):
        """Return title from folder title

        :rtype: str
        """
        languages = getToolByName(self.context, 'portal_languages')
        code = languages.getPreferredLanguage()
        brain = IAdapter(self.context).get_brain(IATDocument, depth=1, id=code)
        if brain:
            title = brain.Title
        else:
            title = self.context.Title()
        return _(u'recent-something',
                 default=u"Recent ${something}",
                 mapping={'something': safe_unicode(title)})
Exemple #27
0
 def _tabs(self):
     context = aq_inner(self.context)
     portal_tabs_view = getMultiAdapter((context, self.request),
                                        name='portal_tabs_view')
     portal = self.context.restrictedTraverse(
         '@@plone_portal_state').portal()
     res = []
     languages = getToolByName(self.context, 'portal_languages')
     code = languages.getPreferredLanguage()
     for tab in portal_tabs_view.topLevelTabs():
         obj = portal.get(tab['id'])
         if obj and IAdapter(obj).get_brains(depth=1, Language=[code, '']):
             name = safe_unicode(tab['name'])
             tab['name'] = _(name)
             res.append(tab)
     return res
Exemple #28
0
 def works(self):
     """Returns list of dictionary of past works"""
     res = []
     languages = getToolByName(self.context, 'portal_languages')
     code = languages.getPreferredLanguage()
     for item in IAdapter(self.context).get_content_listing(
             IATEvent,
             depth=1,
             sort_on='end',
             sort_order='descending',
             Language=code):
         res.append({
             'client': item.contactName,
             'client_url': item.eventUrl,
             'description': item.Description(),
             'title': item.Title(),
             'url': item.getURL(),
             'year': IEventAdapter(item).year(),
             'end': item.endDate,
         })
     return res
Exemple #29
0
    def news(self):
        """Return list of dictionary

        :rtype: list
        """
        query = {
            'depth': 1,
            'sort_order': 'effective',
            'review_state': 'published'
        }
        if self.view.subject():
            query['Subject'] = self.view.subject()
        res = []
        toLocalizedTime = self.context.restrictedTraverse(
            '@@plone').toLocalizedTime
        languages = getToolByName(self.context, 'portal_languages')
        code = languages.getPreferredLanguage()
        for item in IAdapter(self.context).get_content_listing(IATNewsItem,
                                                               Language=code,
                                                               **query):
            res.append({
                'title':
                item.Title(),
                'description':
                item.Description(),
                'id':
                item.id,
                'url':
                item.getURL(),
                'date':
                toLocalizedTime(item.EffectiveDate()),
                'datetime':
                item.effective.asdatetime().date().isoformat(),
                'subjects':
                self._subjects(item),
            })
        return res
 def test_portal_path(self):
     self.assertEqual(IAdapter(self.portal).portal_path(), '/plone')
    def test__two_folders(self):
        from Products.ATContentTypes.interfaces.folder import IATFolder
        base = IAdapter(self.portal)

        folder1 = self.portal[self.portal.invokeFactory('Folder', 'folder1')]
        folder1.reindexObject()
        folder2 = folder1[folder1.invokeFactory('Folder', 'folder2')]
        folder2.reindexObject()

        query = {}

        self.assertEqual(len(base.get_brains(**query)), 2)
        self.assertEqual(len(base.get_objects(**query)), 2)
        self.assertEqual(len(base.get_content_listing(**query)), 2)

        self.assertEqual(len(base.get_brains(interfaces=IATFolder, **query)), 2)
        self.assertEqual(len(base.get_objects(interfaces=IATFolder, **query)), 2)
        self.assertEqual(len(base.get_content_listing(interfaces=IATFolder, **query)), 2)

        query['sort_limit'] = 1
        self.assertEqual(len(base.get_brains(**query)), 1)
        self.assertEqual(len(base.get_objects(**query)), 1)
        self.assertEqual(len(base.get_content_listing(**query)), 1)

        self.assertEqual(len(base.get_brains(interfaces=IATFolder, **query)), 1)
        self.assertEqual(len(base.get_objects(interfaces=IATFolder, **query)), 1)
        self.assertEqual(len(base.get_content_listing(interfaces=IATFolder, **query)), 1)
    def test__folder_and_document(self):
        from Products.ATContentTypes.interfaces.document import IATDocument
        from Products.ATContentTypes.interfaces.folder import IATFolder
        base = IAdapter(self.portal)

        folder1 = self.portal[self.portal.invokeFactory('Folder', 'folder1')]
        folder1.reindexObject()
        doc1 = self.portal[self.portal.invokeFactory('Document', 'doc1')]
        doc1.reindexObject()

        self.assertEqual(len(base.get_brains(IATDocument)), 1)
        self.assertEqual(len(base.get_objects(IATDocument)), 1)
        self.assertEqual(len(base.get_content_listing(IATDocument)), 1)
        self.assertEqual(base.get_brain(IATDocument).id, 'doc1')
        self.assertEqual(base.get_object(IATDocument).id, 'doc1')

        self.assertEqual(len(base.get_brains([IATDocument, IATFolder])), 2)
        self.assertEqual(len(base.get_objects([IATDocument, IATFolder])), 2)
        self.assertEqual(len(base.get_content_listing([IATDocument, IATFolder])), 2)

        self.assertEqual(len(base.get_brains([IATDocument], object_provides=IATFolder.__identifier__)), 2)
        self.assertEqual(len(base.get_objects([IATDocument], object_provides=IATFolder.__identifier__)), 2)
        self.assertEqual(len(base.get_content_listing([IATDocument], object_provides=IATFolder.__identifier__)), 2)
 def test_instance(self):
     from collective.base.adapter import Adapter
     self.assertIsInstance(IAdapter(self.portal), Adapter)
    def test__one_folder(self):
        """Add folder under portal."""
        from Products.ATContentTypes.interfaces.folder import IATFolder
        base = IAdapter(self.portal)

        folder1 = self.portal[self.portal.invokeFactory('Folder', 'folder1')]
        folder1.reindexObject()

        query = {}

        self.assertEqual(len(base.get_brains(**query)), 1)
        self.assertEqual(len(base.get_objects(**query)), 1)
        self.assertEqual(len(base.get_content_listing(**query)), 1)
        self.assertEqual(base.get_brain(**query).id, 'folder1')
        self.assertEqual(base.get_object(**query).id, 'folder1')

        self.assertEqual(len(base.get_brains(interfaces=IATFolder, **query)), 1)
        self.assertEqual(len(base.get_objects(interfaces=IATFolder, **query)), 1)
        self.assertEqual(len(base.get_content_listing(interfaces=IATFolder, **query)), 1)
        self.assertEqual(base.get_brain(interfaces=IATFolder, **query).id, 'folder1')
        self.assertEqual(base.get_object(interfaces=IATFolder, **query).id, 'folder1')

        query = {'path': '/'.join(folder1.getPhysicalPath())}

        self.assertEqual(len(base.get_brains(**query)), 1)
        self.assertEqual(len(base.get_objects(**query)), 1)
        self.assertEqual(len(base.get_content_listing(**query)), 1)
        self.assertEqual(base.get_brain(**query).id, 'folder1')
        self.assertEqual(base.get_object(**query).id, 'folder1')

        self.assertEqual(len(base.get_brains(interfaces=IATFolder, **query)), 1)
        self.assertEqual(len(base.get_objects(interfaces=IATFolder, **query)), 1)
        self.assertEqual(len(base.get_content_listing(interfaces=IATFolder, **query)), 1)
        self.assertEqual(base.get_brain(interfaces=IATFolder, **query).id, 'folder1')
        self.assertEqual(base.get_object(interfaces=IATFolder, **query).id, 'folder1')

        query['depth'] = 0
        self.assertEqual(len(base.get_brains(**query)), 1)
        self.assertEqual(len(base.get_objects(**query)), 1)
        self.assertEqual(len(base.get_content_listing(**query)), 1)
        self.assertEqual(base.get_brain(**query).id, 'folder1')
        self.assertEqual(base.get_object(**query).id, 'folder1')

        self.assertEqual(len(base.get_brains(interfaces=IATFolder, **query)), 1)
        self.assertEqual(len(base.get_objects(interfaces=IATFolder, **query)), 1)
        self.assertEqual(len(base.get_content_listing(interfaces=IATFolder, **query)), 1)
        self.assertEqual(base.get_brain(interfaces=IATFolder, **query).id, 'folder1')
        self.assertEqual(base.get_object(interfaces=IATFolder, **query).id, 'folder1')

        query['depth'] = 1
        self.assertEqual(len(base.get_brains(**query)), 0)
        self.assertEqual(len(base.get_objects(**query)), 0)
        self.assertEqual(len(base.get_content_listing(**query)), 0)
        self.assertIsNone(base.get_brain(**query))
        self.assertIsNone(base.get_object(**query))

        self.assertEqual(len(base.get_brains(interfaces=IATFolder, **query)), 0)
        self.assertEqual(len(base.get_objects(interfaces=IATFolder, **query)), 0)
        self.assertEqual(len(base.get_content_listing(interfaces=IATFolder, **query)), 0)
        self.assertIsNone(base.get_brain(interfaces=IATFolder, **query))
        self.assertIsNone(base.get_object(interfaces=IATFolder, **query))

        query['depth'] = 0
        self.assertEqual(len(base.get_brains(**query)), 1)
        self.assertEqual(len(base.get_objects(**query)), 1)
        self.assertEqual(len(base.get_content_listing(**query)), 1)
        self.assertEqual(base.get_brain(**query).id, 'folder1')
        self.assertEqual(base.get_object(**query).id, 'folder1')

        setRoles(self.portal, TEST_USER_ID, ['Member'])

        from plone.app.testing.helpers import logout
        logout()

        base = IAdapter(self.portal)
        self.assertEqual(len(base.get_brains(**query)), 0)

        query['unrestricted'] = True
        self.assertEqual(len(base.get_brains(**query)), 1)
 def test_context_path(self):
     base = IAdapter(self.portal)
     self.assertEqual(base.context_path(), '/plone')
    def test__get_brains__empty(self):
        from Products.ATContentTypes.interfaces.folder import IATFolder
        base = IAdapter(self.portal)

        query = {}

        self.assertEqual(len(base.get_brains(**query)), 0)
        self.assertEqual(len(base.get_objects(**query)), 0)
        self.assertEqual(len(base.get_content_listing(**query)), 0)
        self.assertIsNone(base.get_brain(**query))
        self.assertIsNone(base.get_object(**query))

        self.assertEqual(len(base.get_brains(interfaces=IATFolder, **query)), 0)
        self.assertEqual(len(base.get_objects(interfaces=IATFolder, **query)), 0)
        self.assertEqual(len(base.get_content_listing(interfaces=IATFolder, **query)), 0)
        self.assertIsNone(base.get_brain(interfaces=IATFolder, **query))
        self.assertIsNone(base.get_object(interfaces=IATFolder, **query))
    def test_catalog(self):

        base = IAdapter(self.portal)
        self.assertEqual(base.catalog(), getToolByName(self.portal, 'portal_catalog'))
 def test_membership(self):
     from Products.PlonePAS.tools.membership import MembershipTool
     adapter = IAdapter(self.portal)
     self.assertIsInstance(adapter.membership(), MembershipTool)
 def test_getSessionData(self, getToolByName):
     from collective.base.interfaces import IAdapter
     IAdapter(self.portal).getSessionData()
     getToolByName().getSessionData.assert_called_with(create=True)
 def test_portal(self):
     self.assertEqual(IAdapter(self.portal).portal(), self.portal)
 def test_verifyObject(self):
     from zope.interface.verify import verifyObject
     self.assertTrue(verifyObject(IAdapter, IAdapter(self.portal)))