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