1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
35 logging.getLogger("init").warning('could not find pytz library, please install it')
36 class pytzclass(object):
41 from datetime import datetime, timedelta
42 from lxml import etree
47 from config import config
49 # Import of XML records requires the unsafe eval as well,
50 # almost everywhere, which is ok because it supposedly comes
51 # from trusted data, but at least we make it obvious now.
53 from tools.safe_eval import safe_eval as eval
55 class ConvertError(Exception):
56 def __init__(self, doc, orig_excpt):
58 self.orig = orig_excpt
61 return 'Exception:\n\t%s\nUsing file:\n%s' % (self.orig, self.d)
64 return lambda x: self.id_get(cr, False, x)
66 def _obj(pool, cr, uid, model_str, context=None):
67 model = pool.get(model_str)
68 return lambda x: model.browse(cr, uid, x, context=context)
70 def _eval_xml(self, node, pool, cr, uid, idref, context=None):
73 if node.tag in ('field','value'):
74 t = node.get('type','char')
75 f_model = node.get('model', '').encode('utf-8')
76 if node.get('search'):
77 f_search = node.get("search",'').encode('utf-8')
78 f_use = node.get("use",'id').encode('utf-8')
79 f_name = node.get("name",'').encode('utf-8')
80 q = unsafe_eval(f_search, idref)
81 ids = pool.get(f_model).search(cr, uid, q)
83 ids = map(lambda x: x[f_use], pool.get(f_model).read(cr, uid, ids, [f_use]))
84 _cols = pool.get(f_model)._columns
85 if (f_name in _cols) and _cols[f_name]._type=='many2many':
90 if isinstance(f_val, tuple):
93 a_eval = node.get('eval','')
99 version=release.major_version,
100 ref=lambda x: self.id_get(cr, False, x),
103 idref2['obj'] = _obj(self.pool, cr, uid, f_model, context=context)
106 return unsafe_eval(a_eval, idref2)
108 logger = logging.getLogger('init')
109 logger.warning('could not eval(%s) for %s in %s' % (a_eval, node.get('name'), context), exc_info=True)
112 def _process(s, idref):
113 m = re.findall('[^%]%\((.*?)\)[ds]', s)
116 idref[id]=self.id_get(cr, False, id)
118 return '<?xml version="1.0"?>\n'\
119 +_process("".join([etree.tostring(n, encoding='utf-8')
122 if t in ('char', 'int', 'float'):
129 return int(d.strip())
131 return float(d.strip())
133 elif t in ('list','tuple'):
135 for n in node.findall('./value'):
136 res.append(_eval_xml(self,n,pool,cr,uid,idref))
140 elif node.tag == "getitem":
142 res=_eval_xml(self,n,pool,cr,uid,idref)
145 elif node.get('type') in ("int", "list"):
146 return res[int(node.get('index'))]
148 return res[node.get('index','').encode("utf8")]
149 elif node.tag == "function":
151 a_eval = node.get('eval','')
153 idref['ref'] = lambda x: self.id_get(cr, False, x)
154 args = unsafe_eval(a_eval, idref)
156 return_val = _eval_xml(self,n, pool, cr, uid, idref, context)
157 if return_val is not None:
158 args.append(return_val)
159 model = pool.get(node.get('model',''))
160 method = node.get('name','')
161 res = getattr(model, method)(cr, uid, *args)
163 elif node.tag == "test":
166 escape_re = re.compile(r'(?<!\\)/')
168 return x.replace('\\/', '/')
170 class assertion_report(object):
174 def record_assertion(self, success, severity):
176 Records the result of an assertion for the failed/success count
179 if severity in self._report:
180 self._report[severity][success] += 1
182 self._report[severity] = {success:1, not success: 0}
185 def get_report(self):
189 res = '\nAssertions report:\nLevel\tsuccess\tfailed\n'
191 for sev in self._report:
192 res += sev + '\t' + str(self._report[sev][True]) + '\t' + str(self._report[sev][False]) + '\n'
193 success += self._report[sev][True]
194 failed += self._report[sev][False]
195 res += 'total\t' + str(success) + '\t' + str(failed) + '\n'
196 res += 'end of report (' + str(success + failed) + ' assertion(s) checked)'
199 class xml_import(object):
201 def nodeattr2bool(node, attr, default=False):
202 if not node.get(attr):
204 val = node.get(attr).strip()
207 return val.lower() not in ('0', 'false', 'off')
209 def isnoupdate(self, data_node=None):
210 return self.noupdate or (len(data_node) and self.nodeattr2bool(data_node, 'noupdate', False))
212 def get_context(self, data_node, node, eval_dict):
213 data_node_context = (len(data_node) and data_node.get('context','').encode('utf8'))
214 if data_node_context:
215 context = unsafe_eval(data_node_context, eval_dict)
219 node_context = node.get("context",'').encode('utf8')
221 context.update(unsafe_eval(node_context, eval_dict))
225 def get_uid(self, cr, uid, data_node, node):
226 node_uid = node.get('uid','') or (len(data_node) and data_node.get('uid',''))
228 return self.id_get(cr, None, node_uid)
231 def _test_xml_id(self, xml_id):
234 module, id = xml_id.split('.', 1)
235 assert '.' not in id, """The ID reference "%s" must contain
236 maximum one dot. They are used to refer to other modules ID, in the
237 form: module.record_id""" % (xml_id,)
238 if module != self.module:
239 modcnt = self.pool.get('ir.module.module').search_count(self.cr, self.uid, ['&', ('name', '=', module), ('state', 'in', ['installed'])])
240 assert modcnt == 1, """The ID "%s" refers to an uninstalled module""" % (xml_id,)
243 self.logger.notifyChannel('init', netsvc.LOG_ERROR, 'id: %s is to long (max: 64)'% (id,))
245 def _tag_delete(self, cr, rec, data_node=None):
246 d_model = rec.get("model",'')
247 d_search = rec.get("search",'')
248 d_id = rec.get("id",'')
251 ids = self.pool.get(d_model).search(cr, self.uid, unsafe_eval(d_search))
254 ids.append(self.id_get(cr, d_model, d_id))
256 # d_id cannot be found. doesn't matter in this case
259 self.pool.get(d_model).unlink(cr, self.uid, ids)
260 self.pool.get('ir.model.data')._unlink(cr, self.uid, d_model, ids)
262 def _remove_ir_values(self, cr, name, value, model):
263 ir_value_ids = self.pool.get('ir.values').search(cr, self.uid, [('name','=',name),('value','=',value),('model','=',model)])
265 self.pool.get('ir.values').unlink(cr, self.uid, ir_value_ids)
266 self.pool.get('ir.model.data')._unlink(cr, self.uid, 'ir.values', ir_value_ids)
270 def _tag_report(self, cr, rec, data_node=None):
272 for dest,f in (('name','string'),('model','model'),('report_name','name')):
273 res[dest] = rec.get(f,'').encode('utf8')
274 assert res[dest], "Attribute %s of report is empty !" % (f,)
275 for field,dest in (('rml','report_rml'),('xml','report_xml'),('xsl','report_xsl'),('attachment','attachment'),('attachment_use','attachment_use')):
277 res[dest] = rec.get(field).encode('utf8')
279 res['auto'] = eval(rec.get('auto','False'))
281 sxw_content = misc.file_open(rec.get('sxw')).read()
282 res['report_sxw_content'] = sxw_content
283 if rec.get('header'):
284 res['header'] = eval(rec.get('header','False'))
285 if rec.get('report_type'):
286 res['report_type'] = rec.get('report_type')
288 res['multi'] = rec.get('multi') and eval(rec.get('multi','False'))
290 xml_id = rec.get('id','').encode('utf8')
291 self._test_xml_id(xml_id)
293 if rec.get('groups'):
294 g_names = rec.get('groups','').split(',')
296 for group in g_names:
297 if group.startswith('-'):
298 group_id = self.id_get(cr, 'res.groups', group[1:])
299 groups_value.append((3, group_id))
301 group_id = self.id_get(cr, 'res.groups', group)
302 groups_value.append((4, group_id))
303 res['groups_id'] = groups_value
305 id = self.pool.get('ir.model.data')._update(cr, self.uid, "ir.actions.report.xml", self.module, res, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode)
306 self.idref[xml_id] = int(id)
308 if not rec.get('menu') or eval(rec.get('menu','False')):
309 keyword = str(rec.get('keyword', 'client_print_multi'))
310 value = 'ir.actions.report.xml,'+str(id)
311 replace = rec.get('replace', True)
312 self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, res['name'], [res['model']], value, replace=replace, isobject=True, xml_id=xml_id)
313 elif self.mode=='update' and eval(rec.get('menu','False'))==False:
314 # Special check for report having attribute menu=False on update
315 value = 'ir.actions.report.xml,'+str(id)
316 self._remove_ir_values(cr, res['name'], value, res['model'])
319 def _tag_function(self, cr, rec, data_node=None):
320 if self.isnoupdate(data_node) and self.mode != 'init':
322 context = self.get_context(data_node, rec, {'ref': _ref(self, cr)})
323 uid = self.get_uid(cr, self.uid, data_node, rec)
324 _eval_xml(self,rec, self.pool, cr, uid, self.idref, context=context)
327 def _tag_wizard(self, cr, rec, data_node=None):
328 string = rec.get("string",'').encode('utf8')
329 model = rec.get("model",'').encode('utf8')
330 name = rec.get("name",'').encode('utf8')
331 xml_id = rec.get('id','').encode('utf8')
332 self._test_xml_id(xml_id)
333 multi = rec.get('multi','') and eval(rec.get('multi','False'))
334 res = {'name': string, 'wiz_name': name, 'multi': multi, 'model': model}
336 if rec.get('groups'):
337 g_names = rec.get('groups','').split(',')
339 for group in g_names:
340 if group.startswith('-'):
341 group_id = self.id_get(cr, 'res.groups', group[1:])
342 groups_value.append((3, group_id))
344 group_id = self.id_get(cr, 'res.groups', group)
345 groups_value.append((4, group_id))
346 res['groups_id'] = groups_value
348 id = self.pool.get('ir.model.data')._update(cr, self.uid, "ir.actions.wizard", self.module, res, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode)
349 self.idref[xml_id] = int(id)
351 if (not rec.get('menu') or eval(rec.get('menu','False'))) and id:
352 keyword = str(rec.get('keyword','') or 'client_action_multi')
353 value = 'ir.actions.wizard,'+str(id)
354 replace = rec.get("replace",'') or True
355 self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, string, [model], value, replace=replace, isobject=True, xml_id=xml_id)
356 elif self.mode=='update' and (rec.get('menu') and eval(rec.get('menu','False'))==False):
357 # Special check for wizard having attribute menu=False on update
358 value = 'ir.actions.wizard,'+str(id)
359 self._remove_ir_values(cr, string, value, model)
361 def _tag_url(self, cr, rec, data_node=None):
362 url = rec.get("string",'').encode('utf8')
363 target = rec.get("target",'').encode('utf8')
364 name = rec.get("name",'').encode('utf8')
365 xml_id = rec.get('id','').encode('utf8')
366 self._test_xml_id(xml_id)
368 res = {'name': name, 'url': url, 'target':target}
370 id = self.pool.get('ir.model.data')._update(cr, self.uid, "ir.actions.url", self.module, res, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode)
371 self.idref[xml_id] = int(id)
373 if (not rec.get('menu') or eval(rec.get('menu','False'))) and id:
374 keyword = str(rec.get('keyword','') or 'client_action_multi')
375 value = 'ir.actions.url,'+str(id)
376 replace = rec.get("replace",'') or True
377 self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, url, ["ir.actions.url"], value, replace=replace, isobject=True, xml_id=xml_id)
378 elif self.mode=='update' and (rec.get('menu') and eval(rec.get('menu','False'))==False):
379 # Special check for URL having attribute menu=False on update
380 value = 'ir.actions.url,'+str(id)
381 self._remove_ir_values(cr, url, value, "ir.actions.url")
383 def _tag_act_window(self, cr, rec, data_node=None):
384 name = rec.get('name','').encode('utf-8')
385 xml_id = rec.get('id','').encode('utf8')
386 self._test_xml_id(xml_id)
387 type = rec.get('type','').encode('utf-8') or 'ir.actions.act_window'
390 view_id = self.id_get(cr, 'ir.actions.act_window', rec.get('view','').encode('utf-8'))
391 domain = rec.get('domain','').encode('utf-8') or '{}'
392 context = rec.get('context','').encode('utf-8') or '{}'
393 res_model = rec.get('res_model','').encode('utf-8')
394 src_model = rec.get('src_model','').encode('utf-8')
395 view_type = rec.get('view_type','').encode('utf-8') or 'form'
396 view_mode = rec.get('view_mode','').encode('utf-8') or 'tree,form'
398 usage = rec.get('usage','').encode('utf-8')
399 limit = rec.get('limit','').encode('utf-8')
400 auto_refresh = rec.get('auto_refresh','').encode('utf-8')
402 # WARNING: don't remove the unused variables and functions below as they are
403 # used by the unsafe_eval() call.
404 # TODO: change this into an eval call with locals and globals parameters
406 active_id = str("active_id") # for further reference in client/bin/tools/__init__.py
408 return self.id_get(cr, None, str_id)
409 context = unsafe_eval(context)
410 # domain = eval(domain) # XXX need to test this line -> uid, active_id, active_ids, ...
418 'res_model': res_model,
419 'src_model': src_model,
420 'view_type': view_type,
421 'view_mode': view_mode,
424 'auto_refresh': auto_refresh,
427 if rec.get('groups'):
428 g_names = rec.get('groups','').split(',')
430 for group in g_names:
431 if group.startswith('-'):
432 group_id = self.id_get(cr, 'res.groups', group[1:])
433 groups_value.append((3, group_id))
435 group_id = self.id_get(cr, 'res.groups', group)
436 groups_value.append((4, group_id))
437 res['groups_id'] = groups_value
439 if rec.get('target'):
440 res['target'] = rec.get('target','')
441 id = self.pool.get('ir.model.data')._update(cr, self.uid, 'ir.actions.act_window', self.module, res, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode)
442 self.idref[xml_id] = int(id)
445 #keyword = 'client_action_relate'
446 keyword = rec.get('key2','').encode('utf-8') or 'client_action_relate'
447 value = 'ir.actions.act_window,'+str(id)
448 replace = rec.get('replace','') or True
449 self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, xml_id, [src_model], value, replace=replace, isobject=True, xml_id=xml_id)
450 # TODO add remove ir.model.data
452 def _tag_ir_set(self, cr, rec, data_node=None):
453 if self.mode != 'init':
456 for field in rec.findall('./field'):
457 f_name = field.get("name",'').encode('utf-8')
458 f_val = _eval_xml(self,field,self.pool, cr, self.uid, self.idref)
460 self.pool.get('ir.model.data').ir_set(cr, self.uid, 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))
462 def _tag_workflow(self, cr, rec, data_node=None):
463 if self.isnoupdate(data_node) and self.mode != 'init':
465 model = str(rec.get('model',''))
466 w_ref = rec.get('ref','')
468 id = self.id_get(cr, model, w_ref)
470 number_children = len(rec)
471 assert number_children > 0,\
472 'You must define a child node if you dont give a ref'
473 assert number_children == 1,\
474 'Only one child node is accepted (%d given)' % number_children
475 id = _eval_xml(self, rec[0], self.pool, cr, self.uid, self.idref)
477 uid = self.get_uid(cr, self.uid, data_node, rec)
478 wf_service = netsvc.LocalService("workflow")
479 wf_service.trg_validate(uid, model,
481 str(rec.get('action','')), cr)
484 # Support two types of notation:
485 # name="Inventory Control/Sending Goods"
490 def _tag_menuitem(self, cr, rec, data_node=None):
491 rec_id = rec.get("id",'').encode('ascii')
492 self._test_xml_id(rec_id)
493 m_l = map(escape, escape_re.split(rec.get("name",'').encode('utf8')))
495 values = {'parent_id': False}
496 if not rec.get('parent'):
498 for idx, menu_elem in enumerate(m_l):
500 cr.execute('select id from ir_ui_menu where parent_id=%s and name=%s', (pid, menu_elem))
502 cr.execute('select id from ir_ui_menu where parent_id is null and name=%s', (menu_elem,))
505 values = {'parent_id': pid,'name':menu_elem}
508 xml_id = idx==len(m_l)-1 and rec.get('id','').encode('utf8')
510 self.pool.get('ir.model.data')._update_dummy(cr, self.uid, 'ir.ui.menu', self.module, xml_id, idx==len(m_l)-1)
512 self.logger.notifyChannel('init', netsvc.LOG_ERROR, "module: %s xml_id: %s" % (self.module, xml_id))
514 # the menuitem does't exist but we are in branch (not a leaf)
515 self.logger.notifyChannel("init", netsvc.LOG_WARNING, 'Warning no ID for submenu %s of menu %s !' % (menu_elem, str(m_l)))
516 pid = self.pool.get('ir.ui.menu').create(cr, self.uid, {'parent_id' : pid, 'name' : menu_elem})
518 menu_parent_id = self.id_get(cr, 'ir.ui.menu', rec.get('parent',''))
519 values = {'parent_id': menu_parent_id}
521 values['name'] = rec.get('name')
523 res = [ self.id_get(cr, 'ir.ui.menu', rec.get('id','')) ]
527 if rec.get('action'):
528 a_action = rec.get('action','').encode('utf8')
529 a_type = rec.get('type','').encode('utf8') or 'act_window'
531 "act_window": 'STOCK_NEW',
532 "report.xml": 'STOCK_PASTE',
533 "wizard": 'STOCK_EXECUTE',
534 "url": 'STOCK_JUMP_TO'
536 values['icon'] = icons.get(a_type,'STOCK_NEW')
537 if a_type=='act_window':
538 a_id = self.id_get(cr, 'ir.actions.%s'% a_type, a_action)
539 cr.execute('select view_type,view_mode,name,view_id,target from ir_act_window where id=%s', (int(a_id),))
540 rrres = cr.fetchone()
541 assert rrres, "No window action defined for this id %s !\n" \
542 "Verify that this is a window action or add a type argument." % (a_action,)
543 action_type,action_mode,action_name,view_id,target = rrres
545 cr.execute('SELECT type FROM ir_ui_view WHERE id=%s', (int(view_id),))
546 action_mode, = cr.fetchone()
547 cr.execute('SELECT view_mode FROM ir_act_window_view WHERE act_window_id=%s ORDER BY sequence LIMIT 1', (int(a_id),))
549 action_mode, = cr.fetchone()
550 if action_type=='tree':
551 values['icon'] = 'STOCK_INDENT'
552 elif action_mode and action_mode.startswith('tree'):
553 values['icon'] = 'STOCK_JUSTIFY_FILL'
554 elif action_mode and action_mode.startswith('graph'):
555 values['icon'] = 'terp-graph'
556 elif action_mode and action_mode.startswith('calendar'):
557 values['icon'] = 'terp-calendar'
559 values['icon'] = 'STOCK_EXECUTE'
560 if not values.get('name', False):
561 values['name'] = action_name
562 elif a_type=='wizard':
563 a_id = self.id_get(cr, 'ir.actions.%s'% a_type, a_action)
564 cr.execute('select name from ir_act_wizard where id=%s', (int(a_id),))
566 if (not values.get('name', False)) and resw:
567 values['name'] = resw[0]
568 if rec.get('sequence'):
569 values['sequence'] = int(rec.get('sequence'))
571 values['icon'] = str(rec.get('icon'))
573 if rec.get('groups'):
574 g_names = rec.get('groups','').split(',')
576 for group in g_names:
577 if group.startswith('-'):
578 group_id = self.id_get(cr, 'res.groups', group[1:])
579 groups_value.append((3, group_id))
581 group_id = self.id_get(cr, 'res.groups', group)
582 groups_value.append((4, group_id))
583 values['groups_id'] = groups_value
585 xml_id = rec.get('id','').encode('utf8')
586 self._test_xml_id(xml_id)
587 pid = self.pool.get('ir.model.data')._update(cr, self.uid, 'ir.ui.menu', self.module, values, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode, res_id=res and res[0] or False)
590 self.idref[rec_id] = int(pid)
592 if rec.get('action') and pid:
593 a_action = rec.get('action').encode('utf8')
594 a_type = rec.get('type','').encode('utf8') or 'act_window'
595 a_id = self.id_get(cr, 'ir.actions.%s' % a_type, a_action)
596 action = "ir.actions.%s,%d" % (a_type, a_id)
597 self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', 'tree_but_open', 'Menuitem', [('ir.ui.menu', int(pid))], action, True, True, xml_id=rec_id)
598 return ('ir.ui.menu', pid)
600 def _assert_equals(self, f1, f2, prec = 4):
601 return not round(f1 - f2, prec)
603 def _tag_assert(self, cr, rec, data_node=None):
604 if self.isnoupdate(data_node) and self.mode != 'init':
607 rec_model = rec.get("model",'').encode('ascii')
608 model = self.pool.get(rec_model)
609 assert model, "The model %s does not exist !" % (rec_model,)
610 rec_id = rec.get("id",'').encode('ascii')
611 self._test_xml_id(rec_id)
612 rec_src = rec.get("search",'').encode('utf8')
613 rec_src_count = rec.get("count")
615 severity = rec.get("severity",'').encode('ascii') or netsvc.LOG_ERROR
616 rec_string = rec.get("string",'').encode('utf8') or 'unknown'
619 eval_dict = {'ref': _ref(self, cr)}
620 context = self.get_context(data_node, rec, eval_dict)
621 uid = self.get_uid(cr, self.uid, data_node, rec)
623 ids = [self.id_get(cr, rec_model, rec_id)]
625 q = unsafe_eval(rec_src, eval_dict)
626 ids = self.pool.get(rec_model).search(cr, uid, q, context=context)
628 count = int(rec_src_count)
629 if len(ids) != count:
630 self.assert_report.record_assertion(False, severity)
631 msg = 'assertion "%s" failed!\n' \
632 ' Incorrect search count:\n' \
633 ' expected count: %d\n' \
634 ' obtained count: %d\n' \
635 % (rec_string, count, len(ids))
636 self.logger.notifyChannel('init', severity, msg)
637 sevval = getattr(logging, severity.upper())
638 if sevval >= config['assert_exit_level']:
639 # TODO: define a dedicated exception
640 raise Exception('Severe assertion failure')
643 assert ids is not None,\
644 'You must give either an id or a search criteria'
647 brrec = model.browse(cr, uid, id, context)
649 def __getitem__(self2, key):
652 return dict.__getitem__(self2, key)
654 globals_dict['floatEqual'] = self._assert_equals
655 globals_dict['ref'] = ref
656 globals_dict['_ref'] = ref
657 for test in rec.findall('./test'):
658 f_expr = test.get("expr",'').encode('utf-8')
659 expected_value = _eval_xml(self, test, self.pool, cr, uid, self.idref, context=context) or True
660 expression_value = unsafe_eval(f_expr, globals_dict)
661 if expression_value != expected_value: # assertion failed
662 self.assert_report.record_assertion(False, severity)
663 msg = 'assertion "%s" failed!\n' \
665 ' expected value: %r\n' \
666 ' obtained value: %r\n' \
667 % (rec_string, etree.tostring(test), expected_value, expression_value)
668 self.logger.notifyChannel('init', severity, msg)
669 sevval = getattr(logging, severity.upper())
670 if sevval >= config['assert_exit_level']:
671 # TODO: define a dedicated exception
672 raise Exception('Severe assertion failure')
674 else: # all tests were successful for this assertion tag (no break)
675 self.assert_report.record_assertion(True, severity)
677 def _tag_record(self, cr, rec, data_node=None):
678 rec_model = rec.get("model").encode('ascii')
679 model = self.pool.get(rec_model)
680 assert model, "The model %s does not exist !" % (rec_model,)
681 rec_id = rec.get("id",'').encode('ascii')
682 rec_context = rec.get("context", None)
684 rec_context = unsafe_eval(rec_context)
685 self._test_xml_id(rec_id)
686 if self.isnoupdate(data_node) and self.mode != 'init':
687 # check if the xml record has an id string
690 module,rec_id2 = rec_id.split('.')
694 id = self.pool.get('ir.model.data')._update_dummy(cr, self.uid, rec_model, module, rec_id2)
695 # check if the resource already existed at the last update
697 # if it existed, we don't update the data, but we need to
698 # know the id of the existing record anyway
699 self.idref[rec_id] = int(id)
702 # if the resource didn't exist
703 if not self.nodeattr2bool(rec, 'forcecreate', True):
704 # we don't want to create it, so we skip it
706 # else, we let the record to be created
709 # otherwise it is skipped
712 for field in rec.findall('./field'):
713 #TODO: most of this code is duplicated above (in _eval_xml)...
714 f_name = field.get("name",'').encode('utf-8')
715 f_ref = field.get("ref",'').encode('ascii')
716 f_search = field.get("search",'').encode('utf-8')
717 f_model = field.get("model",'').encode('ascii')
718 if not f_model and model._columns.get(f_name,False):
719 f_model = model._columns[f_name]._obj
720 f_use = field.get("use",'').encode('ascii') or 'id'
724 q = unsafe_eval(f_search, self.idref)
726 assert f_model, 'Define an attribute model="..." in your .XML file !'
727 f_obj = self.pool.get(f_model)
728 # browse the objects searched
729 s = f_obj.browse(cr, self.uid, f_obj.search(cr, self.uid, q))
730 # column definitions of the "local" object
731 _cols = self.pool.get(rec_model)._columns
732 # if the current field is many2many
733 if (f_name in _cols) and _cols[f_name]._type=='many2many':
734 f_val = [(6, 0, map(lambda x: x[f_use], s))]
736 # otherwise (we are probably in a many2one field),
737 # take the first element of the search
743 if f_name in model._columns \
744 and model._columns[f_name]._type == 'reference':
745 val = self.model_id_get(cr, f_model, f_ref)
746 f_val = val[0] + ',' + str(val[1])
748 f_val = self.id_get(cr, f_model, f_ref)
750 f_val = _eval_xml(self,field, self.pool, cr, self.uid, self.idref)
751 if model._columns.has_key(f_name):
752 if isinstance(model._columns[f_name], osv.fields.integer):
756 id = self.pool.get('ir.model.data')._update(cr, self.uid, rec_model, self.module, res, rec_id or False, not self.isnoupdate(data_node), noupdate=self.isnoupdate(data_node), mode=self.mode, context=rec_context )
758 self.idref[rec_id] = int(id)
759 if config.get('import_partial', False):
763 def id_get(self, cr, model, id_str):
764 if id_str in self.idref:
765 return self.idref[id_str]
766 return self.model_id_get(cr, model, id_str)[1]
768 def model_id_get(self, cr, model, id_str):
769 model_data_obj = self.pool.get('ir.model.data')
772 mod,id_str = id_str.split('.')
773 result = model_data_obj._get_id(cr, self.uid, mod, id_str)
774 res = model_data_obj.read(cr, self.uid, [result], ['model', 'res_id'])
775 if res and res[0] and res[0]['res_id']:
776 return res[0]['model'], int(res[0]['res_id'])
780 if not de.tag in ['terp', 'openerp']:
781 self.logger.notifyChannel("init", netsvc.LOG_ERROR, "Mismatch xml format" )
782 raise Exception( "Mismatch xml format: only terp or openerp as root tag" )
785 self.logger.notifyChannel("init", netsvc.LOG_WARNING, "The tag <terp/> is deprecated, use <openerp/>")
787 for n in de.findall('./data'):
789 if rec.tag in self._tags:
791 self._tags[rec.tag](self.cr, rec, n)
793 self.logger.notifyChannel("init", netsvc.LOG_ERROR, '\n'+etree.tostring(rec))
798 def __init__(self, cr, module, idref, mode, report=None, noupdate=False):
800 self.logger = netsvc.Logger()
805 self.pool = pooler.get_pool(cr.dbname)
808 report = assertion_report()
809 self.assert_report = report
810 self.noupdate = noupdate
812 'menuitem': self._tag_menuitem,
813 'record': self._tag_record,
814 'assert': self._tag_assert,
815 'report': self._tag_report,
816 'wizard': self._tag_wizard,
817 'delete': self._tag_delete,
818 'ir_set': self._tag_ir_set,
819 'function': self._tag_function,
820 'workflow': self._tag_workflow,
821 'act_window': self._tag_act_window,
825 def convert_csv_import(cr, module, fname, csvcontent, idref=None, mode='init',
833 model = ('.'.join(fname.split('.')[:-1]).split('-'))[0]
834 #remove folder path from model
835 head, model = os.path.split(model)
837 pool = pooler.get_pool(cr.dbname)
839 input = cStringIO.StringIO(csvcontent)
840 reader = csv.reader(input, quotechar='"', delimiter=',')
841 fields = reader.next()
843 if config.get('import_partial'):
844 fname_partial = module + '/'+ fname
845 if not os.path.isfile(config.get('import_partial')):
846 pickle.dump({}, file(config.get('import_partial'),'w+'))
848 data = pickle.load(file(config.get('import_partial')))
849 if fname_partial in data:
850 if not data[fname_partial]:
853 for i in range(data[fname_partial]):
856 if not (mode == 'init' or 'id' in fields):
857 logger = netsvc.Logger()
858 logger.notifyChannel("init", netsvc.LOG_ERROR,
859 "Import specification does not contain 'id' and we are in init mode, Cannot continue.")
865 if (not line) or not reduce(lambda x,y: x or y, line) :
868 datas.append(map(lambda x: misc.ustr(x), line))
870 logger = netsvc.Logger()
871 logger.notifyChannel("init", netsvc.LOG_ERROR, "Cannot import the line: %s" % line)
872 pool.get(model).import_data(cr, uid, fields, datas,mode, module, noupdate, filename=fname_partial)
873 if config.get('import_partial'):
874 data = pickle.load(file(config.get('import_partial')))
875 data[fname_partial] = 0
876 pickle.dump(data, file(config.get('import_partial'),'wb'))
882 def convert_xml_import(cr, module, xmlfile, idref=None, mode='init', noupdate=False, report=None):
883 doc = etree.parse(xmlfile)
884 relaxng = etree.RelaxNG(
885 etree.parse(os.path.join(config['root_path'],'import_xml.rng' )))
889 logger = netsvc.Logger()
890 logger.notifyChannel('init', netsvc.LOG_ERROR, 'The XML file does not fit the required schema !')
891 logger.notifyChannel('init', netsvc.LOG_ERROR, misc.ustr(relaxng.error_log.last_error))
896 obj = xml_import(cr, module, idref, mode, report=report, noupdate=noupdate)
897 obj.parse(doc.getroot())