[REF] Splitted YAML custom tags definition in itw own file (needed by module recorder).
[odoo/odoo.git] / bin / tools / yaml_import.py
1 # -*- encoding: utf-8 -*-
2 import types
3 import time # used to eval time.strftime expressions
4 import logging
5
6 import pooler
7 import netsvc
8 import misc
9 from config import config
10 import yaml_tag
11
12 import yaml
13
14 logger_channel = 'tests'
15
16 class YamlImportException(Exception):
17     pass
18
19 class YamlImportAbortion(Exception):
20     pass
21
22 def _is_yaml_mapping(node, tag_constructor):
23     value = isinstance(node, types.DictionaryType) \
24         and len(node.keys()) == 1 \
25         and isinstance(node.keys()[0], tag_constructor)
26     return value
27
28 def is_comment(node):
29     return isinstance(node, types.StringTypes)
30
31 def is_assert(node):
32     return _is_yaml_mapping(node, yaml_tag.Assert)
33
34 def is_record(node):
35     return _is_yaml_mapping(node, yaml_tag.Record)
36
37 def is_python(node):
38     return _is_yaml_mapping(node, yaml_tag.Python)
39
40 def is_menuitem(node):
41     return isinstance(node, yaml_tag.Menuitem) \
42         or _is_yaml_mapping(node, yaml_tag.Menuitem)
43
44 def is_function(node):
45     return isinstance(node, yaml_tag.Function) \
46         or _is_yaml_mapping(node, yaml_tag.Function)
47
48 def is_report(node):
49     return isinstance(node, yaml_tag.Report)
50
51 def is_workflow(node):
52     return isinstance(node, yaml_tag.Workflow)
53
54 def is_act_window(node):
55     return isinstance(node, yaml_tag.ActWindow)
56
57 def is_delete(node):
58     return isinstance(node, yaml_tag.Delete)
59
60 def is_context(node):
61     return isinstance(node, yaml_tag.Context)
62
63 def is_url(node):
64     return isinstance(node, yaml_tag.Url)
65
66 def is_eval(node):
67     return isinstance(node, yaml_tag.Eval)
68     
69 def is_ir_set(node):
70     return _is_yaml_mapping(node, yaml_tag.IrSet)
71
72
73 class TestReport(object):
74     def __init__(self):
75         self._report = {}
76
77     def record(self, success, severity):
78         """
79         Records the result of an assertion for the failed/success count.
80         Returns success.
81         """
82         if severity in self._report:
83             self._report[severity][success] += 1
84         else:
85             self._report[severity] = {success: 1, not success: 0}
86         return success
87
88     def __str__(self):
89         res = []
90         res.append('\nAssertions report:\nLevel\tsuccess\tfailure')
91         success = failure = 0
92         for severity in self._report:
93             res.append("%s\t%s\t%s" % (severity, self._report[severity][True], self._report[severity][False]))
94             success += self._report[severity][True]
95             failure += self._report[severity][False]
96         res.append("total\t%s\t%s" % (success, failure))
97         res.append("end of report (%s assertion(s) checked)" % success + failure)
98         return "\n".join(res)
99
100 class RecordDictWrapper(dict):
101     """
102     Used to pass a record as locals in eval:
103     records do not strictly behave like dict, so we force them to.
104     """
105     def __init__(self, record):
106         self.record = record 
107     def __getitem__(self, key):
108         if key in self.record:
109             return self.record[key]
110         return dict.__getitem__(self, key)
111  
112 class YamlInterpreter(object):
113     def __init__(self, cr, module, id_map, mode, filename, noupdate=False):
114         self.cr = cr
115         self.module = module
116         self.id_map = id_map
117         self.mode = mode
118         self.filename = filename
119         self.assert_report = TestReport()
120         self.noupdate = noupdate
121         self.logger = logging.getLogger("%s.%s" % (logger_channel, self.module))
122         self.pool = pooler.get_pool(cr.dbname)
123         self.uid = 1
124         self.context = {} # opererp context
125         self.eval_context = {'ref': self._ref, '_ref': self._ref} # added '_ref' so that record['ref'] is possible
126
127     def _ref(self):
128         return lambda xml_id: self.get_id(xml_id)
129
130     def get_model(self, model_name):
131         model = self.pool.get(model_name)
132         assert model, "The model %s does not exist." % (model_name,)
133         return model
134     
135     def validate_xml_id(self, xml_id):
136         id = xml_id
137         if '.' in xml_id:
138             module, id = xml_id.split('.', 1)
139             assert '.' not in id, "The ID reference '%s' must contains maximum one dot.\n" \
140                                   "It is used to refer to other modules ID, in the form: module.record_id" \
141                                   % (xml_id,)
142             if module != self.module:
143                 module_count = self.pool.get('ir.module.module').search_count(self.cr, self.uid, \
144                         ['&', ('name', '=', module), ('state', 'in', ['installed'])])
145                 assert module_count == 1, 'The ID "%s" refers to an uninstalled module.' % (xml_id,)
146         if len(id) > 64: # TODO where does 64 come from (DB is 128)? should be a constant or loaded form DB
147             self.logger.log(logging.ERROR, 'id: %s is to long (max: 64)', id)
148
149     def get_id(self, xml_id):
150         if not xml_id:
151             raise YamlImportException("The xml_id should be a non empty string.")
152         if isinstance(xml_id, types.IntType):
153             id = xml_id
154         elif xml_id in self.id_map:
155             id = self.id_map[xml_id]
156         else:
157             if '.' in xml_id:
158                 module, xml_id = xml_id.split('.', 1)
159             else:
160                 module = self.module
161             ir_id = self.pool.get('ir.model.data')._get_id(self.cr, self.uid, module, xml_id)
162             obj = self.pool.get('ir.model.data').read(self.cr, self.uid, ir_id, ['res_id'])
163             id = int(obj['res_id'])
164             self.id_map[xml_id] = id
165         return id
166     
167     def get_context(self, node, eval_dict):
168         context = self.context.copy()
169         if node.context:
170             context.update(eval(node.context, eval_dict))
171         return context
172
173     def isnoupdate(self, node):
174         return self.noupdate or node.noupdate or False
175     
176     def process_comment(self, node):
177         return node
178
179     def _log_assert_failure(self, severity, msg, *args):
180         self.assert_report.record(False, severity)
181         self.logger.log(severity, msg, *args)
182         if severity >= config['assert_exit_level']:
183             raise YamlImportAbortion('Severe assertion failure (%s), aborting.' % logging.getLevelName(severity))
184         return
185
186     def _get_assertion_id(self, assertion):
187         if assertion.id:
188             ids = [self.get_id(assertion.id)]
189         elif assertion.search:
190             q = eval(assertion.search, self.eval_context)
191             ids = self.pool.get(assertion.model).search(self.cr, self.uid, q, context=assertion.context)
192         if not ids:
193             raise YamlImportException('Nothing to assert: you must give either an id or a search criteria.')
194         return ids
195
196     def process_assert(self, node):
197         assertion, expressions = node.items()[0]
198
199         if self.isnoupdate(assertion) and self.mode != 'init':
200             return
201         model = self.get_model(assertion.model)
202         ids = self._get_assertion_id(assertion)
203         if assertion.count and len(ids) != assertion.count:
204             msg = 'assertion "%s" failed!\n'   \
205                   ' Incorrect search count:\n' \
206                   ' expected count: %d\n'      \
207                   ' obtained count: %d\n'
208             args = (assertion.string, assertion.count, len(ids))
209             self._log_assert_failure(assertion.severity, msg, *args)
210         else:
211             context = self.get_context(assertion, self.eval_context)
212             for id in ids:
213                 record = model.browse(self.cr, self.uid, id, context)
214                 for test in expressions.get('test', ''):
215                     try:
216                         success = eval(test, self.eval_context, RecordDictWrapper(record))
217                     except Exception, e:
218                         raise YamlImportAbortion(e)
219                     if not success:
220                         msg = 'Assertion "%s" FAILED\ntest: %s\n'
221                         args = (assertion.string, test)
222                         self._log_assert_failure(assertion.severity, msg, *args)
223                         return
224             else: # all tests were successful for this assertion tag (no break)
225                 self.assert_report.record(True, assertion.severity)
226
227     def process_record(self, node):
228         record, fields = node.items()[0]
229
230         self.validate_xml_id(record.id)
231         if self.isnoupdate(record) and self.mode != 'init':
232             model = self.get_model(record.model)
233             record_dict = self._create_record(model, fields)
234             self.logger.debug("RECORD_DICT %s" % record_dict)
235             id = self.pool.get('ir.model.data')._update(self.cr, self.uid, record.model, \
236                     self.module, record_dict, record.id, noupdate=self.isnoupdate(record), mode=self.mode)
237             self.id_map[record.id] = int(id)
238             if config.get('import_partial', False):
239                 self.cr.commit()
240     
241     def _create_record(self, model, fields):
242         record_dict = {}
243         for field_name, expression in fields.items():
244             field_value = self._eval_field(model, field_name, expression)
245             record_dict[field_name] = field_value
246         return record_dict        
247     
248     def _eval_field(self, model, field_name, expression):
249         column = model._columns[field_name]
250         if column._type == "many2one":
251             value = self.get_id(expression)
252         elif column._type == "one2many":
253             other_model = self.get_model(column._obj)
254             value = [(0, 0, self._create_record(other_model, fields)) for fields in expression]
255         elif column._type == "many2many":
256             ids = [self.get_id(xml_id) for xml_id in expression]
257             value= [(6, 0, ids)]
258         else: # scalar field
259             if isinstance(expression, yaml_tag.Eval):
260                 value = eval(expression.expression)
261             else:
262                 value = expression
263             # raise YamlImportException('Unsupported column "%s" or value %s:%s' % (field_name, type(expression), expression))
264         return value
265     
266     def process_context(self, node):
267         self.context = node.__dict__
268         if node.uid:
269             self.uid = self.get_id(node.uid)
270         if node.noupdate:
271             self.noupdate = node.noupdate
272     
273     def process_python(self, node):
274         def log(msg, *args):
275             self.logger.log(logging.TEST, msg, *args)
276         python, statements = node.items()[0]
277         model = self.get_model(python.model)
278         statements = statements.replace("\r\n", "\n")
279         code_context = {'self': model, 'cr': self.cr, 'uid': self.uid, 'log': log, 'context': self.context}
280         try:
281             code = compile(statements, self.filename, 'exec')
282             eval(code, {'ref': self.get_id}, code_context)
283         except AssertionError, e:
284             self._log_assert_failure(python.severity, 'AssertionError in Python code %s: %s', python.name, e)
285             return
286         except Exception, e:
287             raise YamlImportAbortion(e)
288         else:
289             self.assert_report.record(True, python.severity)
290     
291     def process_workflow(self, node):
292         workflow, values = node.items()[0]
293         if self.isnoupdate(workflow) and self.mode != 'init':
294             return
295         model = self.get_model(workflow.model)
296         if workflow.ref:
297             id = self.get_id(workflow.ref)
298         else:
299             if not values:
300                 raise YamlImportException('You must define a child node if you do not give a ref.')
301             if not len(values) == 1:
302                 raise YamlImportException('Only one child node is accepted (%d given).' % len(values))
303             value = values[0]
304             if not 'model' in value and (not 'eval' in value or not 'search' in value):
305                 raise YamlImportException('You must provide a "model" and an "eval" or "search" to evaluate.')
306             value_model = self.get_model(value['model'])
307             local_context = {'obj': lambda x: value_model.browse(self.cr, self.uid, x, context=self.context)}
308             local_context.update(self.id_map)
309             id = eval(value['eval'], self.eval_context, local_context)
310         
311         if workflow.uid is not None:
312             uid = workflow.uid
313         else:
314             uid = self.uid
315         wf_service = netsvc.LocalService("workflow")
316         wf_service.trg_validate(uid, model, id, workflow.action, self.cr)
317         
318     def process_function(self, node):
319         function, values = node.items()[0]
320         if self.isnoupdate(function) and self.mode != 'init':
321             return
322         context = self.get_context(function, self.eval_context)
323         args = []
324         if function.eval:
325             args = eval(function.eval, self.eval_context)
326         for value in values:
327             if not 'model' in value and (not 'eval' in value or not 'search' in value):
328                 raise YamlImportException('You must provide a "model" and an "eval" or "search" to evaluate.')
329             value_model = self.get_model(value['model'])
330             local_context = {'obj': lambda x: value_model.browse(self.cr, self.uid, x, context=context)}
331             local_context.update(self.id_map)
332             id = eval(value['eval'], self.eval_context, local_context)
333             if id != None:
334                 args.append(id)
335         model = self.get_model(function.model)
336         method = function.name
337         getattr(model, method)(self.cr, self.uid, *args)
338     
339     def _set_group_values(self, node, values):
340         if node.groups:
341             group_names = node.groups.split(',')
342             groups_value = []
343             for group in group_names:
344                 if group.startswith('-'):
345                     group_id = self.get_id(group[1:])
346                     groups_value.append((3, group_id))
347                 else:
348                     group_id = self.get_id(group)
349                     groups_value.append((4, group_id))
350             values['groups_id'] = groups_value
351
352     def process_menuitem(self, node):
353         self.validate_xml_id(node.id)
354
355         if not node.parent:
356             parent_id = False
357             self.cr.execute('select id from ir_ui_menu where parent_id is null and name=%s', (node.name,))
358             res = self.cr.fetchone()
359             values = {'parent_id': parent_id, 'name': node.name}
360         else:
361             parent_id = self.get_id(node.parent)
362             values = {'parent_id': parent_id}
363             if node.name:
364                 values['name'] = node.name
365             try:
366                 res = [ self.get_id(node.id) ]
367             except: # which exception ?
368                 res = None
369
370         if node.action:
371             action_type = node.type or 'act_window'
372             icons = {
373                 "act_window": 'STOCK_NEW',
374                 "report.xml": 'STOCK_PASTE',
375                 "wizard": 'STOCK_EXECUTE',
376                 "url": 'STOCK_JUMP_TO',
377             }
378             values['icon'] = icons.get(action_type, 'STOCK_NEW')
379             if action_type == 'act_window':
380                 action_id = self.get_id(node.action)
381                 self.cr.execute('select view_type,view_mode,name,view_id,target from ir_act_window where id=%s', (action_id,))
382                 ir_act_window_result = self.cr.fetchone()
383                 assert ir_act_window_result, "No window action defined for this id %s !\n" \
384                         "Verify that this is a window action or add a type argument." % (node.action,)
385                 action_type, action_mode, action_name, view_id, target = ir_act_window_result
386                 if view_id:
387                     self.cr.execute('SELECT type FROM ir_ui_view WHERE id=%s', (view_id,))
388                     # TODO guess why action_mode is ir_act_window.view_mode above and ir_ui_view.type here
389                     action_mode = self.cr.fetchone()
390                 self.cr.execute('SELECT view_mode FROM ir_act_window_view WHERE act_window_id=%s ORDER BY sequence LIMIT 1', (action_id,))
391                 if self.cr.rowcount:
392                     action_mode = self.cr.fetchone()
393                 if action_type == 'tree':
394                     values['icon'] = 'STOCK_INDENT'
395                 elif action_mode and action_mode.startswith('tree'):
396                     values['icon'] = 'STOCK_JUSTIFY_FILL'
397                 elif action_mode and action_mode.startswith('graph'):
398                     values['icon'] = 'terp-graph'
399                 elif action_mode and action_mode.startswith('calendar'):
400                     values['icon'] = 'terp-calendar'
401                 if target == 'new':
402                     values['icon'] = 'STOCK_EXECUTE'
403                 if not values.get('name', False):
404                     values['name'] = action_name
405             elif action_type == 'wizard':
406                 action_id = self.get_id(node.action)
407                 self.cr.execute('select name from ir_act_wizard where id=%s', (action_id,))
408                 ir_act_wizard_result = self.cr.fetchone()
409                 if (not values.get('name', False)) and ir_act_wizard_result:
410                     values['name'] = ir_act_wizard_result[0]
411             else:
412                 raise YamlImportException("Unsupported type '%s' in menuitem tag." % action_type)
413         if node.sequence:
414             values['sequence'] = node.sequence
415         if node.icon:
416             values['icon'] = node.icon
417
418         self._set_group_values(node, values)
419         
420         pid = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
421                 'ir.ui.menu', self.module, values, node.id, mode=self.mode, \
422                 noupdate=self.isnoupdate(node), res_id=res and res[0] or False)
423
424         if node.id and parent_id:
425             self.id_map[node.id] = int(parent_id)
426
427         if node.action and pid:
428             action_type = node.type or 'act_window'
429             action_id = self.get_id(node.action)
430             action = "ir.actions.%s,%d" % (action_type, action_id)
431             self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
432                     'tree_but_open', 'Menuitem', [('ir.ui.menu', int(parent_id))], action, True, True, xml_id=node.id)
433
434     def process_act_window(self, node):
435         self.validate_xml_id(node.id)
436         view_id = False
437         if node.view:
438             view_id = self.get_id(node.view)
439         context = eval(node.context, self.eval_context)
440
441         values = {
442             'name': node.name,
443             'type': type or 'ir.actions.act_window',
444             'view_id': view_id,
445             'domain': node.domain,
446             'context': context,
447             'res_model': node.res_model,
448             'src_model': node.src_model,
449             'view_type': node.view_type or 'form',
450             'view_mode': node.view_mode or 'tree,form',
451             'usage': node.usage,
452             'limit': node.limit,
453             'auto_refresh': node.auto_refresh,
454         }
455
456         self._set_group_values(node, values)
457
458         if node.target:
459             values['target'] = node.target
460         id = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
461                 'ir.actions.act_window', self.module, values, node.id, mode=self.mode)
462         self.id_map[node.id] = int(id)
463
464         if node.src_model:
465             keyword = 'client_action_relate'
466             value = 'ir.actions.act_window,%s' % id
467             replace = node.replace or True
468             self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', keyword, \
469                     node.id, [node.src_model], value, replace=replace, noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
470         # TODO add remove ir.model.data
471
472     def process_delete(self, node):
473         ids = []
474         if len(node.search):
475             ids = self.pool.get(node.model).search(self.cr, self.uid, eval(node.search, self.eval_context))
476         if len(node.id):
477             try:
478                 ids.append(self.get_id(node.id))
479             except:
480                 pass
481         if len(ids):
482             self.pool.get(node.model).unlink(self.cr, self.uid, ids)
483             self.pool.get('ir.model.data')._unlink(self.cr, self.uid, node.model, ids, direct=True)
484     
485     def process_url(self, node):
486         self.validate_xml_id(node.id)
487
488         res = {'name': node.name, 'url': node.url, 'target': node.target}
489
490         id = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
491                 "ir.actions.url", self.module, res, node.id, mode=self.mode)
492         self.id_map[node.id] = int(id)
493         # ir_set
494         if (not node.menu or eval(node.menu)) and id:
495             keyword = node.keyword or 'client_action_multi'
496             value = 'ir.actions.url,%s' % id
497             replace = node.replace or True
498             self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
499                     keyword, node.url, ["ir.actions.url"], value, replace=replace, \
500                     noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
501     
502     def process_ir_set(self, node):
503         if not self.mode == 'init':
504             return False
505         _, fields = node.items()[0]
506         res = {}
507         for fieldname, expression in fields.items():
508             if isinstance(expression, Eval):
509                 value = eval(expression.expression, self.eval_context)
510             else:
511                 value = expression
512             res[fieldname] = value
513         self.pool.get('ir.model.data').ir_set(self.cr, self.uid, res['key'], res['key2'], \
514                 res['name'], res['models'], res['value'], replace=res.get('replace',True), \
515                 isobject=res.get('isobject', False), meta=res.get('meta',None))
516
517     def process_report(self, node):
518         values = {}
519         for dest, f in (('name','string'), ('model','model'), ('report_name','name')):
520             values[dest] = getattr(node, f)
521             assert values[dest], "Attribute %s of report is empty !" % (f,)
522         for field,dest in (('rml','report_rml'),('xml','report_xml'),('xsl','report_xsl'),('attachment','attachment'),('attachment_use','attachment_use')):
523             if getattr(node, field):
524                 values[dest] = getattr(node, field)
525         if node.auto:
526             values['auto'] = eval(node.auto)
527         if node.sxw:
528             sxw_content = misc.file_open(node.sxw).read()
529             values['report_sxw_content'] = sxw_content
530         if node.header:
531             values['header'] = eval(node.header)
532         values['multi'] = node.multi and eval(node.multi)
533         xml_id = node.id
534         self.validate_xml_id(xml_id)
535
536         self._set_group_values(node, values)
537
538         id = self.pool.get('ir.model.data')._update(self.cr, self.uid, "ir.actions.report.xml", \
539                 self.module, values, xml_id, noupdate=self.isnoupdate(node), mode=self.mode)
540         self.id_map[xml_id] = int(id)
541
542         if not node.menu or eval(node.menu):
543             keyword = node.keyword or 'client_print_multi'
544             value = 'ir.actions.report.xml,%s' % id
545             replace = node.replace or True
546             self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
547                     keyword, values['name'], [values['model']], value, replace=replace, isobject=True, xml_id=xml_id)
548             
549     def process_none(self):
550         """
551         Empty node or commented node should not pass silently.
552         """
553         self._log_assert_failure(logging.WARNING, "You have an empty block in your tests.")
554         
555
556     def process(self, yaml_string):
557         """
558         Processes a Yaml string. Custom tags are interpreted by 'process_' instance methods.
559         """
560         is_preceded_by_comment = False
561         for node in yaml.load(yaml_string):
562             is_preceded_by_comment = self._log(node, is_preceded_by_comment)
563             try:
564                 self._process_node(node)
565             except YamlImportException, e:
566                 self.logger.log(logging.ERROR, e)
567             except Exception, e:
568                 self.logger.log(logging.ERROR, e)
569                 raise e
570     
571     def _process_node(self, node):
572         if is_comment(node):
573             self.process_comment(node)
574         elif is_assert(node):
575             self.process_assert(node)
576         elif is_record(node):
577             self.process_record(node)
578         elif is_python(node):
579             self.process_python(node)
580         elif is_menuitem(node):
581             self.process_menuitem(node)
582         elif is_delete(node):
583             self.process_delete(node)
584         elif is_url(node):
585             self.process_url(node)
586         elif is_context(node):
587             self.process_context(node)
588         elif is_ir_set(node):
589             self.process_ir_set(node)
590         elif is_act_window(node):
591             self.process_act_window(node)
592         elif is_report(node):
593             self.process_report(node)
594         elif is_workflow(node):
595             if isinstance(node, types.DictionaryType):
596                 self.process_workflow(node)
597             else:
598                 self.process_workflow({node: []})
599         elif is_function(node):
600             if isinstance(node, types.DictionaryType):
601                 self.process_function(node)
602             else:
603                 self.process_function({node: []})
604         elif node is None:
605             self.process_none()
606         else:
607             raise YamlImportException("Can not process YAML block: %s" % node)
608     
609     def _log(self, node, is_preceded_by_comment):
610         if is_comment(node):
611             is_preceded_by_comment = True
612             self.logger.log(logging.TEST, node)
613         elif not is_preceded_by_comment:
614             if isinstance(node, types.DictionaryType):
615                 msg = "Creating %s\n with %s"
616                 args = node.items()[0]
617                 self.logger.log(logging.TEST, msg, *args)
618             else:
619                 self.logger.log(logging.TEST, node)
620         else:
621             is_preceded_by_comment = False
622         return is_preceded_by_comment
623
624 def yaml_import(cr, module, yamlfile, idref=None, mode='init', noupdate=False, report=None):
625     if idref is None:
626         idref = {}
627     yaml_string = yamlfile.read()
628     yaml_interpreter = YamlInterpreter(cr, module, idref, mode, filename=yamlfile.name, noupdate=noupdate)
629     yaml_interpreter.process(yaml_string)
630
631 # keeps convention of convert.py
632 convert_yaml_import = yaml_import
633
634 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: