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