1 # -*- encoding: utf-8 -*-
4 import time # used to eval time.strftime expressions
5 from datetime import datetime, timedelta
8 import openerp.pooler as pooler
9 import openerp.sql_db as sql_db
11 from config import config
15 from lxml import etree
17 # YAML import needs both safe and unsafe eval, but let's
20 from safe_eval import safe_eval as eval
22 logger_channel = 'tests'
24 class YamlImportException(Exception):
27 class YamlImportAbortion(Exception):
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)
37 return isinstance(node, types.StringTypes)
40 return isinstance(node, yaml_tag.Assert) \
41 or _is_yaml_mapping(node, yaml_tag.Assert)
44 return _is_yaml_mapping(node, yaml_tag.Record)
47 return _is_yaml_mapping(node, yaml_tag.Python)
49 def is_menuitem(node):
50 return isinstance(node, yaml_tag.Menuitem) \
51 or _is_yaml_mapping(node, yaml_tag.Menuitem)
53 def is_function(node):
54 return isinstance(node, yaml_tag.Function) \
55 or _is_yaml_mapping(node, yaml_tag.Function)
58 return isinstance(node, yaml_tag.Report)
60 def is_workflow(node):
61 return isinstance(node, yaml_tag.Workflow)
63 def is_act_window(node):
64 return isinstance(node, yaml_tag.ActWindow)
67 return isinstance(node, yaml_tag.Delete)
70 return isinstance(node, yaml_tag.Context)
73 return isinstance(node, yaml_tag.Url)
76 return isinstance(node, yaml_tag.Eval)
79 return isinstance(node, yaml_tag.Ref) \
80 or _is_yaml_mapping(node, yaml_tag.Ref)
83 return _is_yaml_mapping(node, yaml_tag.IrSet)
86 return isinstance(node, basestring)
88 class TestReport(object):
92 def record(self, success, severity):
94 Records the result of an assertion for the failed/success count.
97 if severity in self._report:
98 self._report[severity][success] += 1
100 self._report[severity] = {success: 1, not success: 0}
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)
115 class RecordDictWrapper(dict):
117 Used to pass a record as locals in eval:
118 records do not strictly behave like dict, so we force them to.
120 def __init__(self, record):
122 def __getitem__(self, key):
123 if key in self.record:
124 return self.record[key]
125 return dict.__getitem__(self, key)
127 class YamlInterpreter(object):
128 def __init__(self, cr, module, id_map, mode, filename, noupdate=False):
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)
139 self.context = {} # opererp context
140 self.eval_context = {'ref': self._ref(),
141 '_ref': self._ref(), # added '_ref' so that record['ref'] is possible
143 'datetime': datetime,
144 'timedelta': timedelta}
147 return lambda xml_id: self.get_id(xml_id)
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,)
154 def validate_xml_id(self, 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" \
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)
168 def get_id(self, xml_id):
169 if xml_id is False or xml_id is None:
172 # raise YamlImportException("The xml_id should be a non empty string.")
173 elif isinstance(xml_id, types.IntType):
175 elif xml_id in self.id_map:
176 id = self.id_map[xml_id]
179 module, checked_xml_id = xml_id.split('.', 1)
182 checked_xml_id = xml_id
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
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))
193 def get_context(self, node, eval_dict):
194 context = self.context.copy()
196 context.update(eval(node.context, eval_dict))
199 def isnoupdate(self, node):
200 return self.noupdate or node.noupdate or False
202 def _get_first_result(self, results, default=False):
205 if isinstance(value, types.TupleType):
211 def process_comment(self, node):
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)
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)
227 def _get_assertion_id(self, assertion):
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)
234 raise YamlImportException('Nothing to assert: you must give either an id or a search criteria.')
237 def process_assert(self, node):
238 if isinstance(node, dict):
239 assertion, expressions = node.items()[0]
241 assertion, expressions = node, []
243 if self.isnoupdate(assertion) and self.mode != 'init':
244 self.logger.warn('This assertion was not evaluated ("%s").' % assertion.string)
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)
256 context = self.get_context(assertion, self.eval_context)
258 record = model.browse(self.cr, self.uid, id, context)
259 for test in expressions:
261 success = unsafe_eval(test, self.eval_context, RecordDictWrapper(record))
263 self.logger.debug('Exception during evaluation of !assert block in yaml_file %s.', self.filename, exc_info=True)
264 raise YamlImportAbortion(e)
266 msg = 'Assertion "%s" FAILED\ntest: %s\n'
267 args = (assertion.string, test)
268 for aop in ('==', '!=', '<>', 'in', 'not in', '>=', '<=', '>', '<'):
270 left, right = test.split(aop,1)
274 lmsg = unsafe_eval(left, self.eval_context, RecordDictWrapper(record))
279 rmsg = unsafe_eval(right, self.eval_context, RecordDictWrapper(record))
283 msg += 'values: ! %s %s %s'
284 args += ( lmsg, aop, rmsg )
287 self._log_assert_failure(assertion.severity, msg, *args)
289 else: # all tests were successful for this assertion tag (no break)
290 self.assert_report.record(True, assertion.severity)
292 def _coerce_bool(self, value, default=False):
293 if isinstance(value, types.BooleanType):
295 if isinstance(value, types.StringTypes):
296 b = value.strip().lower() not in ('0', 'false', 'off', 'no')
297 elif isinstance(value, types.IntType):
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)
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)
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]
320 if model.is_transient():
321 record_dict=self.create_osv_memory_record(record, fields)
323 self.validate_xml_id(record.id)
325 self.pool.get('ir.model.data')._get_id(self.cr, 1, self.module, record.id)
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
334 self.id_map[record] = int(id)
337 if not self._coerce_bool(record.forcecreate):
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
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'))
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'):
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)
367 fields = fields or {}
369 def process_val(key, val):
370 if fg[key]['type']=='many2one':
371 if type(val) in (tuple,list):
373 elif (fg[key]['type']=='one2many'):
376 if len(val) and type(val[0]) == dict:
377 val = map(lambda x: (0,0,x), val)
380 # Process all on_change calls
381 nodes = (view is not False) and [view] or []
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:
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,))
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'))
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])
406 if not el.attrib.get('on_change', False):
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'], )
411 # creating the context
412 class parent2(object):
413 def __init__(self, d):
415 def __getattr__(self, name):
416 return self.d.get(name, False)
418 ctx = record_dict.copy()
419 ctx['context'] = self.context
421 ctx['parent'] = parent2(parent)
424 ctx[a]=process_val(a, defaults.get(a, False))
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
436 nodes = list(el) + nodes
438 for field_name, expression in fields.items():
439 if field_name in record_dict:
441 field_value = self._eval_field(model, field_name, expression, default=False)
442 record_dict[field_name] = field_value
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'
450 model_name = node.model
452 model_name = column._obj
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)
459 instances = model.browse(self.cr, self.uid, ids)
460 value = [inst[node.use] for inst in instances]
464 value = self.get_id(node.id)
469 def process_eval(self, node):
470 return eval(node.expression, self.eval_context)
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]
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)]
485 if isinstance(elements, (list,tuple)):
486 value = self._get_first_result(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)
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)
506 if is_eval(expression):
507 value = self.process_eval(expression)
510 # raise YamlImportException('Unsupported column "%s" or value %s:%s' % (field_name, type(expression), expression))
513 def process_context(self, node):
514 self.context = node.__dict__
516 self.uid = self.get_id(node.uid)
518 self.noupdate = node.noupdate
520 def process_python(self, node):
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
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)
535 self.logger.debug('Exception during evaluation of !python block in yaml_file %s.', self.filename, exc_info=True)
538 self.assert_report.record(True, python.severity)
540 def process_workflow(self, node):
541 workflow, values = node.items()[0]
542 if self.isnoupdate(workflow) and self.mode != 'init':
545 id = self.get_id(workflow.ref)
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))
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)
559 if workflow.uid is not None:
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)
571 def _eval_params(self, model, params):
573 for i, param in enumerate(params):
574 if isinstance(param, types.ListType):
575 value = self._eval_params(model, param)
577 value = self.process_ref(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)
591 raise YamlImportException('You must provide either a !ref or at least a "eval" or a "search" to function parameter #%d.' % i)
593 value = param # scalar value
597 def process_function(self, node):
598 function, params = node.items()[0]
599 if self.isnoupdate(function) and self.mode != 'init':
601 model = self.get_model(function.model)
603 args = self.process_eval(function.eval)
605 args = self._eval_params(function.model, params)
606 method = function.name
607 getattr(model, method)(self.cr, self.uid, *args)
609 def _set_group_values(self, node, values):
611 group_names = node.groups.split(',')
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))
618 group_id = self.get_id(group)
619 groups_value.append((4, group_id))
620 values['groups_id'] = groups_value
622 def process_menuitem(self, node):
623 self.validate_xml_id(node.id)
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}
631 parent_id = self.get_id(node.parent)
632 values = {'parent_id': parent_id}
634 values['name'] = node.name
636 res = [ self.get_id(node.id) ]
637 except: # which exception ?
641 action_type = node.type or 'act_window'
643 "act_window": 'STOCK_NEW',
644 "report.xml": 'STOCK_PASTE',
645 "wizard": 'STOCK_EXECUTE',
646 "url": 'STOCK_JUMP_TO',
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
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,))
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'
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]
682 raise YamlImportException("Unsupported type '%s' in menuitem tag." % action_type)
684 values['sequence'] = node.sequence
686 values['icon'] = node.icon
688 self._set_group_values(node, values)
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)
694 if node.id and parent_id:
695 self.id_map[node.id] = int(parent_id)
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)
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)
711 view_id = self.get_id(node.view)
714 context = eval(str(node.context), self.eval_context)
717 'type': node.type or 'ir.actions.act_window',
719 'domain': node.domain,
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',
727 'auto_refresh': node.auto_refresh,
728 'multi': getattr(node, 'multi', False),
731 self._set_group_values(node, values)
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)
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
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):
751 ids = self.pool.get(node.model).search(self.cr, self.uid, eval(node.search, self.eval_context))
753 ids = [self.get_id(node.id)]
755 self.pool.get(node.model).unlink(self.cr, self.uid, ids)
757 self.logger.log(logging.TEST, "Record not deleted.")
759 def process_url(self, node):
760 self.validate_xml_id(node.id)
762 res = {'name': node.name, 'url': node.url, 'target': node.target}
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)
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)
776 def process_ir_set(self, node):
777 if not self.mode == 'init':
779 _, fields = node.items()[0]
781 for fieldname, expression in fields.items():
782 if is_eval(expression):
783 value = eval(expression.expression, self.eval_context)
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))
791 def process_report(self, node):
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)
800 values['auto'] = eval(node.auto)
802 sxw_file = misc.file_open(node.sxw)
804 sxw_content = sxw_file.read()
805 values['report_sxw_content'] = sxw_content
809 values['header'] = eval(node.header)
810 values['multi'] = node.multi and eval(node.multi)
812 self.validate_xml_id(xml_id)
814 self._set_group_values(node, values)
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)
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)
827 def process_none(self):
829 Empty node or commented node should not pass silently.
831 self._log_assert_failure(logging.WARNING, "You have an empty block in your tests.")
834 def process(self, yaml_string):
836 Processes a Yaml string. Custom tags are interpreted by 'process_' instance methods.
838 yaml_tag.add_constructors()
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)
844 self._process_node(node)
845 except YamlImportException, e:
846 self.logger.exception(e)
848 self.logger.exception(e)
851 def _process_node(self, 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)
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)
878 self.process_workflow({node: []})
879 elif is_function(node):
880 if isinstance(node, types.DictionaryType):
881 self.process_function(node)
883 self.process_function({node: []})
887 raise YamlImportException("Can not process YAML block: %s" % node)
889 def _log(self, node, is_preceded_by_comment):
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)
899 self.logger.log(logging.TEST, node)
901 is_preceded_by_comment = False
902 return is_preceded_by_comment
904 def yaml_import(cr, module, yamlfile, idref=None, mode='init', noupdate=False):
907 yaml_string = yamlfile.read()
908 yaml_interpreter = YamlInterpreter(cr, module, idref, mode, filename=yamlfile.name, noupdate=noupdate)
909 yaml_interpreter.process(yaml_string)
911 # keeps convention of convert.py
912 convert_yaml_import = yaml_import
914 def threaded_yaml_import(db_name, module_name, file_name, delay=0):
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)
926 threading.Thread(target=f).start()
929 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: