[FIX] Export & Synchronize Translations Corrected
[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 def is_string(node):
82     return isinstance(node, basestring)
83
84 class TestReport(object):
85     def __init__(self):
86         self._report = {}
87
88     def record(self, success, severity):
89         """
90         Records the result of an assertion for the failed/success count.
91         Returns success.
92         """
93         if severity in self._report:
94             self._report[severity][success] += 1
95         else:
96             self._report[severity] = {success: 1, not success: 0}
97         return success
98
99     def __str__(self):
100         res = []
101         res.append('\nAssertions report:\nLevel\tsuccess\tfailure')
102         success = failure = 0
103         for severity in self._report:
104             res.append("%s\t%s\t%s" % (severity, self._report[severity][True], self._report[severity][False]))
105             success += self._report[severity][True]
106             failure += self._report[severity][False]
107         res.append("total\t%s\t%s" % (success, failure))
108         res.append("end of report (%s assertion(s) checked)" % success + failure)
109         return "\n".join(res)
110
111 class RecordDictWrapper(dict):
112     """
113     Used to pass a record as locals in eval:
114     records do not strictly behave like dict, so we force them to.
115     """
116     def __init__(self, record):
117         self.record = record 
118     def __getitem__(self, key):
119         if key in self.record:
120             return self.record[key]
121         return dict.__getitem__(self, key)
122
123 class YamlInterpreter(object):
124     def __init__(self, cr, module, id_map, mode, filename, noupdate=False):
125         self.cr = cr
126         self.module = module
127         self.id_map = id_map
128         self.mode = mode
129         self.filename = filename
130         self.assert_report = TestReport()
131         self.noupdate = noupdate
132         self.logger = logging.getLogger("%s.%s" % (logger_channel, self.module))
133         self.pool = pooler.get_pool(cr.dbname)
134         self.uid = 1
135         self.context = {} # opererp context
136         self.eval_context = {'ref': self._ref(),
137                              '_ref': self._ref(), # added '_ref' so that record['ref'] is possible
138                              'time': time,
139                              'datetime': datetime,
140                              'timedelta': timedelta}
141
142     def _ref(self):
143         return lambda xml_id: self.get_id(xml_id)
144
145     def get_model(self, model_name):
146         model = self.pool.get(model_name)
147         assert model, "The model %s does not exist." % (model_name,)
148         return model
149
150     def validate_xml_id(self, xml_id):
151         id = xml_id
152         if '.' in xml_id:
153             module, id = xml_id.split('.', 1)
154             assert '.' not in id, "The ID reference '%s' must contains maximum one dot.\n" \
155                                   "It is used to refer to other modules ID, in the form: module.record_id" \
156                                   % (xml_id,)
157             if module != self.module:
158                 module_count = self.pool.get('ir.module.module').search_count(self.cr, self.uid, \
159                         ['&', ('name', '=', module), ('state', 'in', ['installed'])])
160                 assert module_count == 1, 'The ID "%s" refers to an uninstalled module.' % (xml_id,)
161         if len(id) > 64: # TODO where does 64 come from (DB is 128)? should be a constant or loaded form DB
162             self.logger.log(logging.ERROR, 'id: %s is to long (max: 64)', id)
163
164     def get_id(self, xml_id):
165         if not xml_id:
166             raise YamlImportException("The xml_id should be a non empty string.")
167         if isinstance(xml_id, types.IntType):
168             id = xml_id
169         elif xml_id in self.id_map:
170             id = self.id_map[xml_id]
171         else:
172             if '.' in xml_id:
173                 module, checked_xml_id = xml_id.split('.', 1)
174             else:
175                 module = self.module
176                 checked_xml_id = xml_id
177             ir_id = self.pool.get('ir.model.data')._get_id(self.cr, self.uid, module, checked_xml_id)
178             obj = self.pool.get('ir.model.data').read(self.cr, self.uid, ir_id, ['res_id'])
179             id = int(obj['res_id'])
180             self.id_map[xml_id] = id
181         return id
182     
183     def get_context(self, node, eval_dict):
184         context = self.context.copy()
185         if node.context:
186             context.update(eval(node.context, eval_dict))
187         return context
188
189     def isnoupdate(self, node):
190         return self.noupdate or node.noupdate or False
191     
192     def _get_first_result(self, results, default=False):
193         if len(results):
194             value = results[0]
195             if isinstance(value, types.TupleType):
196                 value = value[0]
197         else:
198             value = default
199         return value
200     
201     def process_comment(self, node):
202         return node
203
204     def _log_assert_failure(self, severity, msg, *args):
205         if isinstance(severity, types.StringTypes):
206             levelname = severity.strip().upper()
207             level = logging.getLevelName(levelname)
208         else:
209             level = severity
210             levelname = logging.getLevelName(level)
211         self.assert_report.record(False, levelname)
212         self.logger.log(level, msg, *args)
213         if level >= config['assert_exit_level']:
214             raise YamlImportAbortion('Severe assertion failure (%s), aborting.' % levelname)
215         return
216
217     def _get_assertion_id(self, assertion):
218         if assertion.id:
219             ids = [self.get_id(assertion.id)]
220         elif assertion.search:
221             q = eval(assertion.search, self.eval_context)
222             ids = self.pool.get(assertion.model).search(self.cr, self.uid, q, context=assertion.context)
223         if not ids:
224             raise YamlImportException('Nothing to assert: you must give either an id or a search criteria.')
225         return ids
226
227     def process_assert(self, node):
228         assertion, expressions = node.items()[0]
229
230         if self.isnoupdate(assertion) and self.mode != 'init':
231             self.logger.warn('This assertion was not evaluated ("%s").' % assertion.string)
232             return
233         model = self.get_model(assertion.model)
234         ids = self._get_assertion_id(assertion)
235         if assertion.count and len(ids) != assertion.count:
236             msg = 'assertion "%s" failed!\n'   \
237                   ' Incorrect search count:\n' \
238                   ' expected count: %d\n'      \
239                   ' obtained count: %d\n'
240             args = (assertion.string, assertion.count, len(ids))
241             self._log_assert_failure(assertion.severity, msg, *args)
242         else:
243             context = self.get_context(assertion, self.eval_context)
244             for id in ids:
245                 record = model.browse(self.cr, self.uid, id, context)
246                 for test in expressions:
247                     try:
248                         success = unsafe_eval(test, self.eval_context, RecordDictWrapper(record))
249                     except Exception, e:
250                         self.logger.debug('Exception during evaluation of !assert block in yaml_file %s.', self.filename, exc_info=True)
251                         raise YamlImportAbortion(e)
252                     if not success:
253                         msg = 'Assertion "%s" FAILED\ntest: %s\n'
254                         args = (assertion.string, test)
255                         for aop in ('==', '!=', '<>', 'in', 'not in', '>=', '<=', '>', '<'):
256                             if aop in test:
257                                 left, right = test.split(aop,1)
258                                 lmsg = ''
259                                 rmsg = ''
260                                 try:
261                                     lmsg = unsafe_eval(left, self.eval_context, RecordDictWrapper(record))
262                                 except Exception, e:
263                                     lmsg = '<exc>'
264
265                                 try:
266                                     rmsg = unsafe_eval(right, self.eval_context, RecordDictWrapper(record))
267                                 except Exception, e:
268                                     rmsg = '<exc>'
269
270                                 msg += 'values: ! %s %s %s'
271                                 args += ( lmsg, aop, rmsg )
272                                 break
273
274                         self._log_assert_failure(assertion.severity, msg, *args)
275                         return
276             else: # all tests were successful for this assertion tag (no break)
277                 self.assert_report.record(True, assertion.severity)
278
279     def _coerce_bool(self, value, default=False):
280         if isinstance(value, types.BooleanType):
281             b = value
282         if isinstance(value, types.StringTypes):
283             b = value.strip().lower() not in ('0', 'false', 'off', 'no')
284         elif isinstance(value, types.IntType):
285             b = bool(value)
286         else:
287             b = default
288         return b
289
290     def create_osv_memory_record(self, record, fields):
291         model = self.get_model(record.model)
292         record_dict = self._create_record(model, fields)
293         id_new=model.create(self.cr, self.uid, record_dict, context=self.context)
294         self.id_map[record.id] = int(id_new)
295         return record_dict
296
297     def process_record(self, node):
298         import osv
299         record, fields = node.items()[0]
300         model = self.get_model(record.model)
301         if isinstance(model, osv.osv.osv_memory):
302             record_dict=self.create_osv_memory_record(record, fields)
303         else:
304             self.validate_xml_id(record.id)
305             if self.isnoupdate(record) and self.mode != 'init':
306                 id = self.pool.get('ir.model.data')._update_dummy(self.cr, self.uid, record.model, self.module, record.id)
307                 # check if the resource already existed at the last update
308                 if id:
309                     self.id_map[record] = int(id)
310                     return None
311                 else:
312                     if not self._coerce_bool(record.forcecreate):
313                         return None
314
315             record_dict = self._create_record(model, fields)
316             self.logger.debug("RECORD_DICT %s" % record_dict)
317             #context = self.get_context(record, self.eval_context)
318             context = record.context #TOFIX: record.context like {'withoutemployee':True} should pass from self.eval_context. example: test_project.yml in project module
319             id = self.pool.get('ir.model.data')._update(self.cr, self.uid, record.model, \
320                     self.module, record_dict, record.id, noupdate=self.isnoupdate(record), mode=self.mode, context=context)
321             self.id_map[record.id] = int(id)
322             if config.get('import_partial'):
323                 self.cr.commit()
324
325     def _create_record(self, model, fields):
326         record_dict = {}
327         for field_name, expression in fields.items():
328             field_value = self._eval_field(model, field_name, expression)
329             record_dict[field_name] = field_value
330         return record_dict
331
332     def process_ref(self, node, column=None):
333         if node.search:
334             if node.model:
335                 model_name = node.model
336             elif column:
337                 model_name = column._obj
338             else:
339                 raise YamlImportException('You need to give a model for the search, or a column to infer it.')
340             model = self.get_model(model_name)
341             q = eval(node.search, self.eval_context)
342             ids = model.search(self.cr, self.uid, q)
343             if node.use:
344                 instances = model.browse(self.cr, self.uid, ids)
345                 value = [inst[node.use] for inst in instances]
346             else:
347                 value = ids
348         elif node.id:
349             value = self.get_id(node.id)
350         else:
351             value = None
352         return value
353
354     def process_eval(self, node):
355         return eval(node.expression, self.eval_context)
356
357     def _eval_field(self, model, field_name, expression):
358         # TODO this should be refactored as something like model.get_field() in bin/osv
359         if field_name in model._columns:
360             column = model._columns[field_name]
361         elif field_name in model._inherit_fields:
362             column = model._inherit_fields[field_name][2]
363         else:
364             raise KeyError("Object '%s' does not contain field '%s'" % (model, field_name))
365         if is_ref(expression):
366             elements = self.process_ref(expression, column)
367             if column._type in ("many2many", "one2many"):
368                 value = [(6, 0, elements)]
369             else: # many2one
370                 value = self._get_first_result(elements)
371         elif column._type == "many2one":
372             value = self.get_id(expression)
373         elif column._type == "one2many":
374             other_model = self.get_model(column._obj)
375             value = [(0, 0, self._create_record(other_model, fields)) for fields in expression]
376         elif column._type == "many2many":
377             ids = [self.get_id(xml_id) for xml_id in expression]
378             value = [(6, 0, ids)]
379         elif column._type == "date" and is_string(expression):
380             # enforce ISO format for string date values, to be locale-agnostic during tests
381             time.strptime(expression, misc.DEFAULT_SERVER_DATE_FORMAT)
382             value = expression
383         elif column._type == "datetime" and is_string(expression):
384             # enforce ISO format for string datetime values, to be locale-agnostic during tests
385             time.strptime(expression, misc.DEFAULT_SERVER_DATETIME_FORMAT)
386             value = expression
387         else: # scalar field
388             if is_eval(expression):
389                 value = self.process_eval(expression)
390             else:
391                 value = expression
392             # raise YamlImportException('Unsupported column "%s" or value %s:%s' % (field_name, type(expression), expression))
393         return value
394
395     def process_context(self, node):
396         self.context = node.__dict__
397         if node.uid:
398             self.uid = self.get_id(node.uid)
399         if node.noupdate:
400             self.noupdate = node.noupdate
401
402     def process_python(self, node):
403         def log(msg, *args):
404             self.logger.log(logging.TEST, msg, *args)
405         python, statements = node.items()[0]
406         model = self.get_model(python.model)
407         statements = statements.replace("\r\n", "\n")
408         code_context = {'model': model, 'cr': self.cr, 'uid': self.uid, 'log': log, 'context': self.context}
409         code_context.update({'self': model}) # remove me when no !python block test uses 'self' anymore
410         try:
411             code_obj = compile(statements, self.filename, 'exec')
412             unsafe_eval(code_obj, {'ref': self.get_id}, code_context)
413         except AssertionError, e:
414             self._log_assert_failure(python.severity, 'AssertionError in Python code %s: %s', python.name, e)
415             return
416         except Exception, e:
417             self.logger.debug('Exception during evaluation of !python block in yaml_file %s.', self.filename, exc_info=True)
418             raise
419         else:
420             self.assert_report.record(True, python.severity)
421     
422     def process_workflow(self, node):
423         workflow, values = node.items()[0]
424         if self.isnoupdate(workflow) and self.mode != 'init':
425             return
426         if workflow.ref:
427             id = self.get_id(workflow.ref)
428         else:
429             if not values:
430                 raise YamlImportException('You must define a child node if you do not give a ref.')
431             if not len(values) == 1:
432                 raise YamlImportException('Only one child node is accepted (%d given).' % len(values))
433             value = values[0]
434             if not 'model' in value and (not 'eval' in value or not 'search' in value):
435                 raise YamlImportException('You must provide a "model" and an "eval" or "search" to evaluate.')
436             value_model = self.get_model(value['model'])
437             local_context = {'obj': lambda x: value_model.browse(self.cr, self.uid, x, context=self.context)}
438             local_context.update(self.id_map)
439             id = eval(value['eval'], self.eval_context, local_context)
440         
441         if workflow.uid is not None:
442             uid = workflow.uid
443         else:
444             uid = self.uid
445         self.cr.execute('select distinct signal from wkf_transition')
446         signals=[x['signal'] for x in self.cr.dictfetchall()]
447         if workflow.action not in signals:
448             raise YamlImportException('Incorrect action %s. No such action defined' % workflow.action)
449         wf_service = netsvc.LocalService("workflow")
450         wf_service.trg_validate(uid, workflow.model, id, workflow.action, self.cr)
451     
452     def _eval_params(self, model, params):
453         args = []
454         for i, param in enumerate(params):
455             if isinstance(param, types.ListType):
456                 value = self._eval_params(model, param)
457             elif is_ref(param):
458                 value = self.process_ref(param)
459             elif is_eval(param):
460                 value = self.process_eval(param)
461             elif isinstance(param, types.DictionaryType): # supports XML syntax
462                 param_model = self.get_model(param.get('model', model))
463                 if 'search' in param:
464                     q = eval(param['search'], self.eval_context)
465                     ids = param_model.search(self.cr, self.uid, q)
466                     value = self._get_first_result(ids)
467                 elif 'eval' in param:
468                     local_context = {'obj': lambda x: param_model.browse(self.cr, self.uid, x, self.context)}
469                     local_context.update(self.id_map)
470                     value = eval(param['eval'], self.eval_context, local_context)
471                 else:
472                     raise YamlImportException('You must provide either a !ref or at least a "eval" or a "search" to function parameter #%d.' % i)
473             else:
474                 value = param # scalar value
475             args.append(value)
476         return args
477         
478     def process_function(self, node):
479         function, params = node.items()[0]
480         if self.isnoupdate(function) and self.mode != 'init':
481             return
482         model = self.get_model(function.model)
483         context = self.get_context(function, self.eval_context)
484         if function.eval:
485             args = self.process_eval(function.eval)
486         else:
487             args = self._eval_params(function.model, params)
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         assert getattr(node, 'id'), "Attribute %s of act_window is empty !" % ('id',)
588         assert getattr(node, 'name'), "Attribute %s of act_window is empty !" % ('name',)
589         assert getattr(node, 'res_model'), "Attribute %s of act_window is empty !" % ('res_model',)
590         self.validate_xml_id(node.id)
591         view_id = False
592         if node.view:
593             view_id = self.get_id(node.view)
594         if not node.context:
595             node.context={}
596         context = eval(str(node.context), self.eval_context)
597         values = {
598             'name': node.name,
599             'type': node.type or 'ir.actions.act_window',
600             'view_id': view_id,
601             'domain': node.domain,
602             'context': context,
603             'res_model': node.res_model,
604             'src_model': node.src_model,
605             'view_type': node.view_type or 'form',
606             'view_mode': node.view_mode or 'tree,form',
607             'usage': node.usage,
608             'limit': node.limit,
609             'auto_refresh': node.auto_refresh,
610         }
611
612         self._set_group_values(node, values)
613
614         if node.target:
615             values['target'] = node.target
616         id = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
617                 'ir.actions.act_window', self.module, values, node.id, mode=self.mode)
618         self.id_map[node.id] = int(id)
619
620         if node.src_model:
621             keyword = 'client_action_relate'
622             value = 'ir.actions.act_window,%s' % id
623             replace = node.replace or True
624             self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', keyword, \
625                     node.id, [node.src_model], value, replace=replace, noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
626         # TODO add remove ir.model.data
627
628     def process_delete(self, node):
629         assert getattr(node, 'model'), "Attribute %s of delete tag is empty !" % ('model',)
630         if self.pool.get(node.model):
631             if len(node.search):
632                 ids = self.pool.get(node.model).search(self.cr, self.uid, eval(node.search, self.eval_context))
633             else:
634                 ids = [self.get_id(node.id)]
635             if len(ids):
636                 self.pool.get(node.model).unlink(self.cr, self.uid, ids)
637                 self.pool.get('ir.model.data')._unlink(self.cr, self.uid, node.model, ids)
638         else:
639             self.logger.log(logging.TEST, "Record not deleted.")
640     
641     def process_url(self, node):
642         self.validate_xml_id(node.id)
643
644         res = {'name': node.name, 'url': node.url, 'target': node.target}
645
646         id = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
647                 "ir.actions.url", self.module, res, node.id, mode=self.mode)
648         self.id_map[node.id] = int(id)
649         # ir_set
650         if (not node.menu or eval(node.menu)) and id:
651             keyword = node.keyword or 'client_action_multi'
652             value = 'ir.actions.url,%s' % id
653             replace = node.replace or True
654             self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
655                     keyword, node.url, ["ir.actions.url"], value, replace=replace, \
656                     noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
657     
658     def process_ir_set(self, node):
659         if not self.mode == 'init':
660             return False
661         _, fields = node.items()[0]
662         res = {}
663         for fieldname, expression in fields.items():
664             if is_eval(expression):
665                 value = eval(expression.expression, self.eval_context)
666             else:
667                 value = expression
668             res[fieldname] = value
669         self.pool.get('ir.model.data').ir_set(self.cr, self.uid, res['key'], res['key2'], \
670                 res['name'], res['models'], res['value'], replace=res.get('replace',True), \
671                 isobject=res.get('isobject', False), meta=res.get('meta',None))
672
673     def process_report(self, node):
674         values = {}
675         for dest, f in (('name','string'), ('model','model'), ('report_name','name')):
676             values[dest] = getattr(node, f)
677             assert values[dest], "Attribute %s of report is empty !" % (f,)
678         for field,dest in (('rml','report_rml'),('file','report_rml'),('xml','report_xml'),('xsl','report_xsl'),('attachment','attachment'),('attachment_use','attachment_use')):
679             if getattr(node, field):
680                 values[dest] = getattr(node, field)
681         if node.auto:
682             values['auto'] = eval(node.auto)
683         if node.sxw:
684             sxw_content = misc.file_open(node.sxw).read()
685             values['report_sxw_content'] = sxw_content
686         if node.header:
687             values['header'] = eval(node.header)
688         values['multi'] = node.multi and eval(node.multi)
689         xml_id = node.id
690         self.validate_xml_id(xml_id)
691
692         self._set_group_values(node, values)
693
694         id = self.pool.get('ir.model.data')._update(self.cr, self.uid, "ir.actions.report.xml", \
695                 self.module, values, xml_id, noupdate=self.isnoupdate(node), mode=self.mode)
696         self.id_map[xml_id] = int(id)
697
698         if not node.menu or eval(node.menu):
699             keyword = node.keyword or 'client_print_multi'
700             value = 'ir.actions.report.xml,%s' % id
701             replace = node.replace or True
702             self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
703                     keyword, values['name'], [values['model']], value, replace=replace, isobject=True, xml_id=xml_id)
704             
705     def process_none(self):
706         """
707         Empty node or commented node should not pass silently.
708         """
709         self._log_assert_failure(logging.WARNING, "You have an empty block in your tests.")
710         
711
712     def process(self, yaml_string):
713         """
714         Processes a Yaml string. Custom tags are interpreted by 'process_' instance methods.
715         """
716         yaml_tag.add_constructors()
717
718         is_preceded_by_comment = False
719         for node in yaml.load(yaml_string):
720             is_preceded_by_comment = self._log(node, is_preceded_by_comment)
721             try:
722                 self._process_node(node)
723             except YamlImportException, e:
724                 self.logger.exception(e)
725             except Exception, e:
726                 self.logger.exception(e)
727                 raise
728     
729     def _process_node(self, node):
730         if is_comment(node):
731             self.process_comment(node)
732         elif is_assert(node):
733             self.process_assert(node)
734         elif is_record(node):
735             self.process_record(node)
736         elif is_python(node):
737             self.process_python(node)
738         elif is_menuitem(node):
739             self.process_menuitem(node)
740         elif is_delete(node):
741             self.process_delete(node)
742         elif is_url(node):
743             self.process_url(node)
744         elif is_context(node):
745             self.process_context(node)
746         elif is_ir_set(node):
747             self.process_ir_set(node)
748         elif is_act_window(node):
749             self.process_act_window(node)
750         elif is_report(node):
751             self.process_report(node)
752         elif is_workflow(node):
753             if isinstance(node, types.DictionaryType):
754                 self.process_workflow(node)
755             else:
756                 self.process_workflow({node: []})
757         elif is_function(node):
758             if isinstance(node, types.DictionaryType):
759                 self.process_function(node)
760             else:
761                 self.process_function({node: []})
762         elif node is None:
763             self.process_none()
764         else:
765             raise YamlImportException("Can not process YAML block: %s" % node)
766     
767     def _log(self, node, is_preceded_by_comment):
768         if is_comment(node):
769             is_preceded_by_comment = True
770             self.logger.log(logging.TEST, node)
771         elif not is_preceded_by_comment:
772             if isinstance(node, types.DictionaryType):
773                 msg = "Creating %s\n with %s"
774                 args = node.items()[0]
775                 self.logger.log(logging.TEST, msg, *args)
776             else:
777                 self.logger.log(logging.TEST, node)
778         else:
779             is_preceded_by_comment = False
780         return is_preceded_by_comment
781
782 def yaml_import(cr, module, yamlfile, idref=None, mode='init', noupdate=False, report=None):
783     if idref is None:
784         idref = {}
785     yaml_string = yamlfile.read()
786     yaml_interpreter = YamlInterpreter(cr, module, idref, mode, filename=yamlfile.name, noupdate=noupdate)
787     yaml_interpreter.process(yaml_string)
788
789 # keeps convention of convert.py
790 convert_yaml_import = yaml_import
791
792 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: