# -*- encoding: utf-8 -*-
import types
import time # used to eval time.strftime expressions
+from datetime import datetime, timedelta
import logging
import pooler
import misc
from config import config
import yaml_tag
-
import yaml
+# YAML import needs both safe and unsafe eval, but let's
+# default to /safe/.
+unsafe_eval = eval
+from tools.safe_eval import safe_eval as eval
+
logger_channel = 'tests'
class YamlImportException(Exception):
return isinstance(node, types.StringTypes)
def is_assert(node):
- return _is_yaml_mapping(node, yaml_tag.Assert)
+ return isinstance(node, yaml_tag.Assert) \
+ or _is_yaml_mapping(node, yaml_tag.Assert)
def is_record(node):
return _is_yaml_mapping(node, yaml_tag.Record)
def is_eval(node):
return isinstance(node, yaml_tag.Eval)
-
+
def is_ref(node):
return isinstance(node, yaml_tag.Ref) \
or _is_yaml_mapping(node, yaml_tag.Ref)
-
+
def is_ir_set(node):
return _is_yaml_mapping(node, yaml_tag.IrSet)
+def is_string(node):
+ return isinstance(node, basestring)
class TestReport(object):
def __init__(self):
if key in self.record:
return self.record[key]
return dict.__getitem__(self, key)
-
+
class YamlInterpreter(object):
def __init__(self, cr, module, id_map, mode, filename, noupdate=False):
self.cr = cr
self.pool = pooler.get_pool(cr.dbname)
self.uid = 1
self.context = {} # opererp context
- self.eval_context = {'ref': self._ref(), '_ref': self._ref(), 'time': time} # added '_ref' so that record['ref'] is possible
+ self.eval_context = {'ref': self._ref(),
+ '_ref': self._ref(), # added '_ref' so that record['ref'] is possible
+ 'time': time,
+ 'datetime': datetime,
+ 'timedelta': timedelta}
def _ref(self):
return lambda xml_id: self.get_id(xml_id)
model = self.pool.get(model_name)
assert model, "The model %s does not exist." % (model_name,)
return model
-
+
def validate_xml_id(self, xml_id):
id = xml_id
if '.' in xml_id:
else:
module = self.module
checked_xml_id = xml_id
- ir_id = self.pool.get('ir.model.data')._get_id(self.cr, self.uid, module, checked_xml_id)
- obj = self.pool.get('ir.model.data').read(self.cr, self.uid, ir_id, ['res_id'])
- id = int(obj['res_id'])
+ _, id = self.pool.get('ir.model.data').get_object_reference(self.cr, self.uid, module, checked_xml_id)
self.id_map[xml_id] = id
return id
elif assertion.search:
q = eval(assertion.search, self.eval_context)
ids = self.pool.get(assertion.model).search(self.cr, self.uid, q, context=assertion.context)
- if not ids:
+ else:
raise YamlImportException('Nothing to assert: you must give either an id or a search criteria.')
return ids
def process_assert(self, node):
- assertion, expressions = node.items()[0]
+ if isinstance(node, dict):
+ assertion, expressions = node.items()[0]
+ else:
+ assertion, expressions = node, []
if self.isnoupdate(assertion) and self.mode != 'init':
self.logger.warn('This assertion was not evaluated ("%s").' % assertion.string)
return
model = self.get_model(assertion.model)
ids = self._get_assertion_id(assertion)
- if assertion.count and len(ids) != assertion.count:
+ if assertion.count is not None and len(ids) != assertion.count:
msg = 'assertion "%s" failed!\n' \
' Incorrect search count:\n' \
' expected count: %d\n' \
record = model.browse(self.cr, self.uid, id, context)
for test in expressions:
try:
- success = eval(test, self.eval_context, RecordDictWrapper(record))
+ success = unsafe_eval(test, self.eval_context, RecordDictWrapper(record))
except Exception, e:
+ self.logger.debug('Exception during evaluation of !assert block in yaml_file %s.', self.filename, exc_info=True)
raise YamlImportAbortion(e)
if not success:
msg = 'Assertion "%s" FAILED\ntest: %s\n'
args = (assertion.string, test)
+ for aop in ('==', '!=', '<>', 'in', 'not in', '>=', '<=', '>', '<'):
+ if aop in test:
+ left, right = test.split(aop,1)
+ lmsg = ''
+ rmsg = ''
+ try:
+ lmsg = unsafe_eval(left, self.eval_context, RecordDictWrapper(record))
+ except Exception, e:
+ lmsg = '<exc>'
+
+ try:
+ rmsg = unsafe_eval(right, self.eval_context, RecordDictWrapper(record))
+ except Exception, e:
+ rmsg = '<exc>'
+
+ msg += 'values: ! %s %s %s'
+ args += ( lmsg, aop, rmsg )
+ break
+
self._log_assert_failure(assertion.severity, msg, *args)
return
else: # all tests were successful for this assertion tag (no break)
else:
self.validate_xml_id(record.id)
if self.isnoupdate(record) and self.mode != 'init':
- id = self.pool.get('ir.model.data')._update_dummy(self.cr, self.uid, record.model, self.module, record.id)
+ id = self.pool.get('ir.model.data')._update_dummy(self.cr, 1, record.model, self.module, record.id)
# check if the resource already existed at the last update
if id:
self.id_map[record] = int(id)
record_dict = self._create_record(model, fields)
self.logger.debug("RECORD_DICT %s" % record_dict)
- id = self.pool.get('ir.model.data')._update(self.cr, self.uid, record.model, \
- self.module, record_dict, record.id, noupdate=self.isnoupdate(record), mode=self.mode)
+ #context = self.get_context(record, self.eval_context)
+ context = record.context #TOFIX: record.context like {'withoutemployee':True} should pass from self.eval_context. example: test_project.yml in project module
+ id = self.pool.get('ir.model.data')._update(self.cr, 1, record.model, \
+ self.module, record_dict, record.id, noupdate=self.isnoupdate(record), mode=self.mode, context=context)
self.id_map[record.id] = int(id)
if config.get('import_partial'):
self.cr.commit()
else:
raise KeyError("Object '%s' does not contain field '%s'" % (model, field_name))
if is_ref(expression):
- elements = self.process_ref(expression)
+ elements = self.process_ref(expression, column)
if column._type in ("many2many", "one2many"):
value = [(6, 0, elements)]
else: # many2one
elif column._type == "many2many":
ids = [self.get_id(xml_id) for xml_id in expression]
value = [(6, 0, ids)]
+ elif column._type == "date" and is_string(expression):
+ # enforce ISO format for string date values, to be locale-agnostic during tests
+ time.strptime(expression, misc.DEFAULT_SERVER_DATE_FORMAT)
+ value = expression
+ elif column._type == "datetime" and is_string(expression):
+ # enforce ISO format for string datetime values, to be locale-agnostic during tests
+ time.strptime(expression, misc.DEFAULT_SERVER_DATETIME_FORMAT)
+ value = expression
else: # scalar field
if is_eval(expression):
value = self.process_eval(expression)
value = expression
# raise YamlImportException('Unsupported column "%s" or value %s:%s' % (field_name, type(expression), expression))
return value
-
+
def process_context(self, node):
self.context = node.__dict__
if node.uid:
self.uid = self.get_id(node.uid)
if node.noupdate:
self.noupdate = node.noupdate
-
+
def process_python(self, node):
def log(msg, *args):
self.logger.log(logging.TEST, msg, *args)
code_context = {'model': model, 'cr': self.cr, 'uid': self.uid, 'log': log, 'context': self.context}
code_context.update({'self': model}) # remove me when no !python block test uses 'self' anymore
try:
- code = compile(statements, self.filename, 'exec')
- eval(code, {'ref': self.get_id}, code_context)
+ code_obj = compile(statements, self.filename, 'exec')
+ unsafe_eval(code_obj, {'ref': self.get_id}, code_context)
except AssertionError, e:
self._log_assert_failure(python.severity, 'AssertionError in Python code %s: %s', python.name, e)
return
except Exception, e:
- raise YamlImportAbortion(e)
+ self.logger.debug('Exception during evaluation of !python block in yaml_file %s.', self.filename, exc_info=True)
+ raise
else:
self.assert_report.record(True, python.severity)
self._set_group_values(node, values)
- pid = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
+ pid = self.pool.get('ir.model.data')._update(self.cr, 1, \
'ir.ui.menu', self.module, values, node.id, mode=self.mode, \
noupdate=self.isnoupdate(node), res_id=res and res[0] or False)
action_type = node.type or 'act_window'
action_id = self.get_id(node.action)
action = "ir.actions.%s,%d" % (action_type, action_id)
- self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
+ self.pool.get('ir.model.data').ir_set(self.cr, 1, 'action', \
'tree_but_open', 'Menuitem', [('ir.ui.menu', int(parent_id))], action, True, True, xml_id=node.id)
def process_act_window(self, node):
'usage': node.usage,
'limit': node.limit,
'auto_refresh': node.auto_refresh,
+ 'multi': getattr(node, 'multi', False),
}
self._set_group_values(node, values)
if node.target:
values['target'] = node.target
- id = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
+ id = self.pool.get('ir.model.data')._update(self.cr, 1, \
'ir.actions.act_window', self.module, values, node.id, mode=self.mode)
self.id_map[node.id] = int(id)
keyword = 'client_action_relate'
value = 'ir.actions.act_window,%s' % id
replace = node.replace or True
- self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', keyword, \
+ self.pool.get('ir.model.data').ir_set(self.cr, 1, 'action', keyword, \
node.id, [node.src_model], value, replace=replace, noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
# TODO add remove ir.model.data
ids = [self.get_id(node.id)]
if len(ids):
self.pool.get(node.model).unlink(self.cr, self.uid, ids)
- self.pool.get('ir.model.data')._unlink(self.cr, self.uid, node.model, ids)
+ self.pool.get('ir.model.data')._unlink(self.cr, 1, node.model, ids)
else:
self.logger.log(logging.TEST, "Record not deleted.")
res = {'name': node.name, 'url': node.url, 'target': node.target}
- id = self.pool.get('ir.model.data')._update(self.cr, self.uid, \
+ id = self.pool.get('ir.model.data')._update(self.cr, 1, \
"ir.actions.url", self.module, res, node.id, mode=self.mode)
self.id_map[node.id] = int(id)
# ir_set
keyword = node.keyword or 'client_action_multi'
value = 'ir.actions.url,%s' % id
replace = node.replace or True
- self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
+ self.pool.get('ir.model.data').ir_set(self.cr, 1, 'action', \
keyword, node.url, ["ir.actions.url"], value, replace=replace, \
noupdate=self.isnoupdate(node), isobject=True, xml_id=node.id)
else:
value = expression
res[fieldname] = value
- self.pool.get('ir.model.data').ir_set(self.cr, self.uid, res['key'], res['key2'], \
+ self.pool.get('ir.model.data').ir_set(self.cr, 1, res['key'], res['key2'], \
res['name'], res['models'], res['value'], replace=res.get('replace',True), \
isobject=res.get('isobject', False), meta=res.get('meta',None))
for dest, f in (('name','string'), ('model','model'), ('report_name','name')):
values[dest] = getattr(node, f)
assert values[dest], "Attribute %s of report is empty !" % (f,)
- for field,dest in (('rml','report_rml'),('xml','report_xml'),('xsl','report_xsl'),('attachment','attachment'),('attachment_use','attachment_use')):
+ for field,dest in (('rml','report_rml'),('file','report_rml'),('xml','report_xml'),('xsl','report_xsl'),('attachment','attachment'),('attachment_use','attachment_use')):
if getattr(node, field):
values[dest] = getattr(node, field)
if node.auto:
self._set_group_values(node, values)
- id = self.pool.get('ir.model.data')._update(self.cr, self.uid, "ir.actions.report.xml", \
+ id = self.pool.get('ir.model.data')._update(self.cr, 1, "ir.actions.report.xml", \
self.module, values, xml_id, noupdate=self.isnoupdate(node), mode=self.mode)
self.id_map[xml_id] = int(id)
keyword = node.keyword or 'client_print_multi'
value = 'ir.actions.report.xml,%s' % id
replace = node.replace or True
- self.pool.get('ir.model.data').ir_set(self.cr, self.uid, 'action', \
+ self.pool.get('ir.model.data').ir_set(self.cr, 1, 'action', \
keyword, values['name'], [values['model']], value, replace=replace, isobject=True, xml_id=xml_id)
def process_none(self):