report/render: fixes from xrg branch
[odoo/odoo.git] / addons / base_module_quality / speed_test / speed_test.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 from tools.translate import _
23 import pooler
24
25 from base_module_quality import base_module_quality
26
27 class CounterCursor(object):
28     def __init__(self, real_cursor):
29         self.cr = real_cursor
30         self.count = 0
31
32     def reset(self):
33         self.count = 0
34
35     def execute(self, query, *args, **kwargs):
36         if query.lower().startswith('select '):
37             self.count += 1
38         return self.cr.execute(query, *args, **kwargs)
39
40     def __getattr__(self, attr):
41         return getattr(self.cr, attr)
42
43
44 class quality_test(base_module_quality.abstract_quality_check):
45
46     def __init__(self):
47         super(quality_test, self).__init__()
48         self.bool_installed_only = True
49         self.name = _("Speed Test")
50         self.note = _("""
51 This test checks the speed of the module. Note that at least 5 demo data is needed in order to run it.
52
53 """)
54         self.min_score = 30
55         return None
56
57     def run_test(self, cr, uid, module_path):
58         pool = pooler.get_pool(cr.dbname)
59         module_name = module_path.split('/')[-1]
60         obj_list = self.get_objects(cr, uid, module_name)
61
62         # remove osv_memory class becaz it does not have demo data
63         if obj_list:
64             cr.execute("select w.res_model from ir_actions_todo as t left join ir_act_window as w on t.action_id=w.id where w.res_model IN %s",(tuple(obj_list),))
65             res = cr.fetchall()
66             for remove_obj in res:
67                 if remove_obj and (remove_obj[0] in obj_list):
68                     obj_list.remove(remove_obj[0])
69
70         result_dict2 = {}
71         if not obj_list:
72             self.error = True
73             self.result += _("Given module has no objects.Speed test can work only when new objects are created in the module along with demo data")
74             return None
75         obj_counter = 0
76         score = 0.0
77         try:
78             obj_ids = self.get_ids(cr, uid, obj_list)
79         except Exception,e:
80             self.log.warning("Cannot get ids:", exc_info=True)
81             obj_ids= {}
82             self.result_details += e.message
83         result_dict = {}
84         result_dict2 = {}
85         self.result_details += _("<html>O(1) means that the number of SQL requests to read the object does not depand on the number of objects we are reading. This feature is mostly wished.\n</html>")
86         ccr = CounterCursor(cr)
87         for obj, ids in obj_ids.items():
88             code_base_complexity = 0
89             code_half_complexity = 0
90             code_size_complexity = 0
91             obj_counter += 1
92             ids = ids[:100]
93             size = len(ids)
94             list2 = []
95             if size:
96                 speed_list = []
97                 try:
98                     # perform the operation once to put data in cache
99                     pool.get(obj).read(cr, uid, ids)
100
101                     ccr.reset()
102                     pool.get(obj).read(ccr, uid, [ids[0]])
103                     code_base_complexity = ccr.count
104
105                     ccr.reset()
106                     pool.get(obj).read(ccr, uid, ids[:size/2])
107                     code_half_complexity = ccr.count
108
109                     ccr.reset()
110                     pool.get(obj).read(ccr, uid, ids)
111                     code_size_complexity = ccr.count
112
113                 except Exception, e:
114                     self.log.warning('Error in read method', exc_info=True)
115                     list2 = [obj, _("Error in Read method")]
116                     speed_list = [obj, size, code_base_complexity, code_half_complexity, code_size_complexity, _("Error in Read method:" + str(e))]
117                 else:
118                     if size < 5:
119                         speed_list = [obj, size, code_base_complexity, code_half_complexity, code_size_complexity, _("Warning! Not enough demo data")]
120                         list2 = [obj, _("No enough data")]
121                     else:
122                         if code_size_complexity <= (code_base_complexity + size):
123                             complexity = _("O(1)")
124                             score += 1
125                             list2 = [obj, _("Efficient")]
126                         else:
127                             complexity = _("O(n) or worst")
128                             list2 = [obj, _("Not Efficient")]
129
130                         speed_list = [obj, size, code_base_complexity, code_half_complexity, code_size_complexity, complexity]
131             else:
132                 speed_list = [obj, size, "", "", "", _("Warning! Object has no demo data")]
133                 list2 = [obj, _("No data")]
134             result_dict[obj] = speed_list
135             result_dict2[obj] = list2
136         self.score = obj_counter and score / obj_counter or 0.0
137         if self.score*100 < self.min_score:
138             self.message = _('Score is below than minimal score(%s%%)') % self.min_score
139         self.result_details += self.get_result_details(result_dict)
140         self.result += self.get_result(result_dict2)
141         return None
142
143     def get_result(self, dict_speed):
144         header = ('{| border="1" cellspacing="0" cellpadding="5" align="left" \n! %-40s \n! %-10s', [_('Object Name'), _('Result')])
145         if not self.error:
146             return self.format_table(header, data_list=dict_speed)
147         return ""
148
149     def get_result_details(self, dict_speed):
150         str_html = '''<html><head>%s</head><body><table class="tablestyle">'''%(self.get_style())
151         header = ('<tr><th class="tdatastyle" >%s</th><th class="tdatastyle">%s</th><th class="tdatastyle">%s</th><th class="tdatastyle">%s</th><th class="tdatastyle">%s</th><th class="tdatastyle">%s</th></tr>', [_('Object Name'), _('N (Number of Records)'), _('1'), _('N/2'), _('N'), _('Reading Complexity')])
152         if not self.error:
153             res = str_html + self.format_html_table(header, data_list=dict_speed) + '</table></body></html>'
154             res = res.replace('''<td''', '''<td class="tdatastyle" ''')
155             return res
156         return ""
157
158 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: