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