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

Last change on this file since 3169 was 3169, checked in by vmaksymiv, 13 years ago

pep8 fixes

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