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