source: products/quintagroup.analytics/branches/treemap/quintagroup/analytics/tests/tests.py @ 3404

Last change on this file since 3404 was 3404, checked in by potar, 8 years ago

fixed 'import PIL', pylint

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