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

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

Fixed tests for plone 4.1+

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        self.plone_version = portal_migration.getInstanceVersion()
325
326    def test_getTypes(self):
327        """ Tests method that returns ordered list of types."""
328        index = self.pc._catalog.getIndex('portal_type')
329        data = {}
330
331        for k in index._index.keys():
332            if not k:
333                continue
334            haslen = hasattr(index._index[k], '__len__')
335
336            if haslen:
337                data[k] = len(index._index[k])
338
339            else:
340                data[k] = 1
341        data = data.items()
342        data.sort(lambda a, b: a[1] - b[1])
343        data.reverse()
344
345        types = [i[0] for i in data]
346        self.assert_(False not in map(lambda t1, t2: t1 == t2, types,
347                                      self.view.getTypes()))
348
349    def test_getStates(self):
350        """ Tests method that returns ordered list of states."""
351        self.assert_(False not in map(lambda s1, s2: s1 == s2,
352                     ['private', 'published'], self.view.getStates()))
353
354    def test_getContent(self):
355        """ This test verifies method that returns list of numbers.
356            Each number is amount of specified content type objects
357            that owned  by particular user.
358        """
359        # we need to login in to the site as Manager to be able to
360        # see catalog results
361        self.loginAsPortalOwner()
362
363        for state in self.states:
364            self.assert_(False not in \
365            map(lambda i, j: i == j, [len(self.pc(portal_type=type_,
366                                               review_state=state))
367                                   for type_ in self.view.getTypes()],
368                                  self.view.getContent(state)))
369
370    def test_getChart(self):
371        """ This test verifies creation of chart image tag."""
372        plone33chart_tag = \
373            '<imgsrc="http://chart.apis.google.com/chart?chxt=y&amp;chds=0,'\
374            '156&amp;chd=t:156.0,145.0,145.0,0.0,0.0|0.0,1.0,0.0,3.0,3.0|'\
375            '0.0,0.0,0.0,0.0,0.0&amp;chxr=0,0,156&amp;chco=669933,cc9966,'\
376            '993300,ff6633,e8e4e3,a9a486,dcb57e,ffcc99,996633,333300,'\
377            '00ff00&amp;chl=Folder|Document|Event|Large+Plone+Folder|'\
378            'Topic&amp;chbh=a,10,0&amp;chs=800x375&amp;cht=bvs&amp;'\
379            'chtt=Content+type+by+state&amp;chdl=private|published|'\
380            'No+workflow&amp;chdlp=b"/>'
381        plone4chart_tag = \
382            '<imgsrc="http://chart.apis.google.com/chart?chxt=y&amp;'\
383            'chds=0,159&amp;chd=t:156.0,145.0,145.0,0.0|3.0,1.0,0.0,'\
384            '3.0|0.0,0.0,0.0,0.0&amp;chxr=0,0,159&amp;chco=669933,'\
385            'cc9966,993300,ff6633,e8e4e3,a9a486,dcb57e,ffcc99,996633,'\
386            '333300,00ff00&amp;chl=folder|document|event|topic&amp;'\
387            'chbh=a,10,0&amp;chs=800x375&amp;cht=bvs&amp;'\
388            'chtt=content+type+by+state&amp;chdl=private|published|'\
389            'no+workflow&amp;chdlp=b"/>'
390        plone41chart_tag = \
391            '<imgsrc="http://chart.apis.google.com/chart?chxt=y&amp;'\
392            'chds=0,159&amp;chd=t:156.0,145.0,145.0,0.0|3.0,1.0,0.0,'\
393            '3.0|0.0,0.0,0.0,0.0&amp;chxr=0,0,159&amp;chco=669933,'\
394            'cc9966,993300,ff6633,e8e4e3,a9a486,dcb57e,ffcc99,996633,'\
395            '333300,00ff00&amp;chl=folder|document|event|topic&amp;'\
396            'chbh=a,10,0&amp;chs=800x375&amp;cht=bvs&amp;'\
397            'chtt=content+type+by+state&amp;chdl=private|published|'\
398            'no+workflow&amp;chdlp=b"/>'
399
400        if self.plone_version < "4.0":
401            chart_tag = plone33chart_tag
402        elif self.plone_version > "4.1":
403            chart_tag = plone41chart_tag
404        else:
405            chart_tag = plone4chart_tag
406
407        self.loginAsPortalOwner()
408        self.assertEqual(*map(lambda s: ''.join(s.split()),
409                              [chart_tag, self.view.getChart()]))
410
411
412class LegacyPortlets(TestCase):
413    """Test all legasy_portlets view methods."""
414
415    def afterSetUp(self):
416        self.view = queryMultiAdapter((self.portal, self.portal.REQUEST),
417                                       name='legacy_portlets')
418
419    def test_getPortlets(self):
420        """Tests method that returns portlets info."""
421
422        # this is true for Plone 4
423        self.assert_(self.view.getPortlets() == [])
424
425    def test_getAllPortletExpressions(self):
426        """Tests method that returns portlets expressions."""
427
428        # this is true for Plone 4
429        self.assert_(self.view.getAllPortletExpressions() == [])
430
431
432class TestPropertiesStats(TestCase):
433    """Tests all properties_stats view methods."""
434
435    def afterSetUp(self):
436        self.view = queryMultiAdapter((self.portal, self.portal.REQUEST),
437                                       name='properties_stats')
438
439    def test_getPropsList(self):
440        self.view.propname = 'title'
441        result = [u'Plone site', u'Welcome to Plone',
442                  u'News', u'Events', u'Users']
443
444        for title in result:
445            self.assert_(title in [prop_info['slots']
446                     for prop_info in self.view.getPropsList()])
447
448
449class TestPortletsStats(TestCase):
450    """Tests all properties_stats view methods."""
451
452    def afterSetUp(self):
453        self.view = queryMultiAdapter((self.portal, self.portal.REQUEST),
454                                       name='portlets_stats')
455
456    def test_getPropsList(self):
457        """Tests method that collects portlet information from site."""
458
459        self.loginAsPortalOwner()
460        portlet = getUtility(IPortletType, name='portlets.Calendar')
461        mapping = \
462          self.portal.restrictedTraverse('++contextportlets++plone.leftcolumn')
463        mapping.restrictedTraverse('+/' + portlet.addview)()
464
465        plone_portlets_info = filter(lambda info: info['path'] == '/plone',
466                                     self.view.getPropsList())
467        lslots = plone_portlets_info[0]['left_slots']
468        self.assert_(info for info in lslots if info['title'] == 'Calendar')
469
470
471def test_suite():
472    test_suite = unittest.TestSuite([
473
474        # Unit tests
475        #doctestunit.DocFileSuite(
476        #    'README.txt', package='quintagroup.contentstats',
477        #    setUp=testing.setUp, tearDown=testing.tearDown),
478
479        #doctestunit.DocTestSuite(
480        #    module='quintagroup.contentstats.mymodule',
481        #    setUp=testing.setUp, tearDown=testing.tearDown),
482
483
484        # Integration tests that use PloneTestCase
485        #ztc.ZopeDocFileSuite(
486        #    'README.txt', package='quintagroup.contentstats',
487        #    test_class=TestCase),
488
489        #ztc.FunctionalDocFileSuite(
490        #    'browser.txt', package='quintagroup.contentstats',
491        #    test_class=TestCase),
492
493        ])
494
495    test_suite.addTest(unittest.makeSuite(TestQAInstallation))
496    test_suite.addTest(unittest.makeSuite(TestOwnershipByType))
497    test_suite.addTest(unittest.makeSuite(TestOwnershipByState))
498    test_suite.addTest(unittest.makeSuite(TestTypeByState))
499    test_suite.addTest(unittest.makeSuite(LegacyPortlets))
500    test_suite.addTest(unittest.makeSuite(TestPropertiesStats))
501    test_suite.addTest(unittest.makeSuite(TestPortletsStats))
502    return test_suite
503
504if __name__ == '__main__':
505    unittest.main(defaultTest='test_suite')
Note: See TracBrowser for help on using the repository browser.