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 model.is_transient():
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):
343 assert node.search or node.id, '!ref node should have a `search` attribute or `id` attribute'
346 model_name = node.model
348 model_name = column._obj
350 raise YamlImportException('You need to give a model for the search, or a column to infer it.')
351 model = self.get_model(model_name)
352 q = eval(node.search, self.eval_context)
353 ids = model.search(self.cr, self.uid, q)
355 instances = model.browse(self.cr, self.uid, ids)
356 value = [inst[node.use] for inst in instances]
360 value = self.get_id(node.id)
365 def process_eval(self, node):
366 return eval(node.expression, self.eval_context)
368 def _eval_field(self, model, field_name, expression):
369 # TODO this should be refactored as something like model.get_field() in bin/osv
370 if field_name in model._columns:
371 column = model._columns[field_name]
372 elif field_name in model._inherit_fields:
373 column = model._inherit_fields[field_name][2]
375 raise KeyError("Object '%s' does not contain field '%s'" % (model, field_name))
376 if is_ref(expression):
377 elements = self.process_ref(expression, column)
378 if column._type in ("many2many", "one2many"):
379 value = [(6, 0, elements)]
381 if isinstance(elements, (list,tuple)):
382 value = self._get_first_result(elements)
385 elif column._type == "many2one":
386 value = self.get_id(expression)
387 elif column._type == "one2many":
388 other_model = self.get_model(column._obj)
389 value = [(0, 0, self._create_record(other_model, fields)) for fields in expression]
390 elif column._type == "many2many":
391 ids = [self.get_id(xml_id) for xml_id in expression]
392 value = [(6, 0, ids)]
393 elif column._type == "date" and is_string(expression):
394 # enforce ISO format for string date values, to be locale-agnostic during tests
395 time.strptime(expression, misc.DEFAULT_SERVER_DATE_FORMAT)
397 elif column._type == "datetime" and is_string(expression):
398 # enforce ISO format for string datetime values, to be locale-agnostic during tests
399 time.strptime(expression, misc.DEFAULT_SERVER_DATETIME_FORMAT)
402 if is_eval(expression):
403 value = self.process_eval(expression)
406 # raise YamlImportException('Unsupported column "%s" or value %s:%s' % (field_name, type(expression), expression))
409 def process_context(self, node):
410 self.context = node.__dict__
412 self.uid = self.get_id(node.uid)
414 self.noupdate = node.noupdate
416 def process_python(self, node):
418 self.logger.log(logging.TEST, msg, *args)
419 python, statements = node.items()[0]
420 model = self.get_model(python.model)
421 statements = statements.replace("\r\n", "\n")
422 code_context = {'model': model, 'cr': self.cr, 'uid': self.uid, 'log': log, 'context': self.context}
423 code_context.update({'self': model}) # remove me when no !python block test uses 'self' anymore
425 code_obj = compile(statements, self.filename, 'exec')
426 unsafe_eval(code_obj, {'ref': self.get_id}, code_context)
427 except AssertionError, e:
428 self._log_assert_failure(python.severity, 'AssertionError in Python code %s: %s', python.name, e)
431 self.logger.debug('Exception during evaluation of !python block in yaml_file %s.', self.filename, exc_info=True)
434 self.assert_report.record(True, python.severity)
436 def process_workflow(self, node):
437 workflow, values = node.items()[0]
438 if self.isnoupdate(workflow) and self.mode != 'init':
441 id = self.get_id(workflow.ref)
444 raise YamlImportException('You must define a child node if you do not give a ref.')
445 if not len(values) == 1:
446 raise YamlImportException('Only one child node is accepted (%d given).' % len(values))
448 if not 'model' in value and (not 'eval' in value or not 'search' in value):
449 raise YamlImportException('You must provide a "model" and an "eval" or "search" to evaluate.')
450 value_model = self.get_model(value['model'])
451 local_context = {'obj': lambda x: value_model.browse(self.cr, self.uid, x, context=self.context)}
452 local_context.update(self.id_map)
453 id = eval(value['eval'], self.eval_context, local_context)
455 if workflow.uid is not None:
459 self.cr.execute('select distinct signal from wkf_transition')
460 signals=[x['signal'] for x in self.cr.dictfetchall()]
461 if workflow.action not in signals:
462 raise YamlImportException('Incorrect action %s. No such action defined' % workflow.action)
463 import openerp.netsvc as netsvc
464 wf_service = netsvc.LocalService("workflow")
465 wf_service.trg_validate(uid, workflow.model, id, workflow.action, self.cr)
467 def _eval_params(self, model, params):
469 for i, param in enumerate(params):
470 if isinstance(param, types.ListType):
471 value = self._eval_params(model, param)
473 value = self.process_ref(param)
475 value = self.process_eval(param)
476 elif isinstance(param, types.DictionaryType): # supports XML syntax
477 param_model = self.get_model(param.get('model', model))
478 if 'search' in param:
479 q = eval(param['search'], self.eval_context)
480 ids = param_model.search(self.cr, self.uid, q)
481 value = self._get_first_result(ids)
482 elif 'eval' in param:
483 local_context = {'obj': lambda x: param_model.browse(self.cr, self.uid, x, self.context)}
484 local_context.update(self.id_map)
485 value = eval(param['eval'], self.eval_context, local_context)
487 raise YamlImportException('You must provide either a !ref or at least a "eval" or a "search" to function parameter #%d.' % i)
489 value = param # scalar value
493 def process_function(self, node):
494 function, params = node.items()[0]
495 if self.isnoupdate(function) and self.mode != 'init':
497 model = self.get_model(function.model)
499 args = self.process_eval(function.eval)
501 args = self._eval_params(function.model, params)
502 method = function.name
503 getattr(model, method)(self.cr, self.uid, *args)
505 def _set_group_values(self, node, values):
507 group_names = node.groups.split(',')
509 for group in group_names:
510 if group.startswith('-'):
511 group_id = self.get_id(group[1:])
512 groups_value.append((3, group_id))
514 group_id = self.get_id(group)
515 groups_value.append((4, group_id))
516 values['groups_id'] = groups_value
518 def process_menuitem(self, node):
519 self.validate_xml_id(node.id)
523 self.cr.execute('select id from ir_ui_menu where parent_id is null and name=%s', (node.name,))
524 res = self.cr.fetchone()
525 values = {'parent_id': parent_id, 'name': node.name}
527 parent_id = self.get_id(node.parent)
528 values = {'parent_id': parent_id}
530 values['name'] = node.name
532 res = [ self.get_id(node.id) ]
533 except: # which exception ?
537 action_type = node.type or 'act_window'
539 "act_window": 'STOCK_NEW',
540 "report.xml": 'STOCK_PASTE',
541 "wizard": 'STOCK_EXECUTE',
542 "url": 'STOCK_JUMP_TO',
544 values['icon'] = icons.get(action_type, 'STOCK_NEW')
545 if action_type == 'act_window':
546 action_id = self.get_id(node.action)
547 self.cr.execute('select view_type,view_mode,name,view_id,target from ir_act_window where id=%s', (action_id,))
548 ir_act_window_result = self.cr.fetchone()
549 assert ir_act_window_result, "No window action defined for this id %s !\n" \
550 "Verify that this is a window action or add a type argument." % (node.action,)
551 action_type, action_mode, action_name, view_id, target = ir_act_window_result
553 self.cr.execute('SELECT type FROM ir_ui_view WHERE id=%s', (view_id,))
554 # TODO guess why action_mode is ir_act_window.view_mode above and ir_ui_view.type here
555 action_mode = self.cr.fetchone()
556 self.cr.execute('SELECT view_mode FROM ir_act_window_view WHERE act_window_id=%s ORDER BY sequence LIMIT 1', (action_id,))
558 action_mode = self.cr.fetchone()
559 if action_type == 'tree':
560 values['icon'] = 'STOCK_INDENT'
561 elif action_mode and action_mode.startswith('tree'):
562 values['icon'] = 'STOCK_JUSTIFY_FILL'
563 elif action_mode and action_mode.startswith('graph'):
564 values['icon'] = 'terp-graph'
565 elif action_mode and action_mode.startswith('calendar'):
566 values['icon'] = 'terp-calendar'
568 values['icon'] = 'STOCK_EXECUTE'
569 if not values.get('name', False):
570 values['name'] = action_name
571 elif action_type == 'wizard':
572 action_id = self.get_id(node.action)
573 self.cr.execute('select name from ir_act_wizard where id=%s', (action_id,))
574 ir_act_wizard_result = self.cr.fetchone()
575 if (not values.get('name', False)) and ir_act_wizard_result:
576 values['name'] = ir_act_wizard_result[0]
578 raise YamlImportException("Unsupported type '%s' in menuitem tag." % action_type)
580 values['sequence'] = node.sequence
582 values['icon'] = node.icon
584 self._set_group_values(node, values)
586 pid = self.pool.get('ir.model.data')._update(self.cr, 1, \
587 'ir.ui.menu', self.module, values, node.id, mode=self.mode, \
588 noupdate=self.isnoupdate(node), res_id=res and res[0] or False)
590 if node.id and parent_id:
591 self.id_map[node.id] = int(parent_id)
593 if node.action and pid:
594 action_type = node.type or 'act_window'
595 action_id = self.get_id(node.action)
596 action = "ir.actions.%s,%d" % (action_type, action_id)
597 self.pool.get('ir.model.data').ir_set(self.cr, 1, 'action', \
598 'tree_but_open', 'Menuitem', [('ir.ui.menu', int(parent_id))], action, True, True, xml_id=node.id)
600 def process_act_window(self, node):
601 assert getattr(node, 'id'), "Attribute %s of act_window is empty !" % ('id',)
602 assert getattr(node, 'name'), "Attribute %s of act_window is empty !" % ('name',)
603 assert getattr(node, 'res_model'), "Attribute %s of act_window is empty !" % ('res_model',)
604 self.validate_xml_id(node.id)
607 view_id = self.get_id(node.view)
610 context = eval(str(node.context), self.eval_context)
613 'type': node.type or 'ir.actions.act_window',
615 'domain': node.domain,
617 'res_model': node.res_model,
618 'src_model': node.src_model,
619 'view_type': node.view_type or 'form',
620 'view_mode': node.view_mode or 'tree,form',
623 'auto_refresh': node.auto_refresh,
624 'multi': getattr(node, 'multi', False),
627 self._set_group_values(node, values)
630 values['target'] = node.target
631 id = self.pool.get('ir.model.data')._update(self.cr, 1, \
632 'ir.actions.act_window', self.module, values, node.id, mode=self.mode)
633 self.id_map[node.id] = int(id)
636 keyword = 'client_action_relate'
637 value = 'ir.actions.act_window,%s' % id
638 replace = node.replace or True
639 self.pool.get('ir.model.data').ir_set(self.cr, 1, 'action', keyword, \
640 node.id, [node.src_model], value, replace=replace, noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
641 # TODO add remove ir.model.data
643 def process_delete(self, node):
644 assert getattr(node, 'model'), "Attribute %s of delete tag is empty !" % ('model',)
645 if self.pool.get(node.model):
647 ids = self.pool.get(node.model).search(self.cr, self.uid, eval(node.search, self.eval_context))
649 ids = [self.get_id(node.id)]
651 self.pool.get(node.model).unlink(self.cr, self.uid, ids)
653 self.logger.log(logging.TEST, "Record not deleted.")
655 def process_url(self, node):
656 self.validate_xml_id(node.id)
658 res = {'name': node.name, 'url': node.url, 'target': node.target}
660 id = self.pool.get('ir.model.data')._update(self.cr, 1, \
661 "ir.actions.url", self.module, res, node.id, mode=self.mode)
662 self.id_map[node.id] = int(id)
664 if (not node.menu or eval(node.menu)) and id:
665 keyword = node.keyword or 'client_action_multi'
666 value = 'ir.actions.url,%s' % id
667 replace = node.replace or True
668 self.pool.get('ir.model.data').ir_set(self.cr, 1, 'action', \
669 keyword, node.url, ["ir.actions.url"], value, replace=replace, \
670 noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
672 def process_ir_set(self, node):
673 if not self.mode == 'init':
675 _, fields = node.items()[0]
677 for fieldname, expression in fields.items():
678 if is_eval(expression):
679 value = eval(expression.expression, self.eval_context)
682 res[fieldname] = value
683 self.pool.get('ir.model.data').ir_set(self.cr, 1, res['key'], res['key2'], \
684 res['name'], res['models'], res['value'], replace=res.get('replace',True), \
685 isobject=res.get('isobject', False), meta=res.get('meta',None))
687 def process_report(self, node):
689 for dest, f in (('name','string'), ('model','model'), ('report_name','name')):
690 values[dest] = getattr(node, f)
691 assert values[dest], "Attribute %s of report is empty !" % (f,)
692 for field,dest in (('rml','report_rml'),('file','report_rml'),('xml','report_xml'),('xsl','report_xsl'),('attachment','attachment'),('attachment_use','attachment_use')):
693 if getattr(node, field):
694 values[dest] = getattr(node, field)
696 values['auto'] = eval(node.auto)
698 sxw_file = misc.file_open(node.sxw)
700 sxw_content = sxw_file.read()
701 values['report_sxw_content'] = sxw_content
705 values['header'] = eval(node.header)
706 values['multi'] = node.multi and eval(node.multi)
708 self.validate_xml_id(xml_id)
710 self._set_group_values(node, values)
712 id = self.pool.get('ir.model.data')._update(self.cr, 1, "ir.actions.report.xml", \
713 self.module, values, xml_id, noupdate=self.isnoupdate(node), mode=self.mode)
714 self.id_map[xml_id] = int(id)
716 if not node.menu or eval(node.menu):
717 keyword = node.keyword or 'client_print_multi'
718 value = 'ir.actions.report.xml,%s' % id
719 replace = node.replace or True
720 self.pool.get('ir.model.data').ir_set(self.cr, 1, 'action', \
721 keyword, values['name'], [values['model']], value, replace=replace, isobject=True, xml_id=xml_id)
723 def process_none(self):
725 Empty node or commented node should not pass silently.
727 self._log_assert_failure(logging.WARNING, "You have an empty block in your tests.")
730 def process(self, yaml_string):
732 Processes a Yaml string. Custom tags are interpreted by 'process_' instance methods.
734 yaml_tag.add_constructors()
736 is_preceded_by_comment = False
737 for node in yaml.load(yaml_string):
738 is_preceded_by_comment = self._log(node, is_preceded_by_comment)
740 self._process_node(node)
741 except YamlImportException, e:
742 self.logger.exception(e)
744 self.logger.exception(e)
747 def _process_node(self, node):
749 self.process_comment(node)
750 elif is_assert(node):
751 self.process_assert(node)
752 elif is_record(node):
753 self.process_record(node)
754 elif is_python(node):
755 self.process_python(node)
756 elif is_menuitem(node):
757 self.process_menuitem(node)
758 elif is_delete(node):
759 self.process_delete(node)
761 self.process_url(node)
762 elif is_context(node):
763 self.process_context(node)
764 elif is_ir_set(node):
765 self.process_ir_set(node)
766 elif is_act_window(node):
767 self.process_act_window(node)
768 elif is_report(node):
769 self.process_report(node)
770 elif is_workflow(node):
771 if isinstance(node, types.DictionaryType):
772 self.process_workflow(node)
774 self.process_workflow({node: []})
775 elif is_function(node):
776 if isinstance(node, types.DictionaryType):
777 self.process_function(node)
779 self.process_function({node: []})
783 raise YamlImportException("Can not process YAML block: %s" % node)
785 def _log(self, node, is_preceded_by_comment):
787 is_preceded_by_comment = True
788 self.logger.log(logging.TEST, node)
789 elif not is_preceded_by_comment:
790 if isinstance(node, types.DictionaryType):
791 msg = "Creating %s\n with %s"
792 args = node.items()[0]
793 self.logger.log(logging.TEST, msg, *args)
795 self.logger.log(logging.TEST, node)
797 is_preceded_by_comment = False
798 return is_preceded_by_comment
800 def yaml_import(cr, module, yamlfile, idref=None, mode='init', noupdate=False):
803 yaml_string = yamlfile.read()
804 yaml_interpreter = YamlInterpreter(cr, module, idref, mode, filename=yamlfile.name, noupdate=noupdate)
805 yaml_interpreter.process(yaml_string)
807 # keeps convention of convert.py
808 convert_yaml_import = yaml_import
810 def threaded_yaml_import(db_name, module_name, file_name, delay=0):
816 cr = sql_db.db_connect(db_name).cursor()
817 fp = misc.file_open(file_name)
818 convert_yaml_import(cr, module_name, fp, {}, 'update', True)
822 threading.Thread(target=f).start()
825 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: