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