source: products/quintagroup.portlet.collection/trunk/quintagroup/portlet/collection/tests/test_portlet.py @ 3556

Last change on this file since 3556 was 3556, checked in by vmaksymiv, 7 years ago

PPP fixes

  • Property svn:eol-style set to native
File size: 11.3 KB
Line 
1from zope.component import getUtility, getMultiAdapter
2
3from plone.portlets.interfaces import IPortletType
4from plone.portlets.interfaces import IPortletManager
5from plone.portlets.interfaces import IPortletAssignment
6from plone.portlets.interfaces import IPortletDataProvider
7from plone.portlets.interfaces import IPortletRenderer
8
9from plone.app.portlets.storage import PortletAssignmentMapping
10
11from quintagroup.portlet.collection import collection
12
13from quintagroup.portlet.collection.tests.base import TestCase
14
15
16from Products.CMFCore.utils import getToolByName
17
18
19class TestQPortletCollection(TestCase):
20    def afterSetUp(self):
21        self.setRoles(('Manager',))
22
23    def testPortletTypeRegistered(self):
24        portlet = getUtility(
25            IPortletType, name='quintagroup.portlet.collection.Collection')
26        self.assertEquals(
27            portlet.addview, 'quintagroup.portlet.collection.Collection')
28
29    def testInterfaces(self):
30        portlet = collection.Assignment(header=u"title")
31        self.failUnless(IPortletAssignment.providedBy(portlet))
32        self.failUnless(IPortletDataProvider.providedBy(portlet.data))
33
34    def testInvokeAddview(self):
35        portlet = getUtility(
36            IPortletType, name='quintagroup.portlet.collection.Collection')
37        mapping = self.portal.restrictedTraverse(
38            '++contextportlets++plone.leftcolumn')
39        for m in mapping.keys():
40            del mapping[m]
41        addview = mapping.restrictedTraverse('+/' + portlet.addview)
42
43        addview.createAndAdd(data={'header': u"test title"})
44
45        self.assertEquals(len(mapping), 1)
46        self.failUnless(isinstance(mapping.values()[0], collection.Assignment))
47
48    def testInvokeEditView(self):
49        mapping = PortletAssignmentMapping()
50        request = self.folder.REQUEST
51
52        mapping['foo'] = collection.Assignment(header=u"title")
53        editview = getMultiAdapter((mapping['foo'], request), name='edit')
54        self.failUnless(isinstance(editview, collection.EditForm))
55
56    def testRenderer(self):
57        context = self.folder
58        request = self.folder.REQUEST
59        view = self.folder.restrictedTraverse('@@plone')
60        manager = getUtility(
61            IPortletManager, name='plone.rightcolumn', context=self.portal)
62        assignment = collection.Assignment(header=u"title")
63
64        renderer = getMultiAdapter(
65            (context, request, view, manager, assignment), IPortletRenderer)
66        self.failUnless(isinstance(renderer, collection.Renderer))
67
68
69class TestQPortletCollectionRenderer(TestCase):
70
71    def afterSetUp(self):
72        self.setRoles(('Manager',))
73        self.pages = self._createType(self.folder, 'Topic', 'pages')
74        crit = self.folder.pages.addCriterion(
75            'portal_type', 'ATSimpleStringCriterion')
76        crit.setValue('Document')
77
78    def renderer(self, context=None, request=None, view=None, manager=None,
79                 assignment=None):
80        context = context or self.folder
81        request = request or self.folder.REQUEST
82        view = view or self.folder.restrictedTraverse('@@plone')
83        manager = manager or getUtility(
84            IPortletManager, name='plone.rightcolumn', context=self.portal)
85        assignment = assignment or collection.Assignment(header=u"title")
86
87        return getMultiAdapter((context, request, view, manager, assignment),
88                               IPortletRenderer)
89
90    def _createType(self, context, portal_type, id, **kwargs):
91        """Helper method to create a new type
92        """
93        ttool = getToolByName(context, 'portal_types')
94        cat = self.portal.portal_catalog
95
96        fti = ttool.getTypeInfo(portal_type)
97        fti.constructInstance(context, id, **kwargs)
98        obj = getattr(context.aq_inner.aq_explicit, id)
99        cat.indexObject(obj)
100        return obj
101
102    def test_collection_path_unicode(self):
103        """
104        Cover problem in #9184
105        """
106        r = self.renderer(
107            context=self.portal,
108            assignment=collection.Assignment(header=u"title",
109                                             target_collection=u"/events"))
110        r = r.__of__(self.folder)
111        self.assertEqual(r.collection().id, 'events')
112
113    def test_portletStyle(self):
114        renderer = self.renderer(context=self.portal,
115                                 assignment=collection.Assignment(
116                                     header=u"title",
117                                     styling="TestClass"))
118        renderer = renderer.__of__(self.folder)
119        renderer.update()
120
121        self.failUnless('TestClass' in renderer.render())
122
123    def test_attributes(self):
124        page = self._createType(self.folder, 'Document', 'page')
125        page.update(title="Test Page", description="Test description")
126        target_collection = '/Members/test_user_1_/pages'
127        renderer = self.renderer(context=self.portal,
128                                 assignment=collection.Assignment(
129                                     header=u"title",
130                                     item_attributes=[u'Title'],
131                                     target_collection=target_collection))
132        renderer = renderer.__of__(self.folder)
133        renderer.update()
134        self.failUnless('Test Page' in renderer.render())
135        self.failUnless('Test description' not in renderer.render())
136
137
138class TestQPortletCollectionQuery(TestCase):
139
140    def afterSetUp(self):
141        self.setRoles(('Manager',))
142        #make a collection
143        self.collection = self._createType(self.folder, 'Topic', 'collection')
144
145    def _createType(self, context, portal_type, id, **kwargs):
146        """Helper method to create a new type
147        """
148        ttool = getToolByName(context, 'portal_types')
149        cat = self.portal.portal_catalog
150
151        fti = ttool.getTypeInfo(portal_type)
152        fti.constructInstance(context, id, **kwargs)
153        obj = getattr(context.aq_inner.aq_explicit, id)
154        cat.indexObject(obj)
155        return obj
156
157    def renderer(self, context=None, request=None, view=None, manager=None,
158                 assignment=None):
159        context = context or self.folder
160        request = request or self.folder.REQUEST
161        view = view or self.folder.restrictedTraverse('@@plone')
162        manager = manager or getUtility(
163            IPortletManager, name='plone.leftcolumn', context=self.portal)
164        assignment = assignment
165        return getMultiAdapter((context, request, view, manager, assignment),
166                               IPortletRenderer)
167
168    def testSimpleQuery(self):
169        # set up our collection to search for Folders
170        crit = self.folder.collection.addCriterion(
171            'portal_type', 'ATSimpleStringCriterion')
172        crit.setValue('Folder')
173
174        # add a few folders
175        for i in range(6):
176            self.folder.invokeFactory('Folder', 'folder_%s' % i)
177            getattr(self.folder, 'folder_%s' % i).reindexObject()
178
179        # the folders are returned by the topic
180        collection_num_items = len(self.folder.collection.queryCatalog())
181        # We better have some folders
182        self.failUnless(collection_num_items >= 6)
183
184        mapping = PortletAssignmentMapping()
185        t_collection = '/Members/test_user_1_/collection'
186        mapping['foo'] = collection.Assignment(header=u"title",
187                                               target_collection=t_collection)
188        collectionrenderer = self.renderer(context=None, request=None,
189                                           view=None, manager=None,
190                                           assignment=mapping['foo'])
191
192        # we want the portlet to return us the same results as the collection
193        self.assertEquals(
194            collection_num_items, len(collectionrenderer.results()))
195
196    def testRandomQuery(self):
197        # we're being perhaps a bit too clever in random mode with the
198        # internals of the LazyMap returned by the collection query, so let's
199        # try a bunch of scenarios to make sure they work
200
201        def reset_memoize(inst):
202            # Decorator memoize adds attribute('_memojito_') to class instance.
203            # It has cached function and their values so it should be deleted
204            # for testing.
205            # Extra info: http://codereview.corp.quintagroup.com/171241/show
206            if hasattr(inst, '_memojito_'):
207                delattr(inst, '_memojito_')
208
209        # set up our portlet renderer
210        mapping = PortletAssignmentMapping()
211        t_collection = '/Members/test_user_1_/collection'
212        mapping['foo'] = collection.Assignment(header=u"title",
213                                               random=True,
214                                               target_collection=t_collection)
215        collectionrenderer = self.renderer(context=None, request=None,
216                                           view=None, manager=None,
217                                           assignment=mapping['foo'])
218
219        # add some folders
220        for i in range(6):
221            self.folder.invokeFactory('Folder', 'folder_%s' % i)
222            getattr(self.folder, 'folder_%s' % i).reindexObject()
223
224        # collection with no criteria -- should return empty list, without
225        # error
226        self.assertEqual(len(collectionrenderer.results()), 0)
227        reset_memoize(collectionrenderer)
228
229        # let's make sure the results aren't being memoized
230        old_func = self.folder.collection.queryCatalog
231        global collection_was_called
232        collection_was_called = False
233
234        def mark_collection_called(**kw):
235            global collection_was_called
236            collection_was_called = True
237        self.folder.collection.queryCatalog = mark_collection_called
238        collectionrenderer.results()
239        reset_memoize(collectionrenderer)
240        self.folder.collection.queryCatalog = old_func
241        self.failUnless(collection_was_called)
242
243        # collection with simple criterion -- should return 1 (random) folder
244        crit = self.folder.collection.addCriterion(
245            'portal_type', 'ATSimpleStringCriterion')
246        crit.setValue('Folder')
247        self.assertEqual(len(collectionrenderer.results()), 1)
248        reset_memoize(collectionrenderer)
249
250        # collection with multiple criteria -- should behave similarly
251        crit = self.folder.collection.addCriterion(
252            'Creator', 'ATSimpleStringCriterion')
253        crit.setValue('test_user_1_')
254        collectionrenderer.results()
255
256        # collection with sorting -- should behave similarly (sort is
257        # ignored internally)
258        self.folder.collection.setSortCriterion('modified', False)
259        self.assertEqual(len(collectionrenderer.results()), 1)
260        reset_memoize(collectionrenderer)
261
262        # same criteria, now with limit set to 2 -- should return 2 (random)
263        # folders
264        collectionrenderer.data.limit = 2
265        self.assertEqual(len(collectionrenderer.results()), 2)
266        reset_memoize(collectionrenderer)
267
268        # make sure there's no error if the limit is greater than the # of
269        # results found
270        collectionrenderer.data.limit = 10
271        self.failUnless(len(collectionrenderer.results()) >= 6)
272        reset_memoize(collectionrenderer)
273
274
275def test_suite():
276    from unittest import TestSuite, makeSuite
277    suite = TestSuite()
278    suite.addTest(makeSuite(TestQPortletCollection))
279    suite.addTest(makeSuite(TestQPortletCollectionRenderer))
280    suite.addTest(makeSuite(TestQPortletCollectionQuery))
281    return suite
Note: See TracBrowser for help on using the repository browser.