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 # YAML import needs both safe and unsafe eval, but let's
18 from safe_eval import safe_eval as eval
20 logger_channel = 'tests'
22 class YamlImportException(Exception):
25 class YamlImportAbortion(Exception):
28 def _is_yaml_mapping(node, tag_constructor):
29 value = isinstance(node, types.DictionaryType) \
30 and len(node.keys()) == 1 \
31 and isinstance(node.keys()[0], tag_constructor)
35 return isinstance(node, types.StringTypes)
38 return isinstance(node, yaml_tag.Assert) \
39 or _is_yaml_mapping(node, yaml_tag.Assert)
42 return _is_yaml_mapping(node, yaml_tag.Record)
45 return _is_yaml_mapping(node, yaml_tag.Python)
47 def is_menuitem(node):
48 return isinstance(node, yaml_tag.Menuitem) \
49 or _is_yaml_mapping(node, yaml_tag.Menuitem)
51 def is_function(node):
52 return isinstance(node, yaml_tag.Function) \
53 or _is_yaml_mapping(node, yaml_tag.Function)
56 return isinstance(node, yaml_tag.Report)
58 def is_workflow(node):
59 return isinstance(node, yaml_tag.Workflow)
61 def is_act_window(node):
62 return isinstance(node, yaml_tag.ActWindow)
65 return isinstance(node, yaml_tag.Delete)
68 return isinstance(node, yaml_tag.Context)
71 return isinstance(node, yaml_tag.Url)
74 return isinstance(node, yaml_tag.Eval)
77 return isinstance(node, yaml_tag.Ref) \
78 or _is_yaml_mapping(node, yaml_tag.Ref)
81 return _is_yaml_mapping(node, yaml_tag.IrSet)
84 return isinstance(node, basestring)
86 class TestReport(object):
90 def record(self, success, severity):
92 Records the result of an assertion for the failed/success count.
95 if severity in self._report:
96 self._report[severity][success] += 1
98 self._report[severity] = {success: 1, not success: 0}
103 res.append('\nAssertions report:\nLevel\tsuccess\tfailure')
104 success = failure = 0
105 for severity in self._report:
106 res.append("%s\t%s\t%s" % (severity, self._report[severity][True], self._report[severity][False]))
107 success += self._report[severity][True]
108 failure += self._report[severity][False]
109 res.append("total\t%s\t%s" % (success, failure))
110 res.append("end of report (%s assertion(s) checked)" % (success + failure))
111 return "\n".join(res)
113 class RecordDictWrapper(dict):
115 Used to pass a record as locals in eval:
116 records do not strictly behave like dict, so we force them to.
118 def __init__(self, record):
120 def __getitem__(self, key):
121 if key in self.record:
122 return self.record[key]
123 return dict.__getitem__(self, key)
125 class YamlInterpreter(object):
126 def __init__(self, cr, module, id_map, mode, filename, noupdate=False):
131 self.filename = filename
132 self.assert_report = TestReport()
133 self.noupdate = noupdate
134 self.logger = logging.getLogger("%s.%s" % (logger_channel, self.module))
135 self.pool = pooler.get_pool(cr.dbname)
137 self.context = {} # opererp context
138 self.eval_context = {'ref': self._ref(),
139 '_ref': self._ref(), # added '_ref' so that record['ref'] is possible
141 'datetime': datetime,
142 'timedelta': timedelta}
145 return lambda xml_id: self.get_id(xml_id)
147 def get_model(self, model_name):
148 model = self.pool.get(model_name)
149 assert model, "The model %s does not exist." % (model_name,)
152 def validate_xml_id(self, xml_id):
155 module, id = xml_id.split('.', 1)
156 assert '.' not in id, "The ID reference '%s' must contains maximum one dot.\n" \
157 "It is used to refer to other modules ID, in the form: module.record_id" \
159 if module != self.module:
160 module_count = self.pool.get('ir.module.module').search_count(self.cr, self.uid, \
161 ['&', ('name', '=', module), ('state', 'in', ['installed'])])
162 assert module_count == 1, 'The ID "%s" refers to an uninstalled module.' % (xml_id,)
163 if len(id) > 64: # TODO where does 64 come from (DB is 128)? should be a constant or loaded form DB
164 self.logger.log(logging.ERROR, 'id: %s is to long (max: 64)', id)
166 def get_id(self, xml_id):
168 raise YamlImportException("The xml_id should be a non empty string.")
169 if isinstance(xml_id, types.IntType):
171 elif xml_id in self.id_map:
172 id = self.id_map[xml_id]
175 module, checked_xml_id = xml_id.split('.', 1)
178 checked_xml_id = xml_id
180 _, id = self.pool.get('ir.model.data').get_object_reference(self.cr, self.uid, module, checked_xml_id)
181 self.id_map[xml_id] = id
183 raise ValueError("""%s not found when processing %s.
184 This Yaml file appears to depend on missing data. This often happens for
185 tests that belong to a module's test suite and depend on each other.""" % (checked_xml_id, self.filename))
189 def get_context(self, node, eval_dict):
190 context = self.context.copy()
192 context.update(eval(node.context, eval_dict))
195 def isnoupdate(self, node):
196 return self.noupdate or node.noupdate or False
198 def _get_first_result(self, results, default=False):
201 if isinstance(value, types.TupleType):
207 def process_comment(self, node):
210 def _log_assert_failure(self, severity, msg, *args):
211 if isinstance(severity, types.StringTypes):
212 levelname = severity.strip().upper()
213 level = logging.getLevelName(levelname)
216 levelname = logging.getLevelName(level)
217 self.assert_report.record(False, levelname)
218 self.logger.log(level, msg, *args)
219 if level >= config['assert_exit_level']:
220 raise YamlImportAbortion('Severe assertion failure (%s), aborting.' % levelname)
223 def _get_assertion_id(self, assertion):
225 ids = [self.get_id(assertion.id)]
226 elif assertion.search:
227 q = eval(assertion.search, self.eval_context)
228 ids = self.pool.get(assertion.model).search(self.cr, self.uid, q, context=assertion.context)
230 raise YamlImportException('Nothing to assert: you must give either an id or a search criteria.')
233 def process_assert(self, node):
234 if isinstance(node, dict):
235 assertion, expressions = node.items()[0]
237 assertion, expressions = node, []
239 if self.isnoupdate(assertion) and self.mode != 'init':
240 self.logger.warn('This assertion was not evaluated ("%s").' % assertion.string)
242 model = self.get_model(assertion.model)
243 ids = self._get_assertion_id(assertion)
244 if assertion.count is not None and len(ids) != assertion.count:
245 msg = 'assertion "%s" failed!\n' \
246 ' Incorrect search count:\n' \
247 ' expected count: %d\n' \
248 ' obtained count: %d\n'
249 args = (assertion.string, assertion.count, len(ids))
250 self._log_assert_failure(assertion.severity, msg, *args)
252 context = self.get_context(assertion, self.eval_context)
254 record = model.browse(self.cr, self.uid, id, context)
255 for test in expressions:
257 success = unsafe_eval(test, self.eval_context, RecordDictWrapper(record))
259 self.logger.debug('Exception during evaluation of !assert block in yaml_file %s.', self.filename, exc_info=True)
260 raise YamlImportAbortion(e)
262 msg = 'Assertion "%s" FAILED\ntest: %s\n'
263 args = (assertion.string, test)
264 for aop in ('==', '!=', '<>', 'in', 'not in', '>=', '<=', '>', '<'):
266 left, right = test.split(aop,1)
270 lmsg = unsafe_eval(left, self.eval_context, RecordDictWrapper(record))
275 rmsg = unsafe_eval(right, self.eval_context, RecordDictWrapper(record))
279 msg += 'values: ! %s %s %s'
280 args += ( lmsg, aop, rmsg )
283 self._log_assert_failure(assertion.severity, msg, *args)
285 else: # all tests were successful for this assertion tag (no break)
286 self.assert_report.record(True, assertion.severity)
288 def _coerce_bool(self, value, default=False):
289 if isinstance(value, types.BooleanType):
291 if isinstance(value, types.StringTypes):
292 b = value.strip().lower() not in ('0', 'false', 'off', 'no')
293 elif isinstance(value, types.IntType):
299 def create_osv_memory_record(self, record, fields):
300 model = self.get_model(record.model)
301 record_dict = self._create_record(model, fields)
302 id_new=model.create(self.cr, self.uid, record_dict, context=self.context)
303 self.id_map[record.id] = int(id_new)
306 def process_record(self, node):
307 import openerp.osv as osv
308 record, fields = node.items()[0]
309 model = self.get_model(record.model)
310 if isinstance(model, osv.osv.osv_memory):
311 record_dict=self.create_osv_memory_record(record, fields)
313 self.validate_xml_id(record.id)
314 if self.isnoupdate(record) and self.mode != 'init':
315 id = self.pool.get('ir.model.data')._update_dummy(self.cr, 1, record.model, self.module, record.id)
316 # check if the resource already existed at the last update
318 self.id_map[record] = int(id)
321 if not self._coerce_bool(record.forcecreate):
324 record_dict = self._create_record(model, fields)
325 self.logger.debug("RECORD_DICT %s" % record_dict)
326 #context = self.get_context(record, self.eval_context)
327 context = record.context #TOFIX: record.context like {'withoutemployee':True} should pass from self.eval_context. example: test_project.yml in project module
328 id = self.pool.get('ir.model.data')._update(self.cr, 1, record.model, \
329 self.module, record_dict, record.id, noupdate=self.isnoupdate(record), mode=self.mode, context=context)
330 self.id_map[record.id] = int(id)
331 if config.get('import_partial'):
334 def _create_record(self, model, fields):
336 fields = fields or {}
337 for field_name, expression in fields.items():
338 field_value = self._eval_field(model, field_name, expression)
339 record_dict[field_name] = field_value
342 def process_ref(self, node, column=None):
345 model_name = node.model
347 model_name = column._obj
349 raise YamlImportException('You need to give a model for the search, or a column to infer it.')
350 model = self.get_model(model_name)
351 q = eval(node.search, self.eval_context)
352 ids = model.search(self.cr, self.uid, q)
354 instances = model.browse(self.cr, self.uid, ids)
355 value = [inst[node.use] for inst in instances]
359 value = self.get_id(node.id)
364 def process_eval(self, node):
365 return eval(node.expression, self.eval_context)
367 def _eval_field(self, model, field_name, expression):
368 # TODO this should be refactored as something like model.get_field() in bin/osv
369 if field_name in model._columns:
370 column = model._columns[field_name]
371 elif field_name in model._inherit_fields:
372 column = model._inherit_fields[field_name][2]
374 raise KeyError("Object '%s' does not contain field '%s'" % (model, field_name))
375 if is_ref(expression):
376 elements = self.process_ref(expression, column)
377 if column._type in ("many2many", "one2many"):
378 value = [(6, 0, elements)]
380 value = self._get_first_result(elements)
381 elif column._type == "many2one":
382 value = self.get_id(expression)
383 elif column._type == "one2many":
384 other_model = self.get_model(column._obj)
385 value = [(0, 0, self._create_record(other_model, fields)) for fields in expression]
386 elif column._type == "many2many":
387 ids = [self.get_id(xml_id) for xml_id in expression]
388 value = [(6, 0, ids)]
389 elif column._type == "date" and is_string(expression):
390 # enforce ISO format for string date values, to be locale-agnostic during tests
391 time.strptime(expression, misc.DEFAULT_SERVER_DATE_FORMAT)
393 elif column._type == "datetime" and is_string(expression):
394 # enforce ISO format for string datetime values, to be locale-agnostic during tests
395 time.strptime(expression, misc.DEFAULT_SERVER_DATETIME_FORMAT)
398 if is_eval(expression):
399 value = self.process_eval(expression)
402 # raise YamlImportException('Unsupported column "%s" or value %s:%s' % (field_name, type(expression), expression))
405 def process_context(self, node):
406 self.context = node.__dict__
408 self.uid = self.get_id(node.uid)
410 self.noupdate = node.noupdate
412 def process_python(self, node):
414 self.logger.log(logging.TEST, msg, *args)
415 python, statements = node.items()[0]
416 model = self.get_model(python.model)
417 statements = statements.replace("\r\n", "\n")
418 code_context = {'model': model, 'cr': self.cr, 'uid': self.uid, 'log': log, 'context': self.context}
419 code_context.update({'self': model}) # remove me when no !python block test uses 'self' anymore
421 code_obj = compile(statements, self.filename, 'exec')
422 unsafe_eval(code_obj, {'ref': self.get_id}, code_context)
423 except AssertionError, e:
424 self._log_assert_failure(python.severity, 'AssertionError in Python code %s: %s', python.name, e)
427 self.logger.debug('Exception during evaluation of !python block in yaml_file %s.', self.filename, exc_info=True)
430 self.assert_report.record(True, python.severity)
432 def process_workflow(self, node):
433 workflow, values = node.items()[0]
434 if self.isnoupdate(workflow) and self.mode != 'init':
437 id = self.get_id(workflow.ref)
440 raise YamlImportException('You must define a child node if you do not give a ref.')
441 if not len(values) == 1:
442 raise YamlImportException('Only one child node is accepted (%d given).' % len(values))
444 if not 'model' in value and (not 'eval' in value or not 'search' in value):
445 raise YamlImportException('You must provide a "model" and an "eval" or "search" to evaluate.')
446 value_model = self.get_model(value['model'])
447 local_context = {'obj': lambda x: value_model.browse(self.cr, self.uid, x, context=self.context)}
448 local_context.update(self.id_map)
449 id = eval(value['eval'], self.eval_context, local_context)
451 if workflow.uid is not None:
455 self.cr.execute('select distinct signal from wkf_transition')
456 signals=[x['signal'] for x in self.cr.dictfetchall()]
457 if workflow.action not in signals:
458 raise YamlImportException('Incorrect action %s. No such action defined' % workflow.action)
459 import openerp.netsvc as netsvc
460 wf_service = netsvc.LocalService("workflow")
461 wf_service.trg_validate(uid, workflow.model, id, workflow.action, self.cr)
463 def _eval_params(self, model, params):
465 for i, param in enumerate(params):
466 if isinstance(param, types.ListType):
467 value = self._eval_params(model, param)
469 value = self.process_ref(param)
471 value = self.process_eval(param)
472 elif isinstance(param, types.DictionaryType): # supports XML syntax
473 param_model = self.get_model(param.get('model', model))
474 if 'search' in param:
475 q = eval(param['search'], self.eval_context)
476 ids = param_model.search(self.cr, self.uid, q)
477 value = self._get_first_result(ids)
478 elif 'eval' in param:
479 local_context = {'obj': lambda x: param_model.browse(self.cr, self.uid, x, self.context)}
480 local_context.update(self.id_map)
481 value = eval(param['eval'], self.eval_context, local_context)
483 raise YamlImportException('You must provide either a !ref or at least a "eval" or a "search" to function parameter #%d.' % i)
485 value = param # scalar value
489 def process_function(self, node):
490 function, params = node.items()[0]
491 if self.isnoupdate(function) and self.mode != 'init':
493 model = self.get_model(function.model)
495 args = self.process_eval(function.eval)
497 args = self._eval_params(function.model, params)
498 method = function.name
499 getattr(model, method)(self.cr, self.uid, *args)
501 def _set_group_values(self, node, values):
503 group_names = node.groups.split(',')
505 for group in group_names:
506 if group.startswith('-'):
507 group_id = self.get_id(group[1:])
508 groups_value.append((3, group_id))
510 group_id = self.get_id(group)
511 groups_value.append((4, group_id))
512 values['groups_id'] = groups_value
514 def process_menuitem(self, node):
515 self.validate_xml_id(node.id)
519 self.cr.execute('select id from ir_ui_menu where parent_id is null and name=%s', (node.name,))
520 res = self.cr.fetchone()
521 values = {'parent_id': parent_id, 'name': node.name}
523 parent_id = self.get_id(node.parent)
524 values = {'parent_id': parent_id}
526 values['name'] = node.name
528 res = [ self.get_id(node.id) ]
529 except: # which exception ?
533 action_type = node.type or 'act_window'
535 "act_window": 'STOCK_NEW',
536 "report.xml": 'STOCK_PASTE',
537 "wizard": 'STOCK_EXECUTE',
538 "url": 'STOCK_JUMP_TO',
540 values['icon'] = icons.get(action_type, 'STOCK_NEW')
541 if action_type == 'act_window':
542 action_id = self.get_id(node.action)
543 self.cr.execute('select view_type,view_mode,name,view_id,target from ir_act_window where id=%s', (action_id,))
544 ir_act_window_result = self.cr.fetchone()
545 assert ir_act_window_result, "No window action defined for this id %s !\n" \
546 "Verify that this is a window action or add a type argument." % (node.action,)
547 action_type, action_mode, action_name, view_id, target = ir_act_window_result
549 self.cr.execute('SELECT type FROM ir_ui_view WHERE id=%s', (view_id,))
550 # TODO guess why action_mode is ir_act_window.view_mode above and ir_ui_view.type here
551 action_mode = self.cr.fetchone()
552 self.cr.execute('SELECT view_mode FROM ir_act_window_view WHERE act_window_id=%s ORDER BY sequence LIMIT 1', (action_id,))
554 action_mode = self.cr.fetchone()
555 if action_type == 'tree':
556 values['icon'] = 'STOCK_INDENT'
557 elif action_mode and action_mode.startswith('tree'):
558 values['icon'] = 'STOCK_JUSTIFY_FILL'
559 elif action_mode and action_mode.startswith('graph'):
560 values['icon'] = 'terp-graph'
561 elif action_mode and action_mode.startswith('calendar'):
562 values['icon'] = 'terp-calendar'
564 values['icon'] = 'STOCK_EXECUTE'
565 if not values.get('name', False):
566 values['name'] = action_name
567 elif action_type == 'wizard':
568 action_id = self.get_id(node.action)
569 self.cr.execute('select name from ir_act_wizard where id=%s', (action_id,))
570 ir_act_wizard_result = self.cr.fetchone()
571 if (not values.get('name', False)) and ir_act_wizard_result:
572 values['name'] = ir_act_wizard_result[0]
574 raise YamlImportException("Unsupported type '%s' in menuitem tag." % action_type)
576 values['sequence'] = node.sequence
578 values['icon'] = node.icon
580 self._set_group_values(node, values)
582 pid = self.pool.get('ir.model.data')._update(self.cr, 1, \
583 'ir.ui.menu', self.module, values, node.id, mode=self.mode, \
584 noupdate=self.isnoupdate(node), res_id=res and res[0] or False)
586 if node.id and parent_id:
587 self.id_map[node.id] = int(parent_id)
589 if node.action and pid:
590 action_type = node.type or 'act_window'
591 action_id = self.get_id(node.action)
592 action = "ir.actions.%s,%d" % (action_type, action_id)
593 self.pool.get('ir.model.data').ir_set(self.cr, 1, 'action', \
594 'tree_but_open', 'Menuitem', [('ir.ui.menu', int(parent_id))], action, True, True, xml_id=node.id)
596 def process_act_window(self, node):
597 assert getattr(node, 'id'), "Attribute %s of act_window is empty !" % ('id',)
598 assert getattr(node, 'name'), "Attribute %s of act_window is empty !" % ('name',)
599 assert getattr(node, 'res_model'), "Attribute %s of act_window is empty !" % ('res_model',)
600 self.validate_xml_id(node.id)
603 view_id = self.get_id(node.view)
606 context = eval(str(node.context), self.eval_context)
609 'type': node.type or 'ir.actions.act_window',
611 'domain': node.domain,
613 'res_model': node.res_model,
614 'src_model': node.src_model,
615 'view_type': node.view_type or 'form',
616 'view_mode': node.view_mode or 'tree,form',
619 'auto_refresh': node.auto_refresh,
620 'multi': getattr(node, 'multi', False),
623 self._set_group_values(node, values)
626 values['target'] = node.target
627 id = self.pool.get('ir.model.data')._update(self.cr, 1, \
628 'ir.actions.act_window', self.module, values, node.id, mode=self.mode)
629 self.id_map[node.id] = int(id)
632 keyword = 'client_action_relate'
633 value = 'ir.actions.act_window,%s' % id
634 replace = node.replace or True
635 self.pool.get('ir.model.data').ir_set(self.cr, 1, 'action', keyword, \
636 node.id, [node.src_model], value, replace=replace, noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
637 # TODO add remove ir.model.data
639 def process_delete(self, node):
640 assert getattr(node, 'model'), "Attribute %s of delete tag is empty !" % ('model',)
641 if self.pool.get(node.model):
643 ids = self.pool.get(node.model).search(self.cr, self.uid, eval(node.search, self.eval_context))
645 ids = [self.get_id(node.id)]
647 self.pool.get(node.model).unlink(self.cr, self.uid, ids)
649 self.logger.log(logging.TEST, "Record not deleted.")
651 def process_url(self, node):
652 self.validate_xml_id(node.id)
654 res = {'name': node.name, 'url': node.url, 'target': node.target}
656 id = self.pool.get('ir.model.data')._update(self.cr, 1, \
657 "ir.actions.url", self.module, res, node.id, mode=self.mode)
658 self.id_map[node.id] = int(id)
660 if (not node.menu or eval(node.menu)) and id:
661 keyword = node.keyword or 'client_action_multi'
662 value = 'ir.actions.url,%s' % id
663 replace = node.replace or True
664 self.pool.get('ir.model.data').ir_set(self.cr, 1, 'action', \
665 keyword, node.url, ["ir.actions.url"], value, replace=replace, \
666 noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
668 def process_ir_set(self, node):
669 if not self.mode == 'init':
671 _, fields = node.items()[0]
673 for fieldname, expression in fields.items():
674 if is_eval(expression):
675 value = eval(expression.expression, self.eval_context)
678 res[fieldname] = value
679 self.pool.get('ir.model.data').ir_set(self.cr, 1, res['key'], res['key2'], \
680 res['name'], res['models'], res['value'], replace=res.get('replace',True), \
681 isobject=res.get('isobject', False), meta=res.get('meta',None))
683 def process_report(self, node):
685 for dest, f in (('name','string'), ('model','model'), ('report_name','name')):
686 values[dest] = getattr(node, f)
687 assert values[dest], "Attribute %s of report is empty !" % (f,)
688 for field,dest in (('rml','report_rml'),('file','report_rml'),('xml','report_xml'),('xsl','report_xsl'),('attachment','attachment'),('attachment_use','attachment_use')):
689 if getattr(node, field):
690 values[dest] = getattr(node, field)
692 values['auto'] = eval(node.auto)
694 sxw_file = misc.file_open(node.sxw)
696 sxw_content = sxw_file.read()
697 values['report_sxw_content'] = sxw_content
701 values['header'] = eval(node.header)
702 values['multi'] = node.multi and eval(node.multi)
704 self.validate_xml_id(xml_id)
706 self._set_group_values(node, values)
708 id = self.pool.get('ir.model.data')._update(self.cr, 1, "ir.actions.report.xml", \
709 self.module, values, xml_id, noupdate=self.isnoupdate(node), mode=self.mode)
710 self.id_map[xml_id] = int(id)
712 if not node.menu or eval(node.menu):
713 keyword = node.keyword or 'client_print_multi'
714 value = 'ir.actions.report.xml,%s' % id
715 replace = node.replace or True
716 self.pool.get('ir.model.data').ir_set(self.cr, 1, 'action', \
717 keyword, values['name'], [values['model']], value, replace=replace, isobject=True, xml_id=xml_id)
719 def process_none(self):
721 Empty node or commented node should not pass silently.
723 self._log_assert_failure(logging.WARNING, "You have an empty block in your tests.")
726 def process(self, yaml_string):
728 Processes a Yaml string. Custom tags are interpreted by 'process_' instance methods.
730 yaml_tag.add_constructors()
732 is_preceded_by_comment = False
733 for node in yaml.load(yaml_string):
734 is_preceded_by_comment = self._log(node, is_preceded_by_comment)
736 self._process_node(node)
737 except YamlImportException, e:
738 self.logger.exception(e)
740 self.logger.exception(e)
743 def _process_node(self, node):
745 self.process_comment(node)
746 elif is_assert(node):
747 self.process_assert(node)
748 elif is_record(node):
749 self.process_record(node)
750 elif is_python(node):
751 self.process_python(node)
752 elif is_menuitem(node):
753 self.process_menuitem(node)
754 elif is_delete(node):
755 self.process_delete(node)
757 self.process_url(node)
758 elif is_context(node):
759 self.process_context(node)
760 elif is_ir_set(node):
761 self.process_ir_set(node)
762 elif is_act_window(node):
763 self.process_act_window(node)
764 elif is_report(node):
765 self.process_report(node)
766 elif is_workflow(node):
767 if isinstance(node, types.DictionaryType):
768 self.process_workflow(node)
770 self.process_workflow({node: []})
771 elif is_function(node):
772 if isinstance(node, types.DictionaryType):
773 self.process_function(node)
775 self.process_function({node: []})
779 raise YamlImportException("Can not process YAML block: %s" % node)
781 def _log(self, node, is_preceded_by_comment):
783 is_preceded_by_comment = True
784 self.logger.log(logging.TEST, node)
785 elif not is_preceded_by_comment:
786 if isinstance(node, types.DictionaryType):
787 msg = "Creating %s\n with %s"
788 args = node.items()[0]
789 self.logger.log(logging.TEST, msg, *args)
791 self.logger.log(logging.TEST, node)
793 is_preceded_by_comment = False
794 return is_preceded_by_comment
796 def yaml_import(cr, module, yamlfile, idref=None, mode='init', noupdate=False):
799 yaml_string = yamlfile.read()
800 yaml_interpreter = YamlInterpreter(cr, module, idref, mode, filename=yamlfile.name, noupdate=noupdate)
801 yaml_interpreter.process(yaml_string)
803 # keeps convention of convert.py
804 convert_yaml_import = yaml_import
806 def threaded_yaml_import(db_name, module_name, file_name, delay=0):
812 cr = sql_db.db_connect(db_name).cursor()
813 fp = misc.file_open(file_name)
814 convert_yaml_import(cr, module_name, fp, {}, 'update', True)
818 threading.Thread(target=f).start()
821 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: