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