[IMP] lint cleanup
[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:
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         if function.eval:
492             args = self.process_eval(function.eval)
493         else:
494             args = self._eval_params(function.model, params)
495         method = function.name
496         getattr(model, method)(self.cr, self.uid, *args)
497
498     def _set_group_values(self, node, values):
499         if node.groups:
500             group_names = node.groups.split(',')
501             groups_value = []
502             for group in group_names:
503                 if group.startswith('-'):
504                     group_id = self.get_id(group[1:])
505                     groups_value.append((3, group_id))
506                 else:
507                     group_id = self.get_id(group)
508                     groups_value.append((4, group_id))
509             values['groups_id'] = groups_value
510
511     def process_menuitem(self, node):
512         self.validate_xml_id(node.id)
513
514         if not node.parent:
515             parent_id = False
516             self.cr.execute('select id from ir_ui_menu where parent_id is null and name=%s', (node.name,))
517             res = self.cr.fetchone()
518             values = {'parent_id': parent_id, 'name': node.name}
519         else:
520             parent_id = self.get_id(node.parent)
521             values = {'parent_id': parent_id}
522             if node.name:
523                 values['name'] = node.name
524             try:
525                 res = [ self.get_id(node.id) ]
526             except: # which exception ?
527                 res = None
528
529         if node.action:
530             action_type = node.type or 'act_window'
531             icons = {
532                 "act_window": 'STOCK_NEW',
533                 "report.xml": 'STOCK_PASTE',
534                 "wizard": 'STOCK_EXECUTE',
535                 "url": 'STOCK_JUMP_TO',
536             }
537             values['icon'] = icons.get(action_type, 'STOCK_NEW')
538             if action_type == 'act_window':
539                 action_id = self.get_id(node.action)
540                 self.cr.execute('select view_type,view_mode,name,view_id,target from ir_act_window where id=%s', (action_id,))
541                 ir_act_window_result = self.cr.fetchone()
542                 assert ir_act_window_result, "No window action defined for this id %s !\n" \
543                         "Verify that this is a window action or add a type argument." % (node.action,)
544                 action_type, action_mode, action_name, view_id, target = ir_act_window_result
545                 if view_id:
546                     self.cr.execute('SELECT type FROM ir_ui_view WHERE id=%s', (view_id,))
547                     # TODO guess why action_mode is ir_act_window.view_mode above and ir_ui_view.type here
548                     action_mode = self.cr.fetchone()
549                 self.cr.execute('SELECT view_mode FROM ir_act_window_view WHERE act_window_id=%s ORDER BY sequence LIMIT 1', (action_id,))
550                 if self.cr.rowcount:
551                     action_mode = self.cr.fetchone()
552                 if action_type == 'tree':
553                     values['icon'] = 'STOCK_INDENT'
554                 elif action_mode and action_mode.startswith('tree'):
555                     values['icon'] = 'STOCK_JUSTIFY_FILL'
556                 elif action_mode and action_mode.startswith('graph'):
557                     values['icon'] = 'terp-graph'
558                 elif action_mode and action_mode.startswith('calendar'):
559                     values['icon'] = 'terp-calendar'
560                 if target == 'new':
561                     values['icon'] = 'STOCK_EXECUTE'
562                 if not values.get('name', False):
563                     values['name'] = action_name
564             elif action_type == 'wizard':
565                 action_id = self.get_id(node.action)
566                 self.cr.execute('select name from ir_act_wizard where id=%s', (action_id,))
567                 ir_act_wizard_result = self.cr.fetchone()
568                 if (not values.get('name', False)) and ir_act_wizard_result:
569                     values['name'] = ir_act_wizard_result[0]
570             else:
571                 raise YamlImportException("Unsupported type '%s' in menuitem tag." % action_type)
572         if node.sequence:
573             values['sequence'] = node.sequence
574         if node.icon:
575             values['icon'] = node.icon
576
577         self._set_group_values(node, values)
578
579         pid = self.pool.get('ir.model.data')._update(self.cr, 1, \
580                 'ir.ui.menu', self.module, values, node.id, mode=self.mode, \
581                 noupdate=self.isnoupdate(node), res_id=res and res[0] or False)
582
583         if node.id and parent_id:
584             self.id_map[node.id] = int(parent_id)
585
586         if node.action and pid:
587             action_type = node.type or 'act_window'
588             action_id = self.get_id(node.action)
589             action = "ir.actions.%s,%d" % (action_type, action_id)
590             self.pool.get('ir.model.data').ir_set(self.cr, 1, 'action', \
591                     'tree_but_open', 'Menuitem', [('ir.ui.menu', int(parent_id))], action, True, True, xml_id=node.id)
592
593     def process_act_window(self, node):
594         assert getattr(node, 'id'), "Attribute %s of act_window is empty !" % ('id',)
595         assert getattr(node, 'name'), "Attribute %s of act_window is empty !" % ('name',)
596         assert getattr(node, 'res_model'), "Attribute %s of act_window is empty !" % ('res_model',)
597         self.validate_xml_id(node.id)
598         view_id = False
599         if node.view:
600             view_id = self.get_id(node.view)
601         if not node.context:
602             node.context={}
603         context = eval(str(node.context), self.eval_context)
604         values = {
605             'name': node.name,
606             'type': node.type or 'ir.actions.act_window',
607             'view_id': view_id,
608             'domain': node.domain,
609             'context': context,
610             'res_model': node.res_model,
611             'src_model': node.src_model,
612             'view_type': node.view_type or 'form',
613             'view_mode': node.view_mode or 'tree,form',
614             'usage': node.usage,
615             'limit': node.limit,
616             'auto_refresh': node.auto_refresh,
617             'multi': getattr(node, 'multi', False),
618         }
619
620         self._set_group_values(node, values)
621
622         if node.target:
623             values['target'] = node.target
624         id = self.pool.get('ir.model.data')._update(self.cr, 1, \
625                 'ir.actions.act_window', self.module, values, node.id, mode=self.mode)
626         self.id_map[node.id] = int(id)
627
628         if node.src_model:
629             keyword = 'client_action_relate'
630             value = 'ir.actions.act_window,%s' % id
631             replace = node.replace or True
632             self.pool.get('ir.model.data').ir_set(self.cr, 1, 'action', keyword, \
633                     node.id, [node.src_model], value, replace=replace, noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
634         # TODO add remove ir.model.data
635
636     def process_delete(self, node):
637         assert getattr(node, 'model'), "Attribute %s of delete tag is empty !" % ('model',)
638         if self.pool.get(node.model):
639             if len(node.search):
640                 ids = self.pool.get(node.model).search(self.cr, self.uid, eval(node.search, self.eval_context))
641             else:
642                 ids = [self.get_id(node.id)]
643             if len(ids):
644                 self.pool.get(node.model).unlink(self.cr, self.uid, ids)
645         else:
646             self.logger.log(logging.TEST, "Record not deleted.")
647
648     def process_url(self, node):
649         self.validate_xml_id(node.id)
650
651         res = {'name': node.name, 'url': node.url, 'target': node.target}
652
653         id = self.pool.get('ir.model.data')._update(self.cr, 1, \
654                 "ir.actions.url", self.module, res, node.id, mode=self.mode)
655         self.id_map[node.id] = int(id)
656         # ir_set
657         if (not node.menu or eval(node.menu)) and id:
658             keyword = node.keyword or 'client_action_multi'
659             value = 'ir.actions.url,%s' % id
660             replace = node.replace or True
661             self.pool.get('ir.model.data').ir_set(self.cr, 1, 'action', \
662                     keyword, node.url, ["ir.actions.url"], value, replace=replace, \
663                     noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
664
665     def process_ir_set(self, node):
666         if not self.mode == 'init':
667             return False
668         _, fields = node.items()[0]
669         res = {}
670         for fieldname, expression in fields.items():
671             if is_eval(expression):
672                 value = eval(expression.expression, self.eval_context)
673             else:
674                 value = expression
675             res[fieldname] = value
676         self.pool.get('ir.model.data').ir_set(self.cr, 1, res['key'], res['key2'], \
677                 res['name'], res['models'], res['value'], replace=res.get('replace',True), \
678                 isobject=res.get('isobject', False), meta=res.get('meta',None))
679
680     def process_report(self, node):
681         values = {}
682         for dest, f in (('name','string'), ('model','model'), ('report_name','name')):
683             values[dest] = getattr(node, f)
684             assert values[dest], "Attribute %s of report is empty !" % (f,)
685         for field,dest in (('rml','report_rml'),('file','report_rml'),('xml','report_xml'),('xsl','report_xsl'),('attachment','attachment'),('attachment_use','attachment_use')):
686             if getattr(node, field):
687                 values[dest] = getattr(node, field)
688         if node.auto:
689             values['auto'] = eval(node.auto)
690         if node.sxw:
691             sxw_file = misc.file_open(node.sxw)
692             try:
693                 sxw_content = sxw_file.read()
694                 values['report_sxw_content'] = sxw_content
695             finally:
696                 sxw_file.close()
697         if node.header:
698             values['header'] = eval(node.header)
699         values['multi'] = node.multi and eval(node.multi)
700         xml_id = node.id
701         self.validate_xml_id(xml_id)
702
703         self._set_group_values(node, values)
704
705         id = self.pool.get('ir.model.data')._update(self.cr, 1, "ir.actions.report.xml", \
706                 self.module, values, xml_id, noupdate=self.isnoupdate(node), mode=self.mode)
707         self.id_map[xml_id] = int(id)
708
709         if not node.menu or eval(node.menu):
710             keyword = node.keyword or 'client_print_multi'
711             value = 'ir.actions.report.xml,%s' % id
712             replace = node.replace or True
713             self.pool.get('ir.model.data').ir_set(self.cr, 1, 'action', \
714                     keyword, values['name'], [values['model']], value, replace=replace, isobject=True, xml_id=xml_id)
715
716     def process_none(self):
717         """
718         Empty node or commented node should not pass silently.
719         """
720         self._log_assert_failure(logging.WARNING, "You have an empty block in your tests.")
721
722
723     def process(self, yaml_string):
724         """
725         Processes a Yaml string. Custom tags are interpreted by 'process_' instance methods.
726         """
727         yaml_tag.add_constructors()
728
729         is_preceded_by_comment = False
730         for node in yaml.load(yaml_string):
731             is_preceded_by_comment = self._log(node, is_preceded_by_comment)
732             try:
733                 self._process_node(node)
734             except YamlImportException, e:
735                 self.logger.exception(e)
736             except Exception, e:
737                 self.logger.exception(e)
738                 raise
739
740     def _process_node(self, node):
741         if is_comment(node):
742             self.process_comment(node)
743         elif is_assert(node):
744             self.process_assert(node)
745         elif is_record(node):
746             self.process_record(node)
747         elif is_python(node):
748             self.process_python(node)
749         elif is_menuitem(node):
750             self.process_menuitem(node)
751         elif is_delete(node):
752             self.process_delete(node)
753         elif is_url(node):
754             self.process_url(node)
755         elif is_context(node):
756             self.process_context(node)
757         elif is_ir_set(node):
758             self.process_ir_set(node)
759         elif is_act_window(node):
760             self.process_act_window(node)
761         elif is_report(node):
762             self.process_report(node)
763         elif is_workflow(node):
764             if isinstance(node, types.DictionaryType):
765                 self.process_workflow(node)
766             else:
767                 self.process_workflow({node: []})
768         elif is_function(node):
769             if isinstance(node, types.DictionaryType):
770                 self.process_function(node)
771             else:
772                 self.process_function({node: []})
773         elif node is None:
774             self.process_none()
775         else:
776             raise YamlImportException("Can not process YAML block: %s" % node)
777
778     def _log(self, node, is_preceded_by_comment):
779         if is_comment(node):
780             is_preceded_by_comment = True
781             self.logger.log(logging.TEST, node)
782         elif not is_preceded_by_comment:
783             if isinstance(node, types.DictionaryType):
784                 msg = "Creating %s\n with %s"
785                 args = node.items()[0]
786                 self.logger.log(logging.TEST, msg, *args)
787             else:
788                 self.logger.log(logging.TEST, node)
789         else:
790             is_preceded_by_comment = False
791         return is_preceded_by_comment
792
793 def yaml_import(cr, module, yamlfile, idref=None, mode='init', noupdate=False):
794     if idref is None:
795         idref = {}
796     yaml_string = yamlfile.read()
797     yaml_interpreter = YamlInterpreter(cr, module, idref, mode, filename=yamlfile.name, noupdate=noupdate)
798     yaml_interpreter.process(yaml_string)
799
800 # keeps convention of convert.py
801 convert_yaml_import = yaml_import
802
803 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: