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 process_comment(self, node):
184 def _log_assert_failure(self, severity, msg, *args):
185 self.assert_report.record(False, severity)
186 self.logger.log(severity, msg, *args)
187 if severity >= config['assert_exit_level']:
188 raise YamlImportAbortion('Severe assertion failure (%s), aborting.' % logging.getLevelName(severity))
191 def _get_assertion_id(self, assertion):
193 ids = [self.get_id(assertion.id)]
194 elif assertion.search:
195 q = eval(assertion.search, self.eval_context)
196 ids = self.pool.get(assertion.model).search(self.cr, self.uid, q, context=assertion.context)
198 raise YamlImportException('Nothing to assert: you must give either an id or a search criteria.')
201 def process_assert(self, node):
202 assertion, expressions = node.items()[0]
204 if self.isnoupdate(assertion) and self.mode != 'init':
206 model = self.get_model(assertion.model)
207 ids = self._get_assertion_id(assertion)
208 if assertion.count and len(ids) != assertion.count:
209 msg = 'assertion "%s" failed!\n' \
210 ' Incorrect search count:\n' \
211 ' expected count: %d\n' \
212 ' obtained count: %d\n'
213 args = (assertion.string, assertion.count, len(ids))
214 self._log_assert_failure(assertion.severity, msg, *args)
216 context = self.get_context(assertion, self.eval_context)
218 record = model.browse(self.cr, self.uid, id, context)
219 for test in expressions.get('test', ''):
221 success = eval(test, self.eval_context, RecordDictWrapper(record))
223 raise YamlImportAbortion(e)
225 msg = 'Assertion "%s" FAILED\ntest: %s\n'
226 args = (assertion.string, test)
227 self._log_assert_failure(assertion.severity, msg, *args)
229 else: # all tests were successful for this assertion tag (no break)
230 self.assert_report.record(True, assertion.severity)
232 def _coerce_bool(self, value, default=False):
233 if isinstance(value, types.BooleanType):
235 if isinstance(value, types.StringTypes):
236 b = value.strip().lower() not in ('0', 'false', 'off', 'no')
237 elif isinstance(value, types.IntType):
243 def process_record(self, node):
244 record, fields = node.items()[0]
246 self.validate_xml_id(record.id)
247 if self.isnoupdate(record) and self.mode != 'init':
248 id = self.pool.get('ir.model.data')._update_dummy(self.cr, self.uid, record.model, self.module, record.id)
249 # check if the resource already existed at the last update
251 self.id_map[record] = int(id)
254 if not self._coerce_bool(record.forcecreate):
257 model = self.get_model(record.model)
258 record_dict = self._create_record(model, fields)
259 self.logger.debug("RECORD_DICT %s" % record_dict)
260 id = self.pool.get('ir.model.data')._update(self.cr, self.uid, record.model, \
261 self.module, record_dict, record.id, noupdate=self.isnoupdate(record), mode=self.mode)
262 self.id_map[record.id] = int(id)
263 if config.get('import_partial', False):
266 def _create_record(self, model, fields):
268 for field_name, expression in fields.items():
269 field_value = self._eval_field(model, field_name, expression)
270 record_dict[field_name] = field_value
273 def _eval_field(self, model, field_name, expression):
274 column = model._columns[field_name]
275 if is_ref(expression):
277 other_model_name = expression.model
279 other_model_name = column._obj
280 other_model = self.get_model(other_model_name)
281 if expression.search:
282 q = eval(expression.search, self.eval_context)
283 ids = other_model.search(self.cr, self.uid, q)
285 instances = other_model.browse(self.cr, self.uid, ids)
286 elements = [inst[expression.use] for inst in instances]
289 if column._type in ("many2many", "one2many"):
290 value = [(6, 0, elements)]
293 elif column._type == "many2one":
294 value = self.get_id(expression)
295 elif column._type == "one2many":
296 other_model = self.get_model(column._obj)
297 value = [(0, 0, self._create_record(other_model, fields)) for fields in expression]
298 elif column._type == "many2many":
299 ids = [self.get_id(xml_id) for xml_id in expression]
300 value = [(6, 0, ids)]
302 if is_eval(expression):
303 value = eval(expression.expression, self.eval_context)
306 # raise YamlImportException('Unsupported column "%s" or value %s:%s' % (field_name, type(expression), expression))
309 def process_context(self, node):
310 self.context = node.__dict__
312 self.uid = self.get_id(node.uid)
314 self.noupdate = node.noupdate
316 def process_python(self, node):
318 self.logger.log(logging.TEST, msg, *args)
319 python, statements = node.items()[0]
320 model = self.get_model(python.model)
321 statements = statements.replace("\r\n", "\n")
322 code_context = {'self': model, 'cr': self.cr, 'uid': self.uid, 'log': log, 'context': self.context}
324 code = compile(statements, self.filename, 'exec')
325 eval(code, {'ref': self.get_id}, code_context)
326 except AssertionError, e:
327 self._log_assert_failure(python.severity, 'AssertionError in Python code %s: %s', python.name, e)
330 raise YamlImportAbortion(e)
332 self.assert_report.record(True, python.severity)
334 def process_workflow(self, node):
335 workflow, values = node.items()[0]
336 if self.isnoupdate(workflow) and self.mode != 'init':
338 model = self.get_model(workflow.model)
340 id = self.get_id(workflow.ref)
343 raise YamlImportException('You must define a child node if you do not give a ref.')
344 if not len(values) == 1:
345 raise YamlImportException('Only one child node is accepted (%d given).' % len(values))
347 if not 'model' in value and (not 'eval' in value or not 'search' in value):
348 raise YamlImportException('You must provide a "model" and an "eval" or "search" to evaluate.')
349 value_model = self.get_model(value['model'])
350 local_context = {'obj': lambda x: value_model.browse(self.cr, self.uid, x, context=self.context)}
351 local_context.update(self.id_map)
352 id = eval(value['eval'], self.eval_context, local_context)
354 if workflow.uid is not None:
358 wf_service = netsvc.LocalService("workflow")
359 wf_service.trg_validate(uid, model, id, workflow.action, self.cr)
361 def process_function(self, node):
362 function, values = node.items()[0]
363 if self.isnoupdate(function) and self.mode != 'init':
365 context = self.get_context(function, self.eval_context)
368 args = eval(function.eval, self.eval_context)
370 if not 'model' in value and (not 'eval' in value or not 'search' in value):
371 raise YamlImportException('You must provide a "model" and an "eval" or "search" to evaluate.')
372 value_model = self.get_model(value['model'])
373 local_context = {'obj': lambda x: value_model.browse(self.cr, self.uid, x, context=context)}
374 local_context.update(self.id_map)
375 id = eval(value['eval'], self.eval_context, local_context)
378 model = self.get_model(function.model)
379 method = function.name
380 getattr(model, method)(self.cr, self.uid, *args)
382 def _set_group_values(self, node, values):
384 group_names = node.groups.split(',')
386 for group in group_names:
387 if group.startswith('-'):
388 group_id = self.get_id(group[1:])
389 groups_value.append((3, group_id))
391 group_id = self.get_id(group)
392 groups_value.append((4, group_id))
393 values['groups_id'] = groups_value
395 def process_menuitem(self, node):
396 self.validate_xml_id(node.id)
400 self.cr.execute('select id from ir_ui_menu where parent_id is null and name=%s', (node.name,))
401 res = self.cr.fetchone()
402 values = {'parent_id': parent_id, 'name': node.name}
404 parent_id = self.get_id(node.parent)
405 values = {'parent_id': parent_id}
407 values['name'] = node.name
409 res = [ self.get_id(node.id) ]
410 except: # which exception ?
414 action_type = node.type or 'act_window'
416 "act_window": 'STOCK_NEW',
417 "report.xml": 'STOCK_PASTE',
418 "wizard": 'STOCK_EXECUTE',
419 "url": 'STOCK_JUMP_TO',
421 values['icon'] = icons.get(action_type, 'STOCK_NEW')
422 if action_type == 'act_window':
423 action_id = self.get_id(node.action)
424 self.cr.execute('select view_type,view_mode,name,view_id,target from ir_act_window where id=%s', (action_id,))
425 ir_act_window_result = self.cr.fetchone()
426 assert ir_act_window_result, "No window action defined for this id %s !\n" \
427 "Verify that this is a window action or add a type argument." % (node.action,)
428 action_type, action_mode, action_name, view_id, target = ir_act_window_result
430 self.cr.execute('SELECT type FROM ir_ui_view WHERE id=%s', (view_id,))
431 # TODO guess why action_mode is ir_act_window.view_mode above and ir_ui_view.type here
432 action_mode = self.cr.fetchone()
433 self.cr.execute('SELECT view_mode FROM ir_act_window_view WHERE act_window_id=%s ORDER BY sequence LIMIT 1', (action_id,))
435 action_mode = self.cr.fetchone()
436 if action_type == 'tree':
437 values['icon'] = 'STOCK_INDENT'
438 elif action_mode and action_mode.startswith('tree'):
439 values['icon'] = 'STOCK_JUSTIFY_FILL'
440 elif action_mode and action_mode.startswith('graph'):
441 values['icon'] = 'terp-graph'
442 elif action_mode and action_mode.startswith('calendar'):
443 values['icon'] = 'terp-calendar'
445 values['icon'] = 'STOCK_EXECUTE'
446 if not values.get('name', False):
447 values['name'] = action_name
448 elif action_type == 'wizard':
449 action_id = self.get_id(node.action)
450 self.cr.execute('select name from ir_act_wizard where id=%s', (action_id,))
451 ir_act_wizard_result = self.cr.fetchone()
452 if (not values.get('name', False)) and ir_act_wizard_result:
453 values['name'] = ir_act_wizard_result[0]
455 raise YamlImportException("Unsupported type '%s' in menuitem tag." % action_type)
457 values['sequence'] = node.sequence
459 values['icon'] = node.icon
461 self._set_group_values(node, values)
463 pid = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
464 'ir.ui.menu', self.module, values, node.id, mode=self.mode, \
465 noupdate=self.isnoupdate(node), res_id=res and res[0] or False)
467 if node.id and parent_id:
468 self.id_map[node.id] = int(parent_id)
470 if node.action and pid:
471 action_type = node.type or 'act_window'
472 action_id = self.get_id(node.action)
473 action = "ir.actions.%s,%d" % (action_type, action_id)
474 self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
475 'tree_but_open', 'Menuitem', [('ir.ui.menu', int(parent_id))], action, True, True, xml_id=node.id)
477 def process_act_window(self, node):
478 self.validate_xml_id(node.id)
481 view_id = self.get_id(node.view)
482 context = eval(node.context, self.eval_context)
486 'type': type or 'ir.actions.act_window',
488 'domain': node.domain,
490 'res_model': node.res_model,
491 'src_model': node.src_model,
492 'view_type': node.view_type or 'form',
493 'view_mode': node.view_mode or 'tree,form',
496 'auto_refresh': node.auto_refresh,
499 self._set_group_values(node, values)
502 values['target'] = node.target
503 id = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
504 'ir.actions.act_window', self.module, values, node.id, mode=self.mode)
505 self.id_map[node.id] = int(id)
508 keyword = 'client_action_relate'
509 value = 'ir.actions.act_window,%s' % id
510 replace = node.replace or True
511 self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', keyword, \
512 node.id, [node.src_model], value, replace=replace, noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
513 # TODO add remove ir.model.data
515 def process_delete(self, node):
518 ids = self.pool.get(node.model).search(self.cr, self.uid, eval(node.search, self.eval_context))
521 ids.append(self.get_id(node.id))
525 self.pool.get(node.model).unlink(self.cr, self.uid, ids)
526 self.pool.get('ir.model.data')._unlink(self.cr, self.uid, node.model, ids, direct=True)
528 def process_url(self, node):
529 self.validate_xml_id(node.id)
531 res = {'name': node.name, 'url': node.url, 'target': node.target}
533 id = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
534 "ir.actions.url", self.module, res, node.id, mode=self.mode)
535 self.id_map[node.id] = int(id)
537 if (not node.menu or eval(node.menu)) and id:
538 keyword = node.keyword or 'client_action_multi'
539 value = 'ir.actions.url,%s' % id
540 replace = node.replace or True
541 self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
542 keyword, node.url, ["ir.actions.url"], value, replace=replace, \
543 noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
545 def process_ir_set(self, node):
546 if not self.mode == 'init':
548 _, fields = node.items()[0]
550 for fieldname, expression in fields.items():
551 if isinstance(expression, Eval):
552 value = eval(expression.expression, self.eval_context)
555 res[fieldname] = value
556 self.pool.get('ir.model.data').ir_set(self.cr, self.uid, res['key'], res['key2'], \
557 res['name'], res['models'], res['value'], replace=res.get('replace',True), \
558 isobject=res.get('isobject', False), meta=res.get('meta',None))
560 def process_report(self, node):
562 for dest, f in (('name','string'), ('model','model'), ('report_name','name')):
563 values[dest] = getattr(node, f)
564 assert values[dest], "Attribute %s of report is empty !" % (f,)
565 for field,dest in (('rml','report_rml'),('xml','report_xml'),('xsl','report_xsl'),('attachment','attachment'),('attachment_use','attachment_use')):
566 if getattr(node, field):
567 values[dest] = getattr(node, field)
569 values['auto'] = eval(node.auto)
571 sxw_content = misc.file_open(node.sxw).read()
572 values['report_sxw_content'] = sxw_content
574 values['header'] = eval(node.header)
575 values['multi'] = node.multi and eval(node.multi)
577 self.validate_xml_id(xml_id)
579 self._set_group_values(node, values)
581 id = self.pool.get('ir.model.data')._update(self.cr, self.uid, "ir.actions.report.xml", \
582 self.module, values, xml_id, noupdate=self.isnoupdate(node), mode=self.mode)
583 self.id_map[xml_id] = int(id)
585 if not node.menu or eval(node.menu):
586 keyword = node.keyword or 'client_print_multi'
587 value = 'ir.actions.report.xml,%s' % id
588 replace = node.replace or True
589 self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
590 keyword, values['name'], [values['model']], value, replace=replace, isobject=True, xml_id=xml_id)
592 def process_none(self):
594 Empty node or commented node should not pass silently.
596 self._log_assert_failure(logging.WARNING, "You have an empty block in your tests.")
599 def process(self, yaml_string):
601 Processes a Yaml string. Custom tags are interpreted by 'process_' instance methods.
603 is_preceded_by_comment = False
604 for node in yaml.load(yaml_string):
605 is_preceded_by_comment = self._log(node, is_preceded_by_comment)
607 self._process_node(node)
608 except YamlImportException, e:
609 self.logger.log(logging.ERROR, e)
611 self.logger.log(logging.ERROR, e)
614 def _process_node(self, node):
616 self.process_comment(node)
617 elif is_assert(node):
618 self.process_assert(node)
619 elif is_record(node):
620 self.process_record(node)
621 elif is_python(node):
622 self.process_python(node)
623 elif is_menuitem(node):
624 self.process_menuitem(node)
625 elif is_delete(node):
626 self.process_delete(node)
628 self.process_url(node)
629 elif is_context(node):
630 self.process_context(node)
631 elif is_ir_set(node):
632 self.process_ir_set(node)
633 elif is_act_window(node):
634 self.process_act_window(node)
635 elif is_report(node):
636 self.process_report(node)
637 elif is_workflow(node):
638 if isinstance(node, types.DictionaryType):
639 self.process_workflow(node)
641 self.process_workflow({node: []})
642 elif is_function(node):
643 if isinstance(node, types.DictionaryType):
644 self.process_function(node)
646 self.process_function({node: []})
650 raise YamlImportException("Can not process YAML block: %s" % node)
652 def _log(self, node, is_preceded_by_comment):
654 is_preceded_by_comment = True
655 self.logger.log(logging.TEST, node)
656 elif not is_preceded_by_comment:
657 if isinstance(node, types.DictionaryType):
658 msg = "Creating %s\n with %s"
659 args = node.items()[0]
660 self.logger.log(logging.TEST, msg, *args)
662 self.logger.log(logging.TEST, node)
664 is_preceded_by_comment = False
665 return is_preceded_by_comment
667 def yaml_import(cr, module, yamlfile, idref=None, mode='init', noupdate=False, report=None):
670 yaml_string = yamlfile.read()
671 yaml_interpreter = YamlInterpreter(cr, module, idref, mode, filename=yamlfile.name, noupdate=noupdate)
672 yaml_interpreter.process(yaml_string)
674 # keeps convention of convert.py
675 convert_yaml_import = yaml_import
677 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: