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