1 # -*- encoding: utf-8 -*-
3 import time # used to eval time.strftime expressions
9 from config import config
14 logger_channel = 'tests'
16 class YamlImportException(Exception):
19 class YamlImportAbortion(Exception):
22 def _is_yaml_mapping(node, tag_constructor):
23 value = isinstance(node, types.DictionaryType) \
24 and len(node.keys()) == 1 \
25 and isinstance(node.keys()[0], tag_constructor)
29 return isinstance(node, types.StringTypes)
32 return _is_yaml_mapping(node, yaml_tag.Assert)
35 return _is_yaml_mapping(node, yaml_tag.Record)
38 return _is_yaml_mapping(node, yaml_tag.Python)
40 def is_menuitem(node):
41 return isinstance(node, yaml_tag.Menuitem) \
42 or _is_yaml_mapping(node, yaml_tag.Menuitem)
44 def is_function(node):
45 return isinstance(node, yaml_tag.Function) \
46 or _is_yaml_mapping(node, yaml_tag.Function)
49 return isinstance(node, yaml_tag.Report)
51 def is_workflow(node):
52 return isinstance(node, yaml_tag.Workflow)
54 def is_act_window(node):
55 return isinstance(node, yaml_tag.ActWindow)
58 return isinstance(node, yaml_tag.Delete)
61 return isinstance(node, yaml_tag.Context)
64 return isinstance(node, yaml_tag.Url)
67 return isinstance(node, yaml_tag.Eval)
70 return isinstance(node, yaml_tag.Ref) \
71 or _is_yaml_mapping(node, yaml_tag.Ref)
74 return _is_yaml_mapping(node, yaml_tag.IrSet)
77 class TestReport(object):
81 def record(self, success, severity):
83 Records the result of an assertion for the failed/success count.
86 if severity in self._report:
87 self._report[severity][success] += 1
89 self._report[severity] = {success: 1, not success: 0}
94 res.append('\nAssertions report:\nLevel\tsuccess\tfailure')
96 for severity in self._report:
97 res.append("%s\t%s\t%s" % (severity, self._report[severity][True], self._report[severity][False]))
98 success += self._report[severity][True]
99 failure += self._report[severity][False]
100 res.append("total\t%s\t%s" % (success, failure))
101 res.append("end of report (%s assertion(s) checked)" % success + failure)
102 return "\n".join(res)
104 class RecordDictWrapper(dict):
106 Used to pass a record as locals in eval:
107 records do not strictly behave like dict, so we force them to.
109 def __init__(self, record):
111 def __getitem__(self, key):
112 if key in self.record:
113 return self.record[key]
114 return dict.__getitem__(self, key)
116 class YamlInterpreter(object):
117 def __init__(self, cr, module, id_map, mode, filename, noupdate=False):
122 self.filename = filename
123 self.assert_report = TestReport()
124 self.noupdate = noupdate
125 self.logger = logging.getLogger("%s.%s" % (logger_channel, self.module))
126 self.pool = pooler.get_pool(cr.dbname)
128 self.context = {} # opererp context
129 self.eval_context = {'ref': self._ref(), '_ref': self._ref(), 'time': time} # added '_ref' so that record['ref'] is possible
132 return lambda xml_id: self.get_id(xml_id)
134 def get_model(self, model_name):
135 model = self.pool.get(model_name)
136 assert model, "The model %s does not exist." % (model_name,)
139 def validate_xml_id(self, xml_id):
142 module, id = xml_id.split('.', 1)
143 assert '.' not in id, "The ID reference '%s' must contains maximum one dot.\n" \
144 "It is used to refer to other modules ID, in the form: module.record_id" \
146 if module != self.module:
147 module_count = self.pool.get('ir.module.module').search_count(self.cr, self.uid, \
148 ['&', ('name', '=', module), ('state', 'in', ['installed'])])
149 assert module_count == 1, 'The ID "%s" refers to an uninstalled module.' % (xml_id,)
150 if len(id) > 64: # TODO where does 64 come from (DB is 128)? should be a constant or loaded form DB
151 self.logger.log(logging.ERROR, 'id: %s is to long (max: 64)', id)
153 def get_id(self, xml_id):
155 raise YamlImportException("The xml_id should be a non empty string.")
156 if isinstance(xml_id, types.IntType):
158 elif xml_id in self.id_map:
159 id = self.id_map[xml_id]
162 module, checked_xml_id = xml_id.split('.', 1)
165 checked_xml_id = xml_id
166 ir_id = self.pool.get('ir.model.data')._get_id(self.cr, self.uid, module, checked_xml_id)
167 obj = self.pool.get('ir.model.data').read(self.cr, self.uid, ir_id, ['res_id'])
168 id = int(obj['res_id'])
169 self.id_map[xml_id] = id
172 def get_context(self, node, eval_dict):
173 context = self.context.copy()
175 context.update(eval(node.context, eval_dict))
178 def isnoupdate(self, node):
179 return self.noupdate or node.noupdate or False
181 def _get_first_result(self, results, default=False):
184 if isinstance(value, types.TupleType):
190 def process_comment(self, node):
193 def _log_assert_failure(self, severity, msg, *args):
194 if isinstance(severity, types.StringTypes):
195 levelname = severity.strip().upper()
196 level = logging.getLevelName(levelname)
199 levelname = logging.getLevelName(level)
200 self.assert_report.record(False, levelname)
201 self.logger.log(level, msg, *args)
202 if level >= config['assert_exit_level']:
203 raise YamlImportAbortion('Severe assertion failure (%s), aborting.' % levelname)
206 def _get_assertion_id(self, assertion):
208 ids = [self.get_id(assertion.id)]
209 elif assertion.search:
210 q = eval(assertion.search, self.eval_context)
211 ids = self.pool.get(assertion.model).search(self.cr, self.uid, q, context=assertion.context)
213 raise YamlImportException('Nothing to assert: you must give either an id or a search criteria.')
216 def process_assert(self, node):
217 assertion, expressions = node.items()[0]
219 if self.isnoupdate(assertion) and self.mode != 'init':
220 self.logger.warn('This assertion was not evaluated ("%s").' % assertion.string)
222 model = self.get_model(assertion.model)
223 ids = self._get_assertion_id(assertion)
224 if assertion.count and len(ids) != assertion.count:
225 msg = 'assertion "%s" failed!\n' \
226 ' Incorrect search count:\n' \
227 ' expected count: %d\n' \
228 ' obtained count: %d\n'
229 args = (assertion.string, assertion.count, len(ids))
230 self._log_assert_failure(assertion.severity, msg, *args)
232 context = self.get_context(assertion, self.eval_context)
234 record = model.browse(self.cr, self.uid, id, context)
235 for test in expressions:
237 success = eval(test, self.eval_context, RecordDictWrapper(record))
239 raise YamlImportAbortion(e)
241 msg = 'Assertion "%s" FAILED\ntest: %s\n'
242 args = (assertion.string, test)
243 self._log_assert_failure(assertion.severity, msg, *args)
245 else: # all tests were successful for this assertion tag (no break)
246 self.assert_report.record(True, assertion.severity)
248 def _coerce_bool(self, value, default=False):
249 if isinstance(value, types.BooleanType):
251 if isinstance(value, types.StringTypes):
252 b = value.strip().lower() not in ('0', 'false', 'off', 'no')
253 elif isinstance(value, types.IntType):
259 def process_record(self, node):
260 record, fields = node.items()[0]
262 self.validate_xml_id(record.id)
263 if self.isnoupdate(record) and self.mode != 'init':
264 id = self.pool.get('ir.model.data')._update_dummy(self.cr, self.uid, record.model, self.module, record.id)
265 # check if the resource already existed at the last update
267 self.id_map[record] = int(id)
270 if not self._coerce_bool(record.forcecreate):
273 model = self.get_model(record.model)
274 record_dict = self._create_record(model, fields)
275 self.logger.debug("RECORD_DICT %s" % record_dict)
276 id = self.pool.get('ir.model.data')._update(self.cr, self.uid, record.model, \
277 self.module, record_dict, record.id, noupdate=self.isnoupdate(record), mode=self.mode)
278 self.id_map[record.id] = int(id)
279 if config.get('import_partial', False):
282 def _create_record(self, model, fields):
284 for field_name, expression in fields.items():
285 field_value = self._eval_field(model, field_name, expression)
286 record_dict[field_name] = field_value
289 def process_ref(self, node, column=None):
292 model_name = node.model
294 model_name = column._obj
296 raise YamlImportException('You need to give a model for the search, or a column to infer it.')
297 model = self.get_model(model_name)
298 q = eval(node.search, self.eval_context)
299 ids = model.search(self.cr, self.uid, q)
301 instances = model.browse(self.cr, self.uid, ids)
302 value = [inst[node.use] for inst in instances]
306 value = self.get_id(node.id)
311 def process_eval(self, node):
312 return eval(node.expression, self.eval_context)
314 def _eval_field(self, model, field_name, expression):
315 column = model._columns[field_name]
316 if is_ref(expression):
317 elements = self.process_ref(expression)
318 if column._type in ("many2many", "one2many"):
319 value = [(6, 0, elements)]
321 value = self._get_first_result(elements)
322 elif column._type == "many2one":
323 value = self.get_id(expression)
324 elif column._type == "one2many":
325 other_model = self.get_model(column._obj)
326 value = [(0, 0, self._create_record(other_model, fields)) for fields in expression]
327 elif column._type == "many2many":
328 ids = [self.get_id(xml_id) for xml_id in expression]
329 value = [(6, 0, ids)]
331 if is_eval(expression):
332 value = self.process_eval(expression)
335 # raise YamlImportException('Unsupported column "%s" or value %s:%s' % (field_name, type(expression), expression))
338 def process_context(self, node):
339 self.context = node.__dict__
341 self.uid = self.get_id(node.uid)
343 self.noupdate = node.noupdate
345 def process_python(self, node):
347 self.logger.log(logging.TEST, msg, *args)
348 python, statements = node.items()[0]
349 model = self.get_model(python.model)
350 statements = statements.replace("\r\n", "\n")
351 code_context = {'self': model, 'cr': self.cr, 'uid': self.uid, 'log': log, 'context': self.context}
353 code = compile(statements, self.filename, 'exec')
354 eval(code, {'ref': self.get_id}, code_context)
355 except AssertionError, e:
356 self._log_assert_failure(python.severity, 'AssertionError in Python code %s: %s', python.name, e)
359 raise YamlImportAbortion(e)
361 self.assert_report.record(True, python.severity)
363 def process_workflow(self, node):
364 workflow, values = node.items()[0]
365 if self.isnoupdate(workflow) and self.mode != 'init':
368 id = self.get_id(workflow.ref)
371 raise YamlImportException('You must define a child node if you do not give a ref.')
372 if not len(values) == 1:
373 raise YamlImportException('Only one child node is accepted (%d given).' % len(values))
375 if not 'model' in value and (not 'eval' in value or not 'search' in value):
376 raise YamlImportException('You must provide a "model" and an "eval" or "search" to evaluate.')
377 value_model = self.get_model(value['model'])
378 local_context = {'obj': lambda x: value_model.browse(self.cr, self.uid, x, context=self.context)}
379 local_context.update(self.id_map)
380 id = eval(value['eval'], self.eval_context, local_context)
382 if workflow.uid is not None:
386 wf_service = netsvc.LocalService("workflow")
387 wf_service.trg_validate(uid, workflow.model, id, workflow.action, self.cr)
389 def _eval_params(self, model, params):
391 for i, param in enumerate(params):
392 if isinstance(param, types.ListType):
393 value = self._eval_params(model, param)
395 value = self.process_ref(param)
397 value = self.process_eval(param)
398 elif isinstance(param, types.DictionaryType): # supports XML syntax
399 param_model = self.get_model(param.get('model', model))
400 if 'search' in param:
401 q = eval(param['search'], self.eval_context)
402 ids = param_model.search(cr, uid, q)
403 value = self._get_first_result(ids)
404 elif 'eval' in param:
405 local_context = {'obj': lambda x: param_model.browse(self.cr, self.uid, x, context)}
406 local_context.update(self.id_map)
407 value = eval(param['eval'], self.eval_context, local_context)
409 raise YamlImportException('You must provide either a !ref or at least a "eval" or a "search" to function parameter #%d.' % i)
411 value = param # scalar value
415 def process_function(self, node):
416 function, params = node.items()[0]
417 if self.isnoupdate(function) and self.mode != 'init':
419 model = self.get_model(function.model)
420 context = self.get_context(function, self.eval_context)
422 args = self.process_eval(function.eval)
424 args = self._eval_params(function.model, params)
425 method = function.name
426 getattr(model, method)(self.cr, self.uid, *args)
428 def _set_group_values(self, node, values):
430 group_names = node.groups.split(',')
432 for group in group_names:
433 if group.startswith('-'):
434 group_id = self.get_id(group[1:])
435 groups_value.append((3, group_id))
437 group_id = self.get_id(group)
438 groups_value.append((4, group_id))
439 values['groups_id'] = groups_value
441 def process_menuitem(self, node):
442 self.validate_xml_id(node.id)
446 self.cr.execute('select id from ir_ui_menu where parent_id is null and name=%s', (node.name,))
447 res = self.cr.fetchone()
448 values = {'parent_id': parent_id, 'name': node.name}
450 parent_id = self.get_id(node.parent)
451 values = {'parent_id': parent_id}
453 values['name'] = node.name
455 res = [ self.get_id(node.id) ]
456 except: # which exception ?
460 action_type = node.type or 'act_window'
462 "act_window": 'STOCK_NEW',
463 "report.xml": 'STOCK_PASTE',
464 "wizard": 'STOCK_EXECUTE',
465 "url": 'STOCK_JUMP_TO',
467 values['icon'] = icons.get(action_type, 'STOCK_NEW')
468 if action_type == 'act_window':
469 action_id = self.get_id(node.action)
470 self.cr.execute('select view_type,view_mode,name,view_id,target from ir_act_window where id=%s', (action_id,))
471 ir_act_window_result = self.cr.fetchone()
472 assert ir_act_window_result, "No window action defined for this id %s !\n" \
473 "Verify that this is a window action or add a type argument." % (node.action,)
474 action_type, action_mode, action_name, view_id, target = ir_act_window_result
476 self.cr.execute('SELECT type FROM ir_ui_view WHERE id=%s', (view_id,))
477 # TODO guess why action_mode is ir_act_window.view_mode above and ir_ui_view.type here
478 action_mode = self.cr.fetchone()
479 self.cr.execute('SELECT view_mode FROM ir_act_window_view WHERE act_window_id=%s ORDER BY sequence LIMIT 1', (action_id,))
481 action_mode = self.cr.fetchone()
482 if action_type == 'tree':
483 values['icon'] = 'STOCK_INDENT'
484 elif action_mode and action_mode.startswith('tree'):
485 values['icon'] = 'STOCK_JUSTIFY_FILL'
486 elif action_mode and action_mode.startswith('graph'):
487 values['icon'] = 'terp-graph'
488 elif action_mode and action_mode.startswith('calendar'):
489 values['icon'] = 'terp-calendar'
491 values['icon'] = 'STOCK_EXECUTE'
492 if not values.get('name', False):
493 values['name'] = action_name
494 elif action_type == 'wizard':
495 action_id = self.get_id(node.action)
496 self.cr.execute('select name from ir_act_wizard where id=%s', (action_id,))
497 ir_act_wizard_result = self.cr.fetchone()
498 if (not values.get('name', False)) and ir_act_wizard_result:
499 values['name'] = ir_act_wizard_result[0]
501 raise YamlImportException("Unsupported type '%s' in menuitem tag." % action_type)
503 values['sequence'] = node.sequence
505 values['icon'] = node.icon
507 self._set_group_values(node, values)
509 pid = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
510 'ir.ui.menu', self.module, values, node.id, mode=self.mode, \
511 noupdate=self.isnoupdate(node), res_id=res and res[0] or False)
513 if node.id and parent_id:
514 self.id_map[node.id] = int(parent_id)
516 if node.action and pid:
517 action_type = node.type or 'act_window'
518 action_id = self.get_id(node.action)
519 action = "ir.actions.%s,%d" % (action_type, action_id)
520 self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
521 'tree_but_open', 'Menuitem', [('ir.ui.menu', int(parent_id))], action, True, True, xml_id=node.id)
523 def process_act_window(self, node):
524 self.validate_xml_id(node.id)
527 view_id = self.get_id(node.view)
528 context = eval(node.context, self.eval_context)
532 'type': type or 'ir.actions.act_window',
534 'domain': node.domain,
536 'res_model': node.res_model,
537 'src_model': node.src_model,
538 'view_type': node.view_type or 'form',
539 'view_mode': node.view_mode or 'tree,form',
542 'auto_refresh': node.auto_refresh,
545 self._set_group_values(node, values)
548 values['target'] = node.target
549 id = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
550 'ir.actions.act_window', self.module, values, node.id, mode=self.mode)
551 self.id_map[node.id] = int(id)
554 keyword = 'client_action_relate'
555 value = 'ir.actions.act_window,%s' % id
556 replace = node.replace or True
557 self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', keyword, \
558 node.id, [node.src_model], value, replace=replace, noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
559 # TODO add remove ir.model.data
561 def process_delete(self, node):
563 ids = self.pool.get(node.model).search(self.cr, self.uid, eval(node.search, self.eval_context))
565 ids = [self.get_id(node.id)]
567 self.pool.get(node.model).unlink(self.cr, self.uid, ids)
568 self.pool.get('ir.model.data')._unlink(self.cr, self.uid, node.model, ids)
570 def process_url(self, node):
571 self.validate_xml_id(node.id)
573 res = {'name': node.name, 'url': node.url, 'target': node.target}
575 id = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
576 "ir.actions.url", self.module, res, node.id, mode=self.mode)
577 self.id_map[node.id] = int(id)
579 if (not node.menu or eval(node.menu)) and id:
580 keyword = node.keyword or 'client_action_multi'
581 value = 'ir.actions.url,%s' % id
582 replace = node.replace or True
583 self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
584 keyword, node.url, ["ir.actions.url"], value, replace=replace, \
585 noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
587 def process_ir_set(self, node):
588 if not self.mode == 'init':
590 _, fields = node.items()[0]
592 for fieldname, expression in fields.items():
593 if isinstance(expression, Eval):
594 value = eval(expression.expression, self.eval_context)
597 res[fieldname] = value
598 self.pool.get('ir.model.data').ir_set(self.cr, self.uid, res['key'], res['key2'], \
599 res['name'], res['models'], res['value'], replace=res.get('replace',True), \
600 isobject=res.get('isobject', False), meta=res.get('meta',None))
602 def process_report(self, node):
604 for dest, f in (('name','string'), ('model','model'), ('report_name','name')):
605 values[dest] = getattr(node, f)
606 assert values[dest], "Attribute %s of report is empty !" % (f,)
607 for field,dest in (('rml','report_rml'),('xml','report_xml'),('xsl','report_xsl'),('attachment','attachment'),('attachment_use','attachment_use')):
608 if getattr(node, field):
609 values[dest] = getattr(node, field)
611 values['auto'] = eval(node.auto)
613 sxw_content = misc.file_open(node.sxw).read()
614 values['report_sxw_content'] = sxw_content
616 values['header'] = eval(node.header)
617 values['multi'] = node.multi and eval(node.multi)
619 self.validate_xml_id(xml_id)
621 self._set_group_values(node, values)
623 id = self.pool.get('ir.model.data')._update(self.cr, self.uid, "ir.actions.report.xml", \
624 self.module, values, xml_id, noupdate=self.isnoupdate(node), mode=self.mode)
625 self.id_map[xml_id] = int(id)
627 if not node.menu or eval(node.menu):
628 keyword = node.keyword or 'client_print_multi'
629 value = 'ir.actions.report.xml,%s' % id
630 replace = node.replace or True
631 self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
632 keyword, values['name'], [values['model']], value, replace=replace, isobject=True, xml_id=xml_id)
634 def process_none(self):
636 Empty node or commented node should not pass silently.
638 self._log_assert_failure(logging.WARNING, "You have an empty block in your tests.")
641 def process(self, yaml_string):
643 Processes a Yaml string. Custom tags are interpreted by 'process_' instance methods.
645 is_preceded_by_comment = False
646 for node in yaml.load(yaml_string):
647 is_preceded_by_comment = self._log(node, is_preceded_by_comment)
649 self._process_node(node)
650 except YamlImportException, e:
651 self.logger.exception(e)
653 self.logger.exception(e)
656 def _process_node(self, node):
658 self.process_comment(node)
659 elif is_assert(node):
660 self.process_assert(node)
661 elif is_record(node):
662 self.process_record(node)
663 elif is_python(node):
664 self.process_python(node)
665 elif is_menuitem(node):
666 self.process_menuitem(node)
667 elif is_delete(node):
668 self.process_delete(node)
670 self.process_url(node)
671 elif is_context(node):
672 self.process_context(node)
673 elif is_ir_set(node):
674 self.process_ir_set(node)
675 elif is_act_window(node):
676 self.process_act_window(node)
677 elif is_report(node):
678 self.process_report(node)
679 elif is_workflow(node):
680 if isinstance(node, types.DictionaryType):
681 self.process_workflow(node)
683 self.process_workflow({node: []})
684 elif is_function(node):
685 if isinstance(node, types.DictionaryType):
686 self.process_function(node)
688 self.process_function({node: []})
692 raise YamlImportException("Can not process YAML block: %s" % node)
694 def _log(self, node, is_preceded_by_comment):
696 is_preceded_by_comment = True
697 self.logger.log(logging.TEST, node)
698 elif not is_preceded_by_comment:
699 if isinstance(node, types.DictionaryType):
700 msg = "Creating %s\n with %s"
701 args = node.items()[0]
702 self.logger.log(logging.TEST, msg, *args)
704 self.logger.log(logging.TEST, node)
706 is_preceded_by_comment = False
707 return is_preceded_by_comment
709 def yaml_import(cr, module, yamlfile, idref=None, mode='init', noupdate=False, report=None):
712 yaml_string = yamlfile.read()
713 yaml_interpreter = YamlInterpreter(cr, module, idref, mode, filename=yamlfile.name, noupdate=noupdate)
714 yaml_interpreter.process(yaml_string)
716 # keeps convention of convert.py
717 convert_yaml_import = yaml_import
719 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: