source: products/quintagroup.analytics/trunk/quintagroup/analytics/tests.py @ 3380

Last change on this file since 3380 was 3380, checked in by kroman0, 12 years ago

Fixed pep8

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