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

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

PPP fixes

  • Property svn:eol-style set to native
File size: 11.2 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 internals of the
198        # LazyMap returned by the collection query, so let's try a bunch of scenarios
199        # 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 error
225        self.assertEqual(len(collectionrenderer.results()), 0)
226        reset_memoize(collectionrenderer)
227
228        # let's make sure the results aren't being memoized
229        old_func = self.folder.collection.queryCatalog
230        global collection_was_called
231        collection_was_called = False
232
233        def mark_collection_called(**kw):
234            global collection_was_called
235            collection_was_called = True
236        self.folder.collection.queryCatalog = mark_collection_called
237        collectionrenderer.results()
238        reset_memoize(collectionrenderer)
239        self.folder.collection.queryCatalog = old_func
240        self.failUnless(collection_was_called)
241
242        # collection with simple criterion -- should return 1 (random) folder
243        crit = self.folder.collection.addCriterion(
244            'portal_type', 'ATSimpleStringCriterion')
245        crit.setValue('Folder')
246        self.assertEqual(len(collectionrenderer.results()), 1)
247        reset_memoize(collectionrenderer)
248
249        # collection with multiple criteria -- should behave similarly
250        crit = self.folder.collection.addCriterion(
251            'Creator', 'ATSimpleStringCriterion')
252        crit.setValue('test_user_1_')
253        collectionrenderer.results()
254
255        # collection with sorting -- should behave similarly (sort is ignored internally)
256        self.folder.collection.setSortCriterion('modified', False)
257        self.assertEqual(len(collectionrenderer.results()), 1)
258        reset_memoize(collectionrenderer)
259
260        # same criteria, now with limit set to 2 -- should return 2 (random) folders
261        collectionrenderer.data.limit = 2
262        self.assertEqual(len(collectionrenderer.results()), 2)
263        reset_memoize(collectionrenderer)
264
265        # make sure there's no error if the limit is greater than the # of results found
266        collectionrenderer.data.limit = 10
267        self.failUnless(len(collectionrenderer.results()) >= 6)
268        reset_memoize(collectionrenderer)
269
270
271def test_suite():
272    from unittest import TestSuite, makeSuite
273    suite = TestSuite()
274    suite.addTest(makeSuite(TestQPortletCollection))
275    suite.addTest(makeSuite(TestQPortletCollectionRenderer))
276    suite.addTest(makeSuite(TestQPortletCollectionQuery))
277    return suite
Note: See TracBrowser for help on using the repository browser.