1 # -*- encoding: utf-8 -*-
4 import time # used to eval time.strftime expressions
10 from config import config
12 logger_channel = 'tests'
14 class YamlImportException(Exception):
17 class YamlImportAbortion(Exception):
20 class YamlTag(object):
21 """Superclass for constructors of custom tags defined in yaml file."""
23 def __init__(self, **kwargs):
24 self.__dict__.update(kwargs)
25 def __getitem__(self, key):
26 return getattr(self, key)
27 def __getattr__(self, attr):
30 return "<%s %s>" % (self.__class__.__name__, sorted(self.__dict__.items()))
32 class Assert(YamlTag):
33 def __init__(self, model, id, severity=netsvc.LOG_ERROR, string="NONAME", **kwargs):
36 self.severity = severity
38 super(Assert, self).__init__(**kwargs)
40 class Record(YamlTag):
41 def __init__(self, model, id, **kwargs):
44 super(Record, self).__init__(**kwargs)
46 class Python(YamlTag):
47 def __init__(self, model, severity=netsvc.LOG_ERROR, name="NONAME", **kwargs):
49 self.severity = severity
51 super(Python, self).__init__(**kwargs)
53 class Workflow(YamlTag):
54 def __init__(self, model, action, **kwargs):
57 super(Workflow, self).__init__(**kwargs)
59 class Context(YamlTag):
60 def __init__(self, **kwargs):
61 super(Context, self).__init__(**kwargs)
64 def __init__(self, expression):
65 self.expression = expression
66 super(Eval, self).__init__()
69 def __init__(self, xmlid):
71 super(Ref, self).__init__()
73 def assert_constructor(loader, node):
74 kwargs = loader.construct_mapping(node)
75 return Assert(**kwargs)
77 def record_constructor(loader, node):
78 kwargs = loader.construct_mapping(node)
79 return Record(**kwargs)
81 def python_constructor(loader, node):
82 kwargs = loader.construct_mapping(node)
83 return Python(**kwargs)
85 def workflow_constructor(loader, node):
86 kwargs = loader.construct_mapping(node)
87 return Workflow(**kwargs)
89 def context_constructor(loader, node):
90 kwargs = loader.construct_mapping(node)
91 return Context(**kwargs)
93 def eval_constructor(loader, node):
94 expression = loader.construct_scalar(node)
95 return Eval(expression)
97 def ref_constructor(loader, node):
98 xmlid = loader.construct_scalar(node)
101 yaml.add_constructor(u"!assert", assert_constructor)
102 yaml.add_constructor(u"!record", record_constructor)
103 yaml.add_constructor(u"!python", python_constructor)
104 yaml.add_constructor(u"!workflow", workflow_constructor)
105 yaml.add_constructor(u"!context", context_constructor)
106 yaml.add_constructor(u"!eval", eval_constructor)
107 yaml.add_constructor(u"!ref", ref_constructor)
109 def _is_yaml_mapping(node, tag_constructor):
110 value = isinstance(node, types.DictionaryType) \
111 and len(node.keys()) == 1 \
112 and isinstance(node.keys()[0], tag_constructor)
115 def is_comment(node):
116 return isinstance(node, types.StringTypes)
119 return _is_yaml_mapping(node, Assert)
122 return _is_yaml_mapping(node, Record)
125 return _is_yaml_mapping(node, Python)
127 def is_workflow(node):
128 return isinstance(node, Workflow) \
129 or _is_yaml_mapping(node, Workflow)
131 def is_context(node):
132 return isinstance(node, Context)
135 return isinstance(node, Eval)
138 return isinstance(node, Ref)
141 class TestReport(object):
145 def record(self, success, severity):
146 """Records the result of an assertion for the failed/success count.
149 if severity in self._report:
150 self._report[severity][success] += 1
152 self._report[severity] = {success: 1, not success: 0}
157 res.append('\nAssertions report:\nLevel\tsuccess\tfailed')
158 success = failure = 0
159 for severity in self._report:
160 res.append("%s\t%s\t%s" % (severity, self._report[severity][True], self._report[severity][False]))
161 success += self._report[severity][True]
162 failure += self._report[severity][False]
163 res.append("total\t%s\t%s" % (success, failure))
164 res.append("end of report (%s assertion(s) checked)" % success + failure)
165 return "\n".join(res)
168 class YamlInterpreter(object):
169 def __init__(self, cr, module, id_map, mode, filename, noupdate=False):
174 self.filename = filename
175 self.assert_report = TestReport()
176 self.noupdate = noupdate
177 self.logger = netsvc.Logger()
178 self.pool = pooler.get_pool(cr.dbname)
183 return lambda xml_id: self.get_id(xml_id)
185 def get_model(self, model_name):
186 model = self.pool.get(model_name)
187 assert model, "The model %s does not exist." % (model_name,)
190 def validate_xml_id(self, xml_id):
193 module, id = xml_id.split('.', 1)
194 assert '.' not in id, "The ID reference '%s' must contains maximum one dot.\n" \
195 "It is used to refer to other modules ID, in the form: module.record_id" \
197 if module != self.module:
198 module_count = self.pool.get('ir.module.module').search_count(self.cr, self.uid, \
199 ['&', ('name', '=', module), ('state', 'in', ['installed'])])
200 assert module_count == 1, """The ID "%s" refers to an uninstalled module""" % (xml_id,)
201 if len(id) > 64: # TODO where does 64 come from (DB is 128)? should be a constant or loaded form DB
202 self.logger.notifyChannel(logger_channel, netsvc.LOG_ERROR, 'id: %s is to long (max: 64)' % (id,))
204 def get_id(self, xml_id):
205 if isinstance(xml_id, types.IntType):
207 elif xml_id in self.id_map:
208 id = self.id_map[xml_id]
211 module, xml_id = xml_id.split('.', 1)
214 ir_id = self.pool.get('ir.model.data')._get_id(self.cr, self.uid, module, xml_id)
215 obj = self.pool.get('ir.model.data').read(self.cr, self.uid, ir_id, ['res_id'])
216 id = int(obj['res_id'])
217 self.id_map[xml_id] = id
220 def process_comment(self, node):
223 def _log_assert_failure(self, severity, msg, *args):
224 self.assert_report.record(False, severity)
225 self.logger.notifyChannel(logger_channel, severity, msg % (args))
226 if getattr(logging, severity.upper()) >= config['assert_exit_level']:
227 raise YamlImportAbortion('Severe assertion failure (%s), aborting.' % (severity,))
230 def _get_assertion_id(self, assertion):
232 ids = [self.get_id(assertion.id)]
233 elif assertion.search:
234 q = eval(assertion.search, {'ref': self._ref})
235 ids = self.pool.get(assertion.model).search(self.cr, self.uid, q, context=assertion.context)
237 raise YamlImportException('Nothing to assert: you must give either an id or a search criteria.')
240 def process_assert(self, node):
241 assertion, expressions = node.items()[0]
243 model = self.get_model(assertion.model)
244 ids = self._get_assertion_id(assertion)
245 if assertion.count and len(ids) != assertion.count:
246 msg = 'assertion "%s" failed!\n' \
247 ' Incorrect search count:\n' \
248 ' expected count: %d\n' \
249 ' obtained count: %d\n'
250 args = (assertion.string, assertion.count, len(ids))
251 self._log_assert_failure(assertion.severity, msg, *args)
253 test_context = {'ref': self._ref, '_ref': self._ref} # added '_ref' so that record['ref'] is possible
255 record = model.browse(self.cr, self.uid, id, assertion.context)
256 for test in expressions.get('test', ''):
257 success = eval(test, test_context, record)
259 msg = 'Assertion "%s" FAILED\ntest: %s\n'
260 args = (assertion.string, test)
261 self._log_assert_failure(assertion.severity, msg, *args)
263 else: # all tests were successful for this assertion tag (no break)
264 self.assert_report.record(True, assertion.severity)
266 def process_record(self, node):
267 record, fields = node.items()[0]
269 self.validate_xml_id(record.id)
270 model = self.get_model(record.model)
271 record_dict = self._create_record(model, fields)
272 id = self.pool.get('ir.model.data')._update(self.cr, self.uid, record.model, \
273 self.module, record_dict, record.id, mode=self.mode)
274 self.id_map[record.id] = int(id)
275 if config.get('import_partial', False):
278 def _create_record(self, model, fields):
280 for field_name, expression in fields.items():
281 field_value = self._eval_field(model, field_name, expression)
282 record_dict[field_name] = field_value
285 def _eval_field(self, model, field_name, expression):
286 column = model._columns[field_name]
287 if column._type == "many2one":
288 value = self.get_id(expression)
289 elif column._type == "one2many":
290 other_model = self.get_model(column._obj)
291 value = [(0, 0, self._create_record(other_model, fields)) for fields in expression]
292 elif column._type == "many2many":
293 ids = [self.get_id(xml_id) for xml_id in expression]
296 if isinstance(expression, Eval):
297 value = eval(expression.expression)
300 # raise YamlImportException('Unsupported column "%s" or value %s:%s' % (field_name, type(expression), expression))
303 def process_context(self, node):
304 self.context = node.__dict__
305 if 'uid' in node.__dict__:
306 self.uid = self.get_id(node.__dict__['uid'])
308 def process_python(self, node):
310 self.logger.notifyChannel(logger_channel, netsvc.LOG_TEST, msg)
311 python, statements = node.items()[0]
312 model = self.get_model(python.model)
313 statements = statements.replace("\r\n", "\n").replace("\n", ";")
314 code_context = {'self': model, 'cr': self.cr, 'uid': self.uid, 'log': log, 'context': self.context}
316 code = compile(statements, self.filename, 'exec')
317 eval(code, code_context)
318 except AssertionError, e:
319 msg = 'Assertion "%s" FAILED in Python code.'
320 args = (python.name,)
321 self._log_assert_failure(python.severity, msg, *args)
324 raise YamlImportAbortion(e)
326 self.assert_report.record(True, python.severity)
328 def process_workflow(self, node):
329 workflow, values = node.items()[0]
330 model = self.get_model(workflow.model)
332 id = self.get_id(workflow.ref)
335 raise YamlImportException('You must define a child node if you do not give a ref.')
336 if not len(values) == 1:
337 raise YamlImportException('Only one child node is accepted (%d given).' % len(values))
339 if not 'model' in value and not 'eval' in value:
340 raise YamlImportException('You must provide a model and an expression to evaluate for the workflow.')
341 value_model = self.get_model(value['model'])
342 local_context = {'ref': self._ref, '_ref': self._ref}
343 local_context['obj'] = lambda x: value_model.browse(self.cr, self.uid, x, context=self.context)
344 local_context.update(self.id_map)
345 id = eval(value['eval'], local_context)
347 if workflow.uid is not None:
351 wf_service = netsvc.LocalService("workflow")
352 wf_service.trg_validate(uid, model, id, workflow.action, self.cr)
354 def process(self, yaml_string):
355 """Processes a Yaml string. Custom tags are interpreted by 'process_' instance methods."""
357 is_preceded_by_comment = False
358 for node in yaml.load(yaml_string):
359 is_preceded_by_comment = self._log(node, is_preceded_by_comment)
361 self._process_node(node)
362 except YamlImportException, e:
363 self.logger.notifyChannel(logger_channel, netsvc.LOG_ERROR, e)
364 except YamlImportAbortion, e:
365 self.logger.notifyChannel(logger_channel, netsvc.LOG_ERROR, e)
368 def _process_node(self, node):
370 self.process_comment(node)
371 elif is_assert(node):
372 self.process_assert(node)
373 elif is_record(node):
374 self.process_record(node)
375 elif is_python(node):
376 self.process_python(node)
377 elif is_context(node):
378 self.process_context(node)
379 elif is_workflow(node):
380 if isinstance(node, types.DictionaryType):
381 self.process_workflow(node)
383 self.process_workflow({node: []})
385 raise YamlImportException("Can not process YAML block: %s" % node)
387 def _log(self, node, is_preceded_by_comment):
389 is_preceded_by_comment = True
390 self.logger.notifyChannel(logger_channel, netsvc.LOG_TEST, node)
391 elif not is_preceded_by_comment:
392 if isinstance(node, types.DictionaryType):
393 k, v = node.items()[0]
394 msg = "Creating %s\n with %s" % (k, v)
395 self.logger.notifyChannel(logger_channel, netsvc.LOG_TEST, msg)
397 self.logger.notifyChannel(logger_channel, netsvc.LOG_TEST, node)
399 is_preceded_by_comment = False
400 return is_preceded_by_comment
402 def yaml_import(cr, module, yamlfile, idref=None, mode='init', noupdate=False, report=None):
405 yaml_string = yamlfile.read()
406 yaml_interpreter = YamlInterpreter(cr, module, idref, mode, filename=yamlfile.name, noupdate=noupdate)
407 yaml_interpreter.process(yaml_string)
409 # keeps convention of convert.py
410 convert_yaml_import = yaml_import
412 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: