source: products/quintagroup.analytics/branches/wf_colours/quintagroup/analytics/tests.py

Last change on this file was 3020, checked in by fenix, 13 years ago

added tests for portlets stats and properties stats views

File size: 16.0 KB
Line 
1import unittest
2import transaction
3
4from AccessControl.SecurityManagement import newSecurityManager
5from Testing import ZopeTestCase as ztc
6from Products.Five import zcml
7from Products.Five import fiveconfigure
8from zope.component import testing, queryMultiAdapter, getUtility
9
10from Products.PloneTestCase import PloneTestCase as ptc
11from Products.PloneTestCase import setup as ptc_setup
12from Products.PloneTestCase.layer import PloneSite
13from plone.portlets.interfaces import IPortletType
14
15import quintagroup.analytics
16
17ptc.setupPloneSite()
18
19class Installed(PloneSite):
20
21    @classmethod
22    def setUp(cls):
23        fiveconfigure.debug_mode = True
24        zcml.load_config('configure.zcml',
25                         quintagroup.analytics)
26        fiveconfigure.debug_mode = False
27        ztc.installPackage('quintagroup.analytics')
28        app = ztc.app()
29        portal = app[ptc_setup.portal_name]
30
31        # Sets the local site/manager
32        ptc_setup._placefulSetUp(portal)
33
34        qi = getattr(portal, 'portal_quickinstaller', None)
35        qi.installProduct('quintagroup.analytics')
36        transaction.commit()
37
38    @classmethod
39    def tearDown(cls):
40            pass
41
42class SetUpContent(Installed):
43
44    max = 10
45    types_ = ['Document', 'Event', 'Folder']
46    users = [('user%s'%i, 'user%s'%i, 'Member', None)
47             for i in xrange(max)]
48
49    @classmethod
50    def setupUsers(cls, portal):
51        """ Creates users."""
52        acl_users = portal.acl_users
53        mp = portal.portal_membership
54        map(acl_users._doAddUser, *zip(*cls.users))
55        if not mp.memberareaCreationFlag:
56            mp.setMemberareaCreationFlag()
57        map(mp.createMemberArea, [u[0] for u in cls.users])
58
59    @classmethod
60    def setupContent(cls, portal):
61        """ Creates test content."""
62        uf = portal.acl_users
63        pm = portal.portal_membership
64        pc = portal.portal_catalog
65        users = [u[0] for u in cls.users]
66        for u in users:
67            folder = pm.getHomeFolder(u)
68            user = uf.getUserById(u)
69            if not hasattr(user, 'aq_base'):
70                user = user.__of__(uf)
71            newSecurityManager(None, user)
72            for i in xrange(users.index(u)+cls.max):
73                map(folder.invokeFactory, cls.types_, [t+str(i) for t in cls.types_])
74        transaction.commit()
75
76
77    @classmethod
78    def setUp(cls):
79        app = ztc.app()
80        portal = app[ptc_setup.portal_name]
81        cls.setupUsers(portal)
82        cls.setupContent(portal)
83
84    @classmethod
85    def tearDown(cls):
86        pass
87
88class TestCase(ptc.PloneTestCase):
89    layer = Installed
90
91
92class TestQAInstallation(TestCase):
93    """ This class veryfies registrations of all needed views and
94        actions.
95    """
96
97    def test_cp_action_installation(self):
98        """This test validates control panel action. """
99        control_panel = self.portal.portal_controlpanel
100        self.assert_('QAnalytics' in [a.id for a in control_panel.listActions()],
101                     "Configlet for quintagroup.analitycs isn't registered.")
102
103    def test_OwnershipByType(self):
104        """ This test validates registration of
105            ownership_by_type view.
106        """
107        view = queryMultiAdapter((self.portal, self.portal.REQUEST),
108                                 name="ownership_by_type")
109
110        self.assert_(view, "Ownership by type view isn't registered")
111
112    def test_OwnershipByState(self):
113        """ This test validates registration of
114            ownership_by_state view.
115        """
116        view = queryMultiAdapter((self.portal, self.portal.REQUEST),
117                                 name="ownership_by_state")
118
119        self.assert_(view, "Ownership by state view isn't registered")
120
121    def test_TypeByState(self):
122        """ This test validates registration of
123            type_by_state view.
124        """
125        view = queryMultiAdapter((self.portal, self.portal.REQUEST),
126                                 name="type_by_state")
127
128        self.assert_(view, "Type by state view isn't registered")
129
130    def test_LegacyPortlets(self):
131        """ This test validates registration of
132            legacy_portlets view.
133        """
134        view = queryMultiAdapter((self.portal, self.portal.REQUEST),
135                                 name="legacy_portlets")
136
137        self.assert_(view, "Legacy Portlets view isn't registered")
138
139    def test_PropertiesStats(self):
140        """ This test validates registration of
141            properties_stats view.
142        """
143        view = queryMultiAdapter((self.portal, self.portal.REQUEST),
144                                 name="properties_stats")
145
146        self.assert_(view, "Properties Stats view isn't registered")
147
148
149    def test_PortletsStats(self):
150        """ This test validates registration of
151            portlets_stats view.
152        """
153        view = queryMultiAdapter((self.portal, self.portal.REQUEST),
154                                 name="portlets_stats")
155
156        self.assert_(view, "Portlets Stats view isn't registered")
157
158class TestOwnershipByType(TestCase):
159    """Tests all ownership by type view methods."""
160
161    layer = SetUpContent
162
163    def afterSetUp(self):
164        self.view = queryMultiAdapter((self.portal, self.portal.REQUEST),
165                                 name="ownership_by_type")
166        self.pc = self.portal.portal_catalog
167
168    def test_getUsers(self):
169        """ Tests method that returns ordered list of users."""
170        users = [u[0] for u in self.layer.users]
171        users.reverse()
172        self.assert_(False not in map(lambda u1, u2:u1==u2,
173                     users, self.view.getUsers()))
174
175    def test_getTypes(self):
176        """ Tests method that returns ordered list of types."""
177        data = {}
178        index = self.pc._catalog.getIndex('portal_type')
179        for k in index._index.keys():
180            if not k:
181                continue
182            haslen = hasattr(index._index[k], '__len__')
183            if haslen:
184                data[k] = len(index._index[k])
185            else:
186                data[k] = 1
187        data = data.items()
188        data.sort(lambda a, b: a[1] - b[1])
189        data.reverse()
190        types = [i[0] for i in data]
191        self.assert_(False not in map(lambda t1, t2:t1==t2,
192                     self.view.getTypes(), types))
193
194    def test_getContent(self):
195        """ This test verifies method that returns list of numbers.
196            Each number is amount of specified content type objects
197            that owned  by particular user.
198        """
199        # we need to login in to the site as Manager to be able to
200        # see catalog results
201        self.loginAsPortalOwner()
202
203        for type_ in self.layer.types_:
204            self.assert_(False not in \
205            map(lambda i, j:i==j, [len(self.pc(portal_type=type_, Creator=user))
206                                   for user in self.view.getUsers()],
207                                  self.view.getContent(type_)))
208
209    def test_getChart(self):
210        """ This test verifies creation of chart image tag."""
211        chart_tag = """<img src="http://chart.apis.google.com/chart?chxt=y&amp;
212                       chds=0,57&amp;chd=t:19.0,18.0,17.0,16.0,15.0,14.0,
213                       13.0,12.0,11.0,10.0|19.0,18.0,17.0,16.0,15.0,14.0,13.0,
214                       12.0,11.0,10.0|19.0,18.0,17.0,16.0,15.0,14.0,13.0,12.0,
215                       11.0,10.0|0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0|&amp;
216                       chxr=0,0,57&amp;chco=669933,cc9966,993300,ff6633,e8e4e3,
217                       a9a486,dcb57e,ffcc99,996633,333300,00ff00&amp;chl=user9|
218                       user8|user7|user6|user5|user4|user3|user2|user1|user0&amp;
219                       chbh=a,10,0&amp;chs=800x375&amp;cht=bvs&amp;
220                       chtt=Content+ownership+by+type&amp;chdl=Folder|Document|
221                       Event|Topic|Other+types&amp;chdlp=b" />"""
222        self.loginAsPortalOwner()
223        self.assertEqual(*map(lambda s:''.join(s.split()),
224                              [chart_tag, self.view.getChart()]))
225
226class TestOwnershipByState(TestCase):
227    """Tests all ownership by state view methods."""
228
229    layer = SetUpContent
230
231    states = ['private', 'published', 'pending']
232
233    def afterSetUp(self):
234        self.view = queryMultiAdapter((self.portal, self.portal.REQUEST),
235                                 name="ownership_by_state")
236        self.pc = self.portal.portal_catalog
237
238    def test_getUsers(self):
239        """ Tests method that returns ordered list of users."""
240        users = [u[0] for u in self.layer.users]
241        users.reverse()
242        self.assert_(False not in map(lambda u1, u2:u1==u2,
243                     users, self.view.getUsers()))
244
245    def test_getStates(self):
246        """ Tests method that returns ordered list of states."""
247        self.assert_(False not in map(lambda s1, s2:s1==s2,
248                     ['private', 'published'], self.view.getStates()))
249
250    def test_getContent(self):
251        """ This test verifies method that returns list of numbers.
252            Each number is amount of specified content type objects
253            that are in particular workflow state.
254        """
255        # we need to login in to the site as Manager to be able to
256        # see catalog results
257        self.loginAsPortalOwner()
258
259        for state in self.states:
260            self.assert_(False not in \
261            map(lambda i, j:i==j,[len(self.pc(review_state=state, Creator=user))
262                                  for user in self.view.getUsers()],
263                                 self.view.getContent(state)))
264
265    def test_getChart(self):
266        """ This test verifies creation of chart image tag."""
267        chart_tag = """<imgsrc="http://chart.apis.google.com/chart?chxt=y&amp;
268                       chds=0,57&amp;chd=t:57.0,54.0,51.0,48.0,45.0,42.0,39.0,
269                       36.0,33.0,30.0|0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
270                       0.0|0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0&amp;chxr=0,
271                       0,57&amp;chco=669933,cc9966,993300,ff6633,e8e4e3,a9a486,
272                       dcb57e,ffcc99,996633,333300,00ff00&amp;chl=user9|user8|
273                       user7|user6|user5|user4|user3|user2|user1|user0&amp;
274                       chbh=a,10,0&amp;chs=800x375&amp;cht=bvs&amp;
275                       chtt=Content+ownership+by+state&amp;chdl=private|
276                       published|No+workflow&amp;chdlp=b"/>"""
277        self.loginAsPortalOwner()
278        self.assertEqual(*map(lambda s:''.join(s.split()),
279                              [chart_tag, self.view.getChart()]))
280
281class TestTypeByState(TestCase):
282    """Tests all type_by_state view methods."""
283    layer = SetUpContent
284    states = ['private', 'published', 'pending']
285
286    def afterSetUp(self):
287        self.view = queryMultiAdapter((self.portal, self.portal.REQUEST),
288                                 name="type_by_state")
289        self.pc = self.portal.portal_catalog
290
291    def test_getTypes(self):
292        """ Tests method that returns ordered list of types."""
293        self.assert_(False not in map(lambda t1, t2:t1==t2,
294                                      ['Folder', 'Document', 'Event', 'Topic'],
295                                      self.view.getTypes()))
296
297    def test_getStates(self):
298        """ Tests method that returns ordered list of states."""
299        self.assert_(False not in map(lambda s1, s2:s1==s2,
300                     ['private', 'published'], self.view.getStates()))
301
302    def test_getContent(self):
303        """ This test verifies method that returns list of numbers.
304            Each number is amount of specified content type objects
305            that owned  by particular user.
306        """
307        # we need to login in to the site as Manager to be able to
308        # see catalog results
309        self.loginAsPortalOwner()
310
311        for state in self.states:
312            self.assert_(False not in \
313            map(lambda i, j:i==j, [len(self.pc(portal_type=type_,
314                                               review_state=state))
315                                   for type_ in self.view.getTypes()],
316                                  self.view.getContent(state)))
317
318    def test_getChart(self):
319        """ This test verifies creation of chart image tag."""
320        chart_tag = """ <imgsrc="http://chart.apis.google.com/chart?chxt=y&amp;
321                        chds=0,159&amp;chd=t:156.0,145.0,145.0,0.0|3.0,1.0,0.0,
322                        3.0|0.0,0.0,0.0,0.0&amp;chxr=0,0,159&amp;chco=669933,
323                        cc9966,993300,ff6633,e8e4e3,a9a486,dcb57e,ffcc99,996633,
324                        333300,00ff00&amp;chl=Folder|Document|Event|Topic&amp;
325                        chbh=a,10,0&amp;chs=800x375&amp;cht=bvs&amp;
326                        chtt=Content+type+by+state&amp;chdl=private|published|
327                        No+workflow&amp;chdlp=b"/>"""
328
329        self.loginAsPortalOwner()
330        self.assertEqual(*map(lambda s:''.join(s.split()),
331                              [chart_tag, self.view.getChart()]))
332
333class LegacyPortlets(TestCase):
334    """Test all legasy_portlets view methods."""
335
336
337    def afterSetUp(self):
338        self.view = queryMultiAdapter((self.portal, self.portal.REQUEST),
339                                       name='legacy_portlets')
340
341    def test_getPortlets(self):
342        """Tests method that returns portlets info."""
343
344        # this is true for Plone 4
345        self.assert_(self.view.getPortlets() == [])
346
347    def test_getAllPortletExpressions(self):
348        """Tests method that returns portlets expressions."""
349
350        # this is true for Plone 4
351        self.assert_(self.view.getAllPortletExpressions() == [])
352
353class TestPropertiesStats(TestCase):
354    """Tests all properties_stats view methods."""
355
356    def afterSetUp(self):
357        self.view = queryMultiAdapter((self.portal, self.portal.REQUEST),
358                                       name='properties_stats')
359
360    def test_getPropsList(self):
361        self.view.propname = 'title'
362        result = [u'Plone site', u'Welcome to Plone',
363                  u'News', u'Events', u'Users']
364
365        for title in result:
366            self.assert_(title in [prop_info['slots']
367                     for prop_info in self.view.getPropsList()])
368
369
370class TestPortletsStats(TestCase):
371    """Tests all properties_stats view methods."""
372
373    def afterSetUp(self):
374        self.view = queryMultiAdapter((self.portal, self.portal.REQUEST),
375                                       name='portlets_stats')
376
377    def test_getPropsList(self):
378        """Tests method that collects portlet information from site."""
379
380        self.loginAsPortalOwner()
381        portlet = getUtility(IPortletType, name='portlets.Calendar')
382        mapping = \
383          self.portal.restrictedTraverse('++contextportlets++plone.leftcolumn')
384        mapping.restrictedTraverse('+/' + portlet.addview)()
385
386        plone_portlets_info = filter(lambda info:info['path'] == '/plone',
387                                     self.view.getPropsList())
388        lslots = plone_portlets_info[0]['left_slots']
389        self.assert_(filter(lambda info: info['title'] == 'Calendar', lslots))
390
391
392def test_suite():
393    from unittest import TestSuite, makeSuite
394
395    test_suite = unittest.TestSuite([
396
397        # Unit tests
398        #doctestunit.DocFileSuite(
399        #    'README.txt', package='quintagroup.contentstats',
400        #    setUp=testing.setUp, tearDown=testing.tearDown),
401
402        #doctestunit.DocTestSuite(
403        #    module='quintagroup.contentstats.mymodule',
404        #    setUp=testing.setUp, tearDown=testing.tearDown),
405
406
407        # Integration tests that use PloneTestCase
408        #ztc.ZopeDocFileSuite(
409        #    'README.txt', package='quintagroup.contentstats',
410        #    test_class=TestCase),
411
412        #ztc.FunctionalDocFileSuite(
413        #    'browser.txt', package='quintagroup.contentstats',
414        #    test_class=TestCase),
415
416        ])
417
418    test_suite.addTest(makeSuite(TestQAInstallation))
419    test_suite.addTest(makeSuite(TestOwnershipByType))
420    test_suite.addTest(makeSuite(TestOwnershipByState))
421    test_suite.addTest(makeSuite(TestTypeByState))
422    test_suite.addTest(makeSuite(LegacyPortlets))
423    test_suite.addTest(makeSuite(TestPropertiesStats))
424    test_suite.addTest(makeSuite(TestPortletsStats))
425    return test_suite
426
427if __name__ == '__main__':
428    unittest.main(defaultTest='test_suite')
Note: See TracBrowser for help on using the repository browser.