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

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

Tests fixed for plone 3.x

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