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 = logging.getLogger(__name__)
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.pool = pooler.get_pool(cr.dbname)
138 self.context = {} # opererp context
139 self.eval_context = {'ref': self._ref(),
140 '_ref': self._ref(), # added '_ref' so that record['ref'] is possible
142 'datetime': datetime,
143 'timedelta': timedelta}
146 return lambda xml_id: self.get_id(xml_id)
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,)
153 def validate_xml_id(self, 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" \
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)
167 def get_id(self, xml_id):
168 if xml_id is False or xml_id is None:
171 # raise YamlImportException("The xml_id should be a non empty string.")
172 elif isinstance(xml_id, types.IntType):
174 elif xml_id in self.id_map:
175 id = self.id_map[xml_id]
178 module, checked_xml_id = xml_id.split('.', 1)
181 checked_xml_id = xml_id
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
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))
192 def get_context(self, node, eval_dict):
193 context = self.context.copy()
195 context.update(eval(node.context, eval_dict))
198 def isnoupdate(self, node):
199 return self.noupdate or node.noupdate or False
201 def _get_first_result(self, results, default=False):
204 if isinstance(value, types.TupleType):
210 def process_comment(self, node):
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)
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)
226 def _get_assertion_id(self, assertion):
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)
233 raise YamlImportException('Nothing to assert: you must give either an id or a search criteria.')
236 def process_assert(self, node):
237 if isinstance(node, dict):
238 assertion, expressions = node.items()[0]
240 assertion, expressions = node, []
242 if self.isnoupdate(assertion) and self.mode != 'init':
243 _logger.warning('This assertion was not evaluated ("%s").', assertion.string)
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)
255 context = self.get_context(assertion, self.eval_context)
257 record = model.browse(self.cr, self.uid, id, context)
258 for test in expressions:
260 success = unsafe_eval(test, self.eval_context, RecordDictWrapper(record))
262 _logger.debug('Exception during evaluation of !assert block in yaml_file %s.', self.filename, exc_info=True)
263 raise YamlImportAbortion(e)
265 msg = 'Assertion "%s" FAILED\ntest: %s\n'
266 args = (assertion.string, test)
267 for aop in ('==', '!=', '<>', 'in', 'not in', '>=', '<=', '>', '<'):
269 left, right = test.split(aop,1)
273 lmsg = unsafe_eval(left, self.eval_context, RecordDictWrapper(record))
278 rmsg = unsafe_eval(right, self.eval_context, RecordDictWrapper(record))
282 msg += 'values: ! %s %s %s'
283 args += ( lmsg, aop, rmsg )
286 self._log_assert_failure(assertion.severity, msg, *args)
288 else: # all tests were successful for this assertion tag (no break)
289 self.assert_report.record(True, assertion.severity)
291 def _coerce_bool(self, value, default=False):
292 if isinstance(value, types.BooleanType):
294 if isinstance(value, types.StringTypes):
295 b = value.strip().lower() not in ('0', 'false', 'off', 'no')
296 elif isinstance(value, types.IntType):
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)
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)
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]
319 if model.is_transient():
320 record_dict=self.create_osv_memory_record(record, fields)
322 self.validate_xml_id(record.id)
324 self.pool.get('ir.model.data')._get_id(self.cr, 1, self.module, record.id)
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
333 self.id_map[record] = int(id)
336 if not self._coerce_bool(record.forcecreate):
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
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'))
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'):
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)
366 fields = fields or {}
368 def process_val(key, val):
369 if fg[key]['type']=='many2one':
370 if type(val) in (tuple,list):
372 elif (fg[key]['type']=='one2many'):
375 if len(val) and type(val[0]) == dict:
376 val = map(lambda x: (0,0,x), val)
379 # Process all on_change calls
380 nodes = (view is not False) and [view] or []
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:
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,))
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'))
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])
405 if not el.attrib.get('on_change', False):
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'], )
410 # creating the context
411 class parent2(object):
412 def __init__(self, d):
414 def __getattr__(self, name):
415 return self.d.get(name, False)
417 ctx = record_dict.copy()
418 ctx['context'] = self.context
420 ctx['parent'] = parent2(parent)
423 ctx[a]=process_val(a, defaults.get(a, False))
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
435 nodes = list(el) + nodes
437 for field_name, expression in fields.items():
438 if field_name in record_dict:
440 field_value = self._eval_field(model, field_name, expression, default=False)
441 record_dict[field_name] = field_value
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'
449 model_name = node.model
451 model_name = column._obj
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)
458 instances = model.browse(self.cr, self.uid, ids)
459 value = [inst[node.use] for inst in instances]
463 value = self.get_id(node.id)
468 def process_eval(self, node):
469 return eval(node.expression, self.eval_context)
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]
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)]
484 if isinstance(elements, (list,tuple)):
485 value = self._get_first_result(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)
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)
505 if is_eval(expression):
506 value = self.process_eval(expression)
509 # raise YamlImportException('Unsupported column "%s" or value %s:%s' % (field_name, type(expression), expression))
512 def process_context(self, node):
513 self.context = node.__dict__
515 self.uid = self.get_id(node.uid)
517 self.noupdate = node.noupdate
519 def process_python(self, node):
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
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)
534 _logger.debug('Exception during evaluation of !python block in yaml_file %s.', self.filename, exc_info=True)
537 self.assert_report.record(True, python.severity)
539 def process_workflow(self, node):
540 workflow, values = node.items()[0]
541 if self.isnoupdate(workflow) and self.mode != 'init':
544 id = self.get_id(workflow.ref)
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))
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)
558 if workflow.uid is not None:
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)
570 def _eval_params(self, model, params):
572 for i, param in enumerate(params):
573 if isinstance(param, types.ListType):
574 value = self._eval_params(model, param)
576 value = self.process_ref(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)
590 raise YamlImportException('You must provide either a !ref or at least a "eval" or a "search" to function parameter #%d.' % i)
592 value = param # scalar value
596 def process_function(self, node):
597 function, params = node.items()[0]
598 if self.isnoupdate(function) and self.mode != 'init':
600 model = self.get_model(function.model)
602 args = self.process_eval(function.eval)
604 args = self._eval_params(function.model, params)
605 method = function.name
606 getattr(model, method)(self.cr, self.uid, *args)
608 def _set_group_values(self, node, values):
610 group_names = node.groups.split(',')
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))
617 group_id = self.get_id(group)
618 groups_value.append((4, group_id))
619 values['groups_id'] = groups_value
621 def process_menuitem(self, node):
622 self.validate_xml_id(node.id)
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}
630 parent_id = self.get_id(node.parent)
631 values = {'parent_id': parent_id}
633 values['name'] = node.name
635 res = [ self.get_id(node.id) ]
636 except: # which exception ?
640 action_type = node.type or 'act_window'
642 "act_window": 'STOCK_NEW',
643 "report.xml": 'STOCK_PASTE',
644 "wizard": 'STOCK_EXECUTE',
645 "url": 'STOCK_JUMP_TO',
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
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,))
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'
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]
681 raise YamlImportException("Unsupported type '%s' in menuitem tag." % action_type)
683 values['sequence'] = node.sequence
685 values['icon'] = node.icon
687 self._set_group_values(node, values)
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)
693 if node.id and parent_id:
694 self.id_map[node.id] = int(parent_id)
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)
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)
710 view_id = self.get_id(node.view)
713 context = eval(str(node.context), self.eval_context)
716 'type': node.type or 'ir.actions.act_window',
718 'domain': node.domain,
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',
726 'auto_refresh': node.auto_refresh,
727 'multi': getattr(node, 'multi', False),
730 self._set_group_values(node, values)
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)
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
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):
750 ids = self.pool.get(node.model).search(self.cr, self.uid, eval(node.search, self.eval_context))
752 ids = [self.get_id(node.id)]
754 self.pool.get(node.model).unlink(self.cr, self.uid, ids)
756 _logger.log(logging.TEST, "Record not deleted.")
758 def process_url(self, node):
759 self.validate_xml_id(node.id)
761 res = {'name': node.name, 'url': node.url, 'target': node.target}
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)
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)
775 def process_ir_set(self, node):
776 if not self.mode == 'init':
778 _, fields = node.items()[0]
780 for fieldname, expression in fields.items():
781 if is_eval(expression):
782 value = eval(expression.expression, self.eval_context)
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))
790 def process_report(self, node):
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)
799 values['auto'] = eval(node.auto)
801 sxw_file = misc.file_open(node.sxw)
803 sxw_content = sxw_file.read()
804 values['report_sxw_content'] = sxw_content
808 values['header'] = eval(node.header)
809 values['multi'] = node.multi and eval(node.multi)
811 self.validate_xml_id(xml_id)
813 self._set_group_values(node, values)
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)
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)
826 def process_none(self):
828 Empty node or commented node should not pass silently.
830 self._log_assert_failure(logging.WARNING, "You have an empty block in your tests.")
833 def process(self, yaml_string):
835 Processes a Yaml string. Custom tags are interpreted by 'process_' instance methods.
837 yaml_tag.add_constructors()
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)
843 self._process_node(node)
844 except YamlImportException, e:
850 def _process_node(self, 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)
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)
877 self.process_workflow({node: []})
878 elif is_function(node):
879 if isinstance(node, types.DictionaryType):
880 self.process_function(node)
882 self.process_function({node: []})
886 raise YamlImportException("Can not process YAML block: %s" % node)
888 def _log(self, node, is_preceded_by_comment):
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)
898 _logger.log(logging.TEST, node)
900 is_preceded_by_comment = False
901 return is_preceded_by_comment
903 def yaml_import(cr, module, yamlfile, idref=None, mode='init', noupdate=False):
906 yaml_string = yamlfile.read()
907 yaml_interpreter = YamlInterpreter(cr, module, idref, mode, filename=yamlfile.name, noupdate=noupdate)
908 yaml_interpreter.process(yaml_string)
910 # keeps convention of convert.py
911 convert_yaml_import = yaml_import
913 def threaded_yaml_import(db_name, module_name, file_name, delay=0):
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)
925 threading.Thread(target=f).start()
928 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: