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