[FIX] remove or convert old-API calls
This commit is contained in:
@@ -2,7 +2,6 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import models, fields, api
|
||||
from odoo.osv import osv
|
||||
|
||||
|
||||
class Project(models.Model):
|
||||
@@ -59,4 +58,4 @@ class Task(models.Model):
|
||||
subtask_project_id = fields.Many2one('project.project', related="project_id.subtask_project_id", string='Sub-task Project')
|
||||
subtask_count = fields.Integer(compute='_get_subtask_count', type='integer', string="Sub-task count")
|
||||
|
||||
_constraints = [(osv.osv._check_recursion, 'Circular references are not permitted between tasks and sub-tasks', ['parent_id'])]
|
||||
_constraints = [(models.BaseModel._check_recursion, 'Circular references are not permitted between tasks and sub-tasks', ['parent_id'])]
|
||||
|
||||
@@ -33,7 +33,8 @@ from odoo.tools import topological_sort
|
||||
from odoo.tools.translate import _
|
||||
from odoo.tools.misc import str2bool, xlwt
|
||||
from odoo import http
|
||||
from odoo.http import request, serialize_exception as _serialize_exception, content_disposition
|
||||
from odoo.http import content_disposition, dispatch_rpc, request, \
|
||||
serialize_exception as _serialize_exception
|
||||
from odoo.exceptions import AccessError
|
||||
from odoo.models import check_method_name
|
||||
|
||||
@@ -291,8 +292,7 @@ def set_cookie_and_redirect(redirect_url):
|
||||
return redirect
|
||||
|
||||
def load_actions_from_ir_values(action_slot, model, res_id):
|
||||
ir_values = request.session.model('ir.values')
|
||||
actions = ir_values.get_actions(action_slot=action_slot, model=model, res_id=res_id, context=request.context)
|
||||
actions = request.env['ir.values'].get_actions(action_slot, model, res_id)
|
||||
return [(id, name, clean_action(action)) for id, name, action in actions]
|
||||
|
||||
def clean_action(action):
|
||||
@@ -632,7 +632,7 @@ class Database(http.Controller):
|
||||
try:
|
||||
# country code could be = "False" which is actually True in python
|
||||
country_code = post.get('country_code') or False
|
||||
request.session.proxy("db").create_database(master_pwd, name, bool(post.get('demo')), lang, password, post.get('login'), country_code)
|
||||
dispatch_rpc('db', 'create_database', [master_pwd, name, bool(post.get('demo')), lang, password, post.get('login'), country_code])
|
||||
request.session.authenticate(name, 'admin', password)
|
||||
return http.local_redirect('/web/')
|
||||
except Exception, e:
|
||||
@@ -642,7 +642,7 @@ class Database(http.Controller):
|
||||
@http.route('/web/database/duplicate', type='http', auth="none", methods=['POST'], csrf=False)
|
||||
def duplicate(self, master_pwd, name, new_name):
|
||||
try:
|
||||
request.session.proxy("db").duplicate_database(master_pwd, name, new_name)
|
||||
dispatch_rpc('db', 'duplicate_database', [master_pwd, name, new_name])
|
||||
return http.local_redirect('/web/database/manager')
|
||||
except Exception, e:
|
||||
error = "Database duplication error: %s" % e
|
||||
@@ -651,7 +651,7 @@ class Database(http.Controller):
|
||||
@http.route('/web/database/drop', type='http', auth="none", methods=['POST'], csrf=False)
|
||||
def drop(self, master_pwd, name):
|
||||
try:
|
||||
request.session.proxy("db").drop(master_pwd, name)
|
||||
dispatch_rpc('db','drop', [master_pwd, name])
|
||||
return http.local_redirect('/web/database/manager')
|
||||
except Exception, e:
|
||||
error = "Database deletion error: %s" % e
|
||||
@@ -679,7 +679,7 @@ class Database(http.Controller):
|
||||
def restore(self, master_pwd, backup_file, name, copy=False):
|
||||
try:
|
||||
data = base64.b64encode(backup_file.read())
|
||||
request.session.proxy("db").restore(master_pwd, name, data, str2bool(copy))
|
||||
dispatch_rpc('db', 'restore', [master_pwd, name, data, str2bool(copy)])
|
||||
return http.local_redirect('/web/database/manager')
|
||||
except Exception, e:
|
||||
error = "Database restore error: %s" % e
|
||||
@@ -688,7 +688,7 @@ class Database(http.Controller):
|
||||
@http.route('/web/database/change_password', type='http', auth="none", methods=['POST'], csrf=False)
|
||||
def change_password(self, master_pwd, master_pwd_new):
|
||||
try:
|
||||
request.session.proxy("db").change_admin_password(master_pwd, master_pwd_new)
|
||||
dispatch_rpc('db', 'change_admin_password', [master_pwd, master_pwd_new])
|
||||
return http.local_redirect('/web/database/manager')
|
||||
except Exception, e:
|
||||
error = "Master password update error: %s" % e
|
||||
@@ -717,8 +717,7 @@ class Session(http.Controller):
|
||||
if new_password != confirm_password:
|
||||
return {'error': _('The new password and its confirmation must be identical.'),'title': _('Change Password')}
|
||||
try:
|
||||
if request.session.model('res.users').change_password(
|
||||
old_password, new_password):
|
||||
if request.env['res.users'].change_password(old_password, new_password):
|
||||
return {'new_password':new_password}
|
||||
except Exception:
|
||||
return {'error': _('The old password you provided is incorrect, your password was not changed.'), 'title': _('Change Password')}
|
||||
@@ -727,7 +726,7 @@ class Session(http.Controller):
|
||||
@http.route('/web/session/get_lang_list', type='json', auth="none")
|
||||
def get_lang_list(self):
|
||||
try:
|
||||
return request.session.proxy("db").list_lang() or []
|
||||
return dispatch_rpc('db', 'list_lang', []) or []
|
||||
except Exception, e:
|
||||
return {"error": e, "title": _("Languages")}
|
||||
|
||||
@@ -765,7 +764,7 @@ class Session(http.Controller):
|
||||
|
||||
@http.route('/web/session/check', type='json', auth="user")
|
||||
def check(self):
|
||||
request.session.assert_valid()
|
||||
request.session.check_security()
|
||||
return None
|
||||
|
||||
@http.route('/web/session/destroy', type='json', auth="user")
|
||||
@@ -786,13 +785,14 @@ class Menu(http.Controller):
|
||||
:return: needaction data
|
||||
:rtype: dict(menu_id: {'needaction_enabled': boolean, 'needaction_counter': int})
|
||||
"""
|
||||
return request.session.model('ir.ui.menu').get_needaction_data(menu_ids, request.context)
|
||||
return request.env['ir.ui.menu'].browse(menu_ids).get_needaction_data()
|
||||
|
||||
class DataSet(http.Controller):
|
||||
|
||||
@http.route('/web/dataset/search_read', type='json', auth="user")
|
||||
def search_read(self, model, fields=False, offset=0, limit=False, domain=None, sort=None):
|
||||
return self.do_search_read(model, fields, offset, limit, domain, sort)
|
||||
|
||||
def do_search_read(self, model, fields=False, offset=0, limit=False, domain=None
|
||||
, sort=None):
|
||||
""" Performs a search() followed by a read() (if needed) using the
|
||||
@@ -810,17 +810,17 @@ class DataSet(http.Controller):
|
||||
matching fields selection set)
|
||||
:rtype: list
|
||||
"""
|
||||
Model = request.session.model(model)
|
||||
Model = request.env[model]
|
||||
|
||||
records = Model.search_read(domain, fields, offset or 0, limit or False, sort or False,
|
||||
request.context)
|
||||
records = Model.search_read(domain, fields,
|
||||
offset=offset or 0, limit=limit or False, order=sort or False)
|
||||
if not records:
|
||||
return {
|
||||
'length': 0,
|
||||
'records': []
|
||||
}
|
||||
if limit and len(records) == limit:
|
||||
length = Model.search_count(domain, request.context)
|
||||
length = Model.search_count(domain)
|
||||
else:
|
||||
length = len(records) + (offset or 0)
|
||||
return {
|
||||
@@ -830,9 +830,8 @@ class DataSet(http.Controller):
|
||||
|
||||
@http.route('/web/dataset/load', type='json', auth="user")
|
||||
def load(self, model, id, fields):
|
||||
m = request.session.model(model)
|
||||
value = {}
|
||||
r = m.read([id], False, request.context)
|
||||
r = request.env[model].browse([id]).read()
|
||||
if r:
|
||||
value = r[0]
|
||||
return {'value': value}
|
||||
@@ -861,7 +860,8 @@ class DataSet(http.Controller):
|
||||
|
||||
@http.route('/web/dataset/exec_workflow', type='json', auth="user")
|
||||
def exec_workflow(self, model, id, signal):
|
||||
return request.session.exec_workflow(model, id, signal)
|
||||
request.session.check_security()
|
||||
return request.env[model].browse(id).signal_workflow(signal)[id]
|
||||
|
||||
@http.route('/web/dataset/resequence', type='json', auth="user")
|
||||
def resequence(self, model, ids, field='sequence', offset=0):
|
||||
@@ -878,24 +878,24 @@ class DataSet(http.Controller):
|
||||
starting the resequencing from an arbitrary number,
|
||||
defaults to ``0``
|
||||
"""
|
||||
m = request.session.model(model)
|
||||
m = request.env[model]
|
||||
if not m.fields_get([field]):
|
||||
return False
|
||||
# python 2.6 has no start parameter
|
||||
for i, id in enumerate(ids):
|
||||
m.write(id, { field: i + offset })
|
||||
for i, record in enumerate(m.browse(ids)):
|
||||
record.write({field: i + offset})
|
||||
return True
|
||||
|
||||
class View(http.Controller):
|
||||
|
||||
@http.route('/web/view/add_custom', type='json', auth="user")
|
||||
def add_custom(self, view_id, arch):
|
||||
CustomView = request.session.model('ir.ui.view.custom')
|
||||
CustomView = request.env['ir.ui.view.custom']
|
||||
CustomView.create({
|
||||
'user_id': request.session.uid,
|
||||
'ref_id': view_id,
|
||||
'arch': arch
|
||||
}, request.context)
|
||||
})
|
||||
return {'result': True}
|
||||
|
||||
class TreeView(View):
|
||||
@@ -1016,23 +1016,23 @@ class Binary(http.Controller):
|
||||
@http.route('/web/binary/upload_attachment', type='http', auth="user")
|
||||
@serialize_exception
|
||||
def upload_attachment(self, callback, model, id, ufile):
|
||||
Model = request.session.model('ir.attachment')
|
||||
Model = request.env['ir.attachment']
|
||||
out = """<script language="javascript" type="text/javascript">
|
||||
var win = window.top.window;
|
||||
win.jQuery(win).trigger(%s, %s);
|
||||
</script>"""
|
||||
try:
|
||||
attachment_id = Model.create({
|
||||
attachment = Model.create({
|
||||
'name': ufile.filename,
|
||||
'datas': base64.encodestring(ufile.read()),
|
||||
'datas_fname': ufile.filename,
|
||||
'res_model': model,
|
||||
'res_id': int(id)
|
||||
}, request.context)
|
||||
})
|
||||
args = {
|
||||
'filename': ufile.filename,
|
||||
'mimetype': ufile.content_type,
|
||||
'id': attachment_id
|
||||
'id': attachment.id
|
||||
}
|
||||
except Exception:
|
||||
args = {'error': _("Something horrible happened")}
|
||||
@@ -1088,19 +1088,19 @@ class Action(http.Controller):
|
||||
|
||||
@http.route('/web/action/load', type='json', auth="user")
|
||||
def load(self, action_id, additional_context=None):
|
||||
Actions = request.session.model('ir.actions.actions')
|
||||
Actions = request.env['ir.actions.actions']
|
||||
value = False
|
||||
try:
|
||||
action_id = int(action_id)
|
||||
except ValueError:
|
||||
try:
|
||||
module, xmlid = action_id.split('.', 1)
|
||||
model, action_id = request.session.model('ir.model.data').get_object_reference(module, xmlid)
|
||||
assert model.startswith('ir.actions.')
|
||||
action = request.env.ref(action_id)
|
||||
assert action._name.startswith('ir.actions.')
|
||||
action_id = action.id
|
||||
except Exception:
|
||||
action_id = 0 # force failed read
|
||||
|
||||
base_action = Actions.read([action_id], ['type'], context=request.context)
|
||||
base_action = Actions.browse([action_id]).read(['type'])
|
||||
if base_action:
|
||||
ctx = request.context
|
||||
action_type = base_action[0]['type']
|
||||
@@ -1108,19 +1108,16 @@ class Action(http.Controller):
|
||||
ctx.update({'bin_size': True})
|
||||
if additional_context:
|
||||
ctx.update(additional_context)
|
||||
action = request.session.model(action_type).read([action_id], False, context=ctx)
|
||||
env = request.env(context=ctx)
|
||||
action = env[action_type].browse([action_id]).read()
|
||||
if action:
|
||||
value = clean_action(action[0])
|
||||
return value
|
||||
|
||||
@http.route('/web/action/run', type='json', auth="user")
|
||||
def run(self, action_id):
|
||||
return_action = request.session.model('ir.actions.server').run(
|
||||
[action_id], request.context)
|
||||
if return_action:
|
||||
return clean_action(return_action)
|
||||
else:
|
||||
return False
|
||||
result = request.env['ir.actions.server'].browse([action_id]).run()
|
||||
return clean_action(result) if result else False
|
||||
|
||||
class Export(http.Controller):
|
||||
|
||||
@@ -1195,9 +1192,8 @@ class Export(http.Controller):
|
||||
@http.route('/web/export/namelist', type='json', auth="user")
|
||||
def namelist(self, model, export_id):
|
||||
# TODO: namelist really has no reason to be in Python (although itertools.groupby helps)
|
||||
export = request.session.model("ir.exports").read([export_id])[0]
|
||||
export_fields_list = request.session.model("ir.exports.line").read(
|
||||
export['export_fields'])
|
||||
export = request.env['ir.exports'].browse([export_id]).read()[0]
|
||||
export_fields_list = request.env['ir.exports.line'].browse(export['export_fields']).read()
|
||||
|
||||
fields_data = self.fields_info(
|
||||
model, map(operator.itemgetter('name'), export_fields_list))
|
||||
@@ -1290,19 +1286,16 @@ class ExportFormat(object):
|
||||
def base(self, data, token):
|
||||
params = json.loads(data)
|
||||
model, fields, ids, domain, import_compat = \
|
||||
operator.itemgetter('model', 'fields', 'ids', 'domain',
|
||||
'import_compat')(
|
||||
params)
|
||||
operator.itemgetter('model', 'fields', 'ids', 'domain', 'import_compat')(params)
|
||||
|
||||
Model = request.session.model(model)
|
||||
context = dict(request.context or {}, **params.get('context', {}))
|
||||
ids = ids or Model.search(domain, offset=0, limit=False, order=False, context=context)
|
||||
Model = request.env[model].with_context(**params.get('context', {}))
|
||||
records = Model.browse(ids) or Model.search(domain, offset=0, limit=False, order=False)
|
||||
|
||||
if not request.env[model]._is_an_ordinary_table():
|
||||
if not Model._is_an_ordinary_table():
|
||||
fields = [field for field in fields if field['name'] != 'id']
|
||||
|
||||
field_names = map(operator.itemgetter('name'), fields)
|
||||
import_data = Model.export_data(ids, field_names, self.raw_data, context=context).get('datas',[])
|
||||
import_data = records.export_data(field_names, self.raw_data).get('datas',[])
|
||||
|
||||
if import_compat:
|
||||
columns_headers = field_names
|
||||
@@ -1420,7 +1413,6 @@ class Reports(http.Controller):
|
||||
def index(self, action, token):
|
||||
action = json.loads(action)
|
||||
|
||||
report_srv = request.session.proxy("report")
|
||||
context = dict(request.context)
|
||||
context.update(action["context"])
|
||||
|
||||
@@ -1433,15 +1425,14 @@ class Reports(http.Controller):
|
||||
report_ids = action['datas'].pop('ids')
|
||||
report_data.update(action['datas'])
|
||||
|
||||
report_id = report_srv.report(
|
||||
report_id = dispatch_rpc('report', 'report', [
|
||||
request.session.db, request.session.uid, request.session.password,
|
||||
action["report_name"], report_ids,
|
||||
report_data, context)
|
||||
action["report_name"], report_ids, report_data, context])
|
||||
|
||||
report_struct = None
|
||||
while True:
|
||||
report_struct = report_srv.report_get(
|
||||
request.session.db, request.session.uid, request.session.password, report_id)
|
||||
report_struct = dispatch_rpc('report', 'report_get', [
|
||||
request.session.db, request.session.uid, request.session.password, report_id])
|
||||
if report_struct["state"]:
|
||||
break
|
||||
|
||||
@@ -1454,11 +1445,10 @@ class Reports(http.Controller):
|
||||
report_struct['format'], 'octet-stream')
|
||||
file_name = action.get('name', 'report')
|
||||
if 'name' not in action:
|
||||
reports = request.session.model('ir.actions.report.xml')
|
||||
res_id = reports.search([('report_name', '=', action['report_name']),],
|
||||
context=context)
|
||||
if len(res_id) > 0:
|
||||
file_name = reports.read(res_id[0], ['name'], context)['name']
|
||||
reports = request.env['ir.actions.report.xml']
|
||||
reports = reports.search([('report_name', '=', action['report_name'])])
|
||||
if reports:
|
||||
file_name = reports[0].name
|
||||
else:
|
||||
file_name = action['report_name']
|
||||
file_name = '%s.%s' % (file_name, report_struct['format'])
|
||||
@@ -1473,16 +1463,14 @@ class Reports(http.Controller):
|
||||
class Apps(http.Controller):
|
||||
@http.route('/apps/<app>', auth='user')
|
||||
def get_app_url(self, req, app):
|
||||
act_window_obj = request.session.model('ir.actions.act_window')
|
||||
ir_model_data = request.session.model('ir.model.data')
|
||||
try:
|
||||
action_id = ir_model_data.get_object_reference('base', 'open_module_tree')[1]
|
||||
action = act_window_obj.read(action_id, ['name', 'type', 'res_model', 'view_mode', 'view_type', 'context', 'views', 'domain'])
|
||||
record = request.env.ref('base.open_module_tree')
|
||||
action = record.read(['name', 'type', 'res_model', 'view_mode', 'view_type', 'context', 'views', 'domain'])[0]
|
||||
action['target'] = 'current'
|
||||
except ValueError:
|
||||
action = False
|
||||
try:
|
||||
app_id = ir_model_data.get_object_reference('base', 'module_%s' % app)[1]
|
||||
app_id = request.env.ref('base.module_%s' % app).id
|
||||
except ValueError:
|
||||
app_id = False
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ class Http(models.AbstractModel):
|
||||
|
||||
def webclient_rendering_context(self):
|
||||
return {
|
||||
'menu_data': request.registry['ir.ui.menu'].load_menus(request.cr, request.uid, request.debug, context=request.context),
|
||||
'menu_data': request.env['ir.ui.menu'].load_menus(request.debug),
|
||||
'session_info': json.dumps(self.session_info()),
|
||||
}
|
||||
|
||||
|
||||
@@ -36,10 +36,9 @@ class DiagramView(http.Controller):
|
||||
shape_colour, shape_color_state = shape_spec.split(':')
|
||||
shapes[shape_colour] = shape_color_state
|
||||
|
||||
ir_view = req.session.model('ir.ui.view')
|
||||
graphs = ir_view.graph_get(
|
||||
int(id), model, node, connector, src_node, des_node, label,
|
||||
(140, 180), req.session.context)
|
||||
ir_view = http.request.env['ir.ui.view']
|
||||
graphs = ir_view.graph_get(int(id), model, node, connector, src_node,
|
||||
des_node, label, (140, 180))
|
||||
nodes = graphs['nodes']
|
||||
transitions = graphs['transitions']
|
||||
isolate_nodes = {}
|
||||
@@ -59,10 +58,9 @@ class DiagramView(http.Controller):
|
||||
's_id': transitions[tr][0],
|
||||
'd_id': transitions[tr][1]
|
||||
})
|
||||
connector_tr = req.session.model(connector)
|
||||
connector_ids = connector_tr.search([('id', 'in', list_tr)], context=req.session.context)
|
||||
|
||||
data_connectors =connector_tr.read(connector_ids, connector_fields, req.session.context)
|
||||
connector_model = http.request.env[connector]
|
||||
data_connectors = connector_model.search([('id', 'in', list_tr)]).read(connector_fields)
|
||||
|
||||
for tr in data_connectors:
|
||||
transition_id = str(tr['id'])
|
||||
@@ -78,12 +76,11 @@ class DiagramView(http.Controller):
|
||||
for i, fld in enumerate(connector_fields):
|
||||
t['options'][connector_fields_string[i]] = tr[fld]
|
||||
|
||||
fields = req.session.model('ir.model.fields')
|
||||
field_ids = fields.search([('model', '=', model), ('relation', '=', node)], context=req.session.context)
|
||||
field_data = fields.read(field_ids, ['relation_field'], req.session.context)
|
||||
node_act = req.session.model(node)
|
||||
search_acts = node_act.search([(field_data[0]['relation_field'], '=', id)], context=req.session.context)
|
||||
data_acts = node_act.read(search_acts, invisible_node_fields + visible_node_fields, req.session.context)
|
||||
fields = http.request.env['ir.model.fields']
|
||||
field = fields.search([('model', '=', model), ('relation', '=', node)])
|
||||
node_act = http.request.env[node]
|
||||
search_acts = node_act.search([(field.relation_field, '=', id)])
|
||||
data_acts = search_acts.read(invisible_node_fields + visible_node_fields)
|
||||
|
||||
for act in data_acts:
|
||||
n = nodes.get(str(act['id']))
|
||||
@@ -109,7 +106,7 @@ class DiagramView(http.Controller):
|
||||
for i, fld in enumerate(visible_node_fields):
|
||||
n['options'][node_fields_string[i]] = act[fld]
|
||||
|
||||
_id, name = req.session.model(model).name_get([id], req.session.context)[0]
|
||||
_id, name = http.request.env[model].browse([id]).name_get()[0]
|
||||
return dict(nodes=nodes,
|
||||
conn=connectors,
|
||||
name=name,
|
||||
|
||||
@@ -206,7 +206,7 @@ class WebsiteBlog(http.Controller):
|
||||
|
||||
tag = None
|
||||
if tag_id:
|
||||
tag = request.registry['blog.tag'].browse(request.cr, request.uid, int(tag_id), context=request.context)
|
||||
tag = request.env['blog.tag'].browse(int(tag_id))
|
||||
blog_url = QueryURL('', ['blog', 'tag'], blog=blog_post.blog_id, tag=tag, date_begin=date_begin, date_end=date_end)
|
||||
|
||||
if not blog_post.blog_id.id == blog.id:
|
||||
|
||||
@@ -26,11 +26,9 @@ class TestAPI(common.TransactionCase):
|
||||
def test_00_query(self):
|
||||
""" Build a recordset, and check its contents. """
|
||||
domain = [('name', 'ilike', 'j')]
|
||||
ids = self.registry('res.partner').search(self.cr, self.uid, domain)
|
||||
partners = self.env['res.partner'].search(domain)
|
||||
|
||||
# partners is a collection of browse records corresponding to ids
|
||||
self.assertTrue(ids)
|
||||
# partners is a collection of browse records
|
||||
self.assertTrue(partners)
|
||||
|
||||
# partners and its contents are instance of the model
|
||||
@@ -38,9 +36,6 @@ class TestAPI(common.TransactionCase):
|
||||
for p in partners:
|
||||
self.assertIsRecord(p, 'res.partner')
|
||||
|
||||
self.assertEqual([p.id for p in partners], ids)
|
||||
self.assertEqual(self.env['res.partner'].browse(ids), partners)
|
||||
|
||||
@mute_logger('openerp.models')
|
||||
def test_01_query_offset(self):
|
||||
""" Build a recordset with offset, and check equivalence. """
|
||||
@@ -71,7 +66,8 @@ class TestAPI(common.TransactionCase):
|
||||
@mute_logger('openerp.models')
|
||||
def test_04_query_count(self):
|
||||
""" Test the search method with count=True. """
|
||||
count1 = self.registry('res.partner').search(self.cr, self.uid, [], count=True)
|
||||
self.cr.execute("SELECT COUNT(*) FROM res_partner WHERE active")
|
||||
count1 = self.cr.fetchone()[0]
|
||||
count2 = self.env['res.partner'].search([], count=True)
|
||||
self.assertIsInstance(count1, (int, long))
|
||||
self.assertIsInstance(count2, (int, long))
|
||||
@@ -137,54 +133,6 @@ class TestAPI(common.TransactionCase):
|
||||
self.assertFalse(partner.parent_id.user_id.groups_id)
|
||||
self.assertIsRecordset(partner.parent_id.user_id.groups_id, 'res.groups')
|
||||
|
||||
@mute_logger('openerp.models')
|
||||
def test_10_old_old(self):
|
||||
""" Call old-style methods in the old-fashioned way. """
|
||||
partners = self.env['res.partner'].search([('name', 'ilike', 'j')])
|
||||
self.assertTrue(partners)
|
||||
ids = map(int, partners)
|
||||
|
||||
# call method name_get on partners' model, and check its effect
|
||||
res = partners._model.name_get(self.cr, self.uid, ids)
|
||||
self.assertEqual(len(res), len(ids))
|
||||
self.assertEqual(set(val[0] for val in res), set(ids))
|
||||
|
||||
@mute_logger('openerp.models')
|
||||
def test_20_old_new(self):
|
||||
""" Call old-style methods in the new API style. """
|
||||
partners = self.env['res.partner'].search([('name', 'ilike', 'j')])
|
||||
self.assertTrue(partners)
|
||||
|
||||
# call method name_get on partners itself, and check its effect
|
||||
res = partners.name_get()
|
||||
self.assertEqual(len(res), len(partners))
|
||||
self.assertEqual(set(val[0] for val in res), set(map(int, partners)))
|
||||
|
||||
@mute_logger('openerp.models')
|
||||
def test_25_old_new(self):
|
||||
""" Call old-style methods on records (new API style). """
|
||||
partners = self.env['res.partner'].search([('name', 'ilike', 'j')])
|
||||
self.assertTrue(partners)
|
||||
|
||||
# call method name_get on partner records, and check its effect
|
||||
for p in partners:
|
||||
res = p.name_get()
|
||||
self.assertTrue(isinstance(res, list) and len(res) == 1)
|
||||
self.assertTrue(isinstance(res[0], tuple) and len(res[0]) == 2)
|
||||
self.assertEqual(res[0][0], p.id)
|
||||
|
||||
@mute_logger('openerp.models')
|
||||
def test_30_new_old(self):
|
||||
""" Call new-style methods in the old-fashioned way. """
|
||||
partners = self.env['res.partner'].search([('name', 'ilike', 'j')])
|
||||
self.assertTrue(partners)
|
||||
ids = map(int, partners)
|
||||
|
||||
# call method write on partners' model, and check its effect
|
||||
partners._model.write(self.cr, self.uid, ids, {'active': False})
|
||||
for p in partners:
|
||||
self.assertFalse(p.active)
|
||||
|
||||
@mute_logger('openerp.models')
|
||||
def test_40_new_new(self):
|
||||
""" Call new-style methods in the new API style. """
|
||||
|
||||
@@ -29,19 +29,18 @@ class TestHasGroup(TransactionCase):
|
||||
'groups_id': [(4, group0, 0)]
|
||||
})
|
||||
|
||||
def test_old_api(self):
|
||||
Users = self.registry['res.users']
|
||||
|
||||
def test_env_uid(self):
|
||||
Users = self.env['res.users'].sudo(self.test_user)
|
||||
self.assertTrue(
|
||||
Users.has_group(self.cr, self.test_user.id, self.group0),
|
||||
Users.has_group(self.group0),
|
||||
"the test user should belong to group0"
|
||||
)
|
||||
self.assertFalse(
|
||||
Users.has_group(self.cr, self.test_user.id, self.group1),
|
||||
Users.has_group(self.group1),
|
||||
"the test user should *not* belong to group1"
|
||||
)
|
||||
|
||||
def test_new_api(self):
|
||||
def test_record(self):
|
||||
self.assertTrue(
|
||||
self.test_user.has_group(self.group0),
|
||||
"the test user should belong to group0",
|
||||
|
||||
@@ -354,13 +354,10 @@ class TestApplyInheritanceSpecs(ViewCase):
|
||||
class TestApplyInheritanceWrapSpecs(ViewCase):
|
||||
def setUp(self):
|
||||
super(TestApplyInheritanceWrapSpecs, self).setUp()
|
||||
self.View = self.registry('ir.ui.view')
|
||||
self.base_arch = E.template(E.div(E.p("Content")))
|
||||
|
||||
def apply_spec(self, spec):
|
||||
self.View.apply_inheritance_specs(self.cr, self.uid,
|
||||
self.base_arch,
|
||||
spec, None)
|
||||
self.View.apply_inheritance_specs(self.base_arch, spec, None)
|
||||
|
||||
def test_replace(self):
|
||||
spec = E.xpath(
|
||||
|
||||
@@ -1639,9 +1639,6 @@ class Selection(Field):
|
||||
}
|
||||
|
||||
def __init__(self, selection=Default, string=Default, **kwargs):
|
||||
if callable(selection):
|
||||
from openerp import api
|
||||
selection = api.expected(api.model, selection)
|
||||
super(Selection, self).__init__(selection=selection, string=string, **kwargs)
|
||||
|
||||
@property
|
||||
|
||||
+3
-5
@@ -1161,7 +1161,7 @@ class OpenERPSession(werkzeug.contrib.sessions.Session):
|
||||
:returns: the new context
|
||||
"""
|
||||
assert self.uid, "The user needs to be logged-in to initialize his context"
|
||||
self.context = request.registry.get('res.users').context_get(request.cr, request.uid) or {}
|
||||
self.context = request.env['res.users'].context_get() or {}
|
||||
self.context['uid'] = self.uid
|
||||
self._fix_lang(self.context)
|
||||
return self.context
|
||||
@@ -1433,11 +1433,9 @@ class Response(werkzeug.wrappers.Response):
|
||||
def render(self):
|
||||
""" Renders the Response's template, returns the result
|
||||
"""
|
||||
view_obj = request.registry["ir.ui.view"]
|
||||
uid = self.uid or request.uid or openerp.SUPERUSER_ID
|
||||
env = request.env(user=self.uid or request.uid or openerp.SUPERUSER_ID)
|
||||
self.qcontext['request'] = request
|
||||
return view_obj.render_template(request.cr, uid, self.template,
|
||||
self.qcontext, context=request.context)
|
||||
return env["ir.ui.view"].render_template(self.template, self.qcontext)
|
||||
|
||||
def flatten(self):
|
||||
""" Forces the rendering of the response's template, sets the result
|
||||
|
||||
+6
-20
@@ -44,7 +44,6 @@ import openerp
|
||||
from . import SUPERUSER_ID
|
||||
from . import api
|
||||
from . import tools
|
||||
from .api import Environment
|
||||
from .exceptions import AccessError, MissingError, ValidationError, UserError
|
||||
from .osv.query import Query
|
||||
from .tools import frozendict, lazy_property, ormcache, Collector, LastOrderedSet, OrderedSet
|
||||
@@ -1086,14 +1085,12 @@ class BaseModel(object):
|
||||
|
||||
# old-style constraint methods
|
||||
trans = self.env['ir.translation']
|
||||
cr, uid, context = self.env.args
|
||||
ids = self.ids
|
||||
errors = []
|
||||
for fun, msg, names in self._constraints:
|
||||
for func, msg, names in self._constraints:
|
||||
try:
|
||||
# validation must be context-independent; call ``fun`` without context
|
||||
# validation must be context-independent; call ``func`` without context
|
||||
valid = names and not (set(names) & field_names)
|
||||
valid = valid or fun(self._model, cr, uid, ids)
|
||||
valid = valid or func(self)
|
||||
extra_error = None
|
||||
except Exception, e:
|
||||
_logger.debug('Exception while validating constraint', exc_info=True)
|
||||
@@ -1101,7 +1098,7 @@ class BaseModel(object):
|
||||
extra_error = tools.ustr(e)
|
||||
if not valid:
|
||||
if callable(msg):
|
||||
res_msg = msg(self._model, cr, uid, ids, context=context)
|
||||
res_msg = msg(self)
|
||||
if isinstance(res_msg, tuple):
|
||||
template, params = res_msg
|
||||
res_msg = template % params
|
||||
@@ -4789,13 +4786,6 @@ class BaseModel(object):
|
||||
prefetch[cls._name].update(ids)
|
||||
return records
|
||||
|
||||
@api.v7
|
||||
def browse(self, cr, uid, arg=None, context=None):
|
||||
ids = _normalize_ids(arg)
|
||||
#assert all(isinstance(id, IdType) for id in ids), "Browsing invalid ids: %s" % ids
|
||||
return self._browse(ids, Environment(cr, uid, context or {}))
|
||||
|
||||
@api.v8
|
||||
def browse(self, arg=None, prefetch=None):
|
||||
""" browse([ids]) -> records
|
||||
|
||||
@@ -5411,12 +5401,8 @@ class BaseModel(object):
|
||||
field_vars = RawRecord(self)
|
||||
params = safe_eval("[%s]" % params, global_vars, field_vars, nocopy=True)
|
||||
|
||||
# call onchange method with context when possible
|
||||
args = (self._cr, self._uid, self._origin.ids) + tuple(params)
|
||||
try:
|
||||
method_res = getattr(self._model, method)(*args, context=self._context)
|
||||
except TypeError:
|
||||
method_res = getattr(self._model, method)(*args)
|
||||
# invoke onchange method
|
||||
method_res = getattr(self._origin, method)(*params)
|
||||
process(method_res)
|
||||
|
||||
@api.multi
|
||||
|
||||
@@ -99,10 +99,7 @@ class BaseCase(unittest.TestCase):
|
||||
:raise: ValueError if not found
|
||||
:returns: registered id
|
||||
"""
|
||||
assert "." in xid, "this method requires a fully qualified parameter, in the following form: 'module.identifier'"
|
||||
module, xid = xid.split('.')
|
||||
_, id = self.registry('ir.model.data').get_object_reference(self.cr, self.uid, module, xid)
|
||||
return id
|
||||
return self.browse_ref(xid).id
|
||||
|
||||
def browse_ref(self, xid):
|
||||
""" Returns a record object for the provided
|
||||
@@ -114,8 +111,7 @@ class BaseCase(unittest.TestCase):
|
||||
:returns: :class:`~openerp.models.BaseModel`
|
||||
"""
|
||||
assert "." in xid, "this method requires a fully qualified parameter, in the following form: 'module.identifier'"
|
||||
module, xid = xid.split('.')
|
||||
return self.registry('ir.model.data').get_object(self.cr, self.uid, module, xid)
|
||||
return self.env.ref(xid)
|
||||
|
||||
@contextmanager
|
||||
def _assertRaises(self, exception):
|
||||
@@ -276,8 +272,8 @@ class HttpCase(TransactionCase):
|
||||
return
|
||||
|
||||
db = get_db_name()
|
||||
Users = self.registry['res.users']
|
||||
uid = Users.authenticate(db, user, password, None)
|
||||
uid = self.registry['res.users'].authenticate(db, user, password, None)
|
||||
env = api.Environment(self.cr, uid, {})
|
||||
|
||||
# self.session.authenticate(db, user, password, uid=uid)
|
||||
# OpenERPSession.authenticate accesses the current request, which we
|
||||
@@ -288,7 +284,7 @@ class HttpCase(TransactionCase):
|
||||
session.uid = uid
|
||||
session.login = user
|
||||
session.password = password
|
||||
session.context = Users.context_get(self.cr, uid) or {}
|
||||
session.context = env['res.users'].context_get() or {}
|
||||
session.context['uid'] = uid
|
||||
session._fix_lang(session.context)
|
||||
|
||||
|
||||
@@ -188,11 +188,10 @@ def _eval_xml(self, node, env):
|
||||
return_val = _eval_xml(self, n, env)
|
||||
if return_val is not None:
|
||||
args.append(return_val)
|
||||
model = env[node.get('model', '')]._model
|
||||
model = env[node.get('model', '')]
|
||||
method = node.get('name')
|
||||
# this one still depends on the old API
|
||||
res = getattr(model, method)(env.cr, env.uid, *args)
|
||||
return res
|
||||
return openerp.api.call_kw(model, method, args, {})
|
||||
elif node.tag == "test":
|
||||
return node.text
|
||||
|
||||
|
||||
@@ -100,13 +100,10 @@ def try_report_action(cr, uid, action_id, active_model=None, active_ids=None,
|
||||
if '.' in action_id:
|
||||
our_module = action_id.split('.', 1)[0]
|
||||
|
||||
if context is None:
|
||||
context = {}
|
||||
else:
|
||||
context = context.copy() # keep it local
|
||||
context = dict(context or {})
|
||||
# TODO context fill-up
|
||||
|
||||
registry = openerp.registry(cr.dbname)
|
||||
env = openerp.api.Environment(cr, uid, context)
|
||||
|
||||
def log_test(msg, *args):
|
||||
_test_logger.info(" - " + msg, *args)
|
||||
@@ -122,30 +119,33 @@ def try_report_action(cr, uid, action_id, active_model=None, active_ids=None,
|
||||
|
||||
if isinstance(action_id, basestring):
|
||||
if '.' in action_id:
|
||||
act_module, act_xmlid = action_id.split('.', 1)
|
||||
_, act_xmlid = action_id.split('.', 1)
|
||||
else:
|
||||
if not our_module:
|
||||
raise ValueError('You cannot only specify action_id "%s" without a module name' % action_id)
|
||||
act_module = our_module
|
||||
act_xmlid = action_id
|
||||
act_model, act_id = registry['ir.model.data'].get_object_reference(cr, uid, act_module, act_xmlid)
|
||||
action_id = '%s.%s' % (our_module, action_id)
|
||||
action = env.ref(action_id)
|
||||
act_model, act_id = action._name, action.id
|
||||
else:
|
||||
assert isinstance(action_id, (long, int))
|
||||
act_model = 'ir.action.act_window' # assume that
|
||||
act_id = action_id
|
||||
act_xmlid = '<%s>' % act_id
|
||||
|
||||
def _exec_action(action, datas, context):
|
||||
def _exec_action(action, datas, env):
|
||||
# taken from client/modules/action/main.py:84 _exec_action()
|
||||
if isinstance(action, bool) or 'type' not in action:
|
||||
return
|
||||
# Updating the context : Adding the context of action in order to use it on Views called from buttons
|
||||
context = dict(env.context)
|
||||
if datas.get('id',False):
|
||||
context.update( {'active_id': datas.get('id',False), 'active_ids': datas.get('ids',[]), 'active_model': datas.get('model',False)})
|
||||
context1 = action.get('context', {})
|
||||
if isinstance(context1, basestring):
|
||||
context1 = safe_eval(context1, context.copy())
|
||||
context1 = safe_eval(context1, dict(context))
|
||||
context.update(context1)
|
||||
env = env(context=context)
|
||||
if action['type'] in ['ir.actions.act_window', 'ir.actions.submenu']:
|
||||
for key in ('res_id', 'res_model', 'view_type', 'view_mode',
|
||||
'limit', 'search_view', 'auto_search', 'search_view_id'):
|
||||
@@ -167,11 +167,11 @@ def try_report_action(cr, uid, action_id, active_model=None, active_ids=None,
|
||||
log_test("will emulate a %s view: %s#%s",
|
||||
action['view_type'], datas['res_model'], view_id or '?')
|
||||
|
||||
view_res = registry[datas['res_model']].fields_view_get(cr, uid, view_id, action['view_type'], context)
|
||||
view_res = env[datas['res_model']].fields_view_get(view_id, action['view_type'])
|
||||
assert view_res and view_res.get('arch'), "Did not return any arch for the view"
|
||||
view_data = {}
|
||||
if view_res.get('fields',{}).keys():
|
||||
view_data = registry[datas['res_model']].default_get(cr, uid, view_res['fields'].keys(), context)
|
||||
if view_res.get('fields'):
|
||||
view_data = env[datas['res_model']].default_get(list(view_res['fields']))
|
||||
if datas.get('form'):
|
||||
view_data.update(datas.get('form'))
|
||||
if wiz_data:
|
||||
@@ -212,11 +212,12 @@ def try_report_action(cr, uid, action_id, active_model=None, active_ids=None,
|
||||
button_weight += 10
|
||||
string = button.getAttribute('string') or '?%s' % len(buttons)
|
||||
|
||||
buttons.append( { 'name': button.getAttribute('name'),
|
||||
'string': string,
|
||||
'type': button.getAttribute('type'),
|
||||
'weight': button_weight,
|
||||
})
|
||||
buttons.append({
|
||||
'name': button.getAttribute('name'),
|
||||
'string': string,
|
||||
'type': button.getAttribute('type'),
|
||||
'weight': button_weight,
|
||||
})
|
||||
except Exception, e:
|
||||
_logger.warning("Cannot resolve the view arch and locate the buttons!", exc_info=True)
|
||||
raise AssertionError(e.args[0])
|
||||
@@ -224,7 +225,7 @@ def try_report_action(cr, uid, action_id, active_model=None, active_ids=None,
|
||||
if not datas['res_id']:
|
||||
# it is probably an orm_memory object, we need to create
|
||||
# an instance
|
||||
datas['res_id'] = registry[datas['res_model']].create(cr, uid, view_data, context)
|
||||
datas['res_id'] = env[datas['res_model']].create(view_data).id
|
||||
|
||||
if not buttons:
|
||||
raise AssertionError("view form doesn't have any buttons to press!")
|
||||
@@ -241,11 +242,12 @@ def try_report_action(cr, uid, action_id, active_model=None, active_ids=None,
|
||||
continue
|
||||
if b['type'] == 'object':
|
||||
#there we are! press the button!
|
||||
fn = getattr(registry[datas['res_model']], b['name'])
|
||||
if not fn:
|
||||
rec = env[datas['res_model']].browse(datas['res_id'])
|
||||
func = getattr(rec, b['name'], None)
|
||||
if not func:
|
||||
_logger.error("The %s model doesn't have a %s attribute!", datas['res_model'], b['name'])
|
||||
continue
|
||||
res = fn(cr, uid, [datas['res_id'],], context)
|
||||
res = func()
|
||||
break
|
||||
else:
|
||||
_logger.warning("in the \"%s\" form, the \"%s\" button has unknown type %s",
|
||||
@@ -269,8 +271,8 @@ def try_report_action(cr, uid, action_id, active_model=None, active_ids=None,
|
||||
raise Exception("Cannot handle action of type %s" % act_model)
|
||||
|
||||
log_test("will be using %s action %s #%d", act_model, act_xmlid, act_id)
|
||||
action = registry[act_model].read(cr, uid, [act_id], context=context)[0]
|
||||
assert action, "Could not read action %s[%s]" %(act_model, act_id)
|
||||
action = env[act_model].browse(act_id).read()[0]
|
||||
assert action, "Could not read action %s[%s]" % (act_model, act_id)
|
||||
loop = 0
|
||||
while action:
|
||||
loop += 1
|
||||
@@ -279,7 +281,7 @@ def try_report_action(cr, uid, action_id, active_model=None, active_ids=None,
|
||||
_logger.info("Passed %d loops, giving up", loop)
|
||||
raise Exception("Too many loops at action")
|
||||
log_test("it is an %s action at loop #%d", action.get('type', 'unknown'), loop)
|
||||
result = _exec_action(action, datas, context)
|
||||
result = _exec_action(action, datas, env)
|
||||
if not isinstance(result, dict):
|
||||
break
|
||||
datas = result.get('datas', {})
|
||||
|
||||
@@ -678,14 +678,13 @@ class YamlInterpreter(object):
|
||||
function, params = node.items()[0]
|
||||
if self.isnoupdate(function) and self.mode != 'init':
|
||||
return
|
||||
model = self.env[function.model]._model
|
||||
model = self.env[function.model]
|
||||
if function.eval:
|
||||
args = self.process_eval(function.eval)
|
||||
else:
|
||||
args = self._eval_params(function.model, params)
|
||||
method = function.name
|
||||
# this one still depends on the old API
|
||||
getattr(model, method)(self.cr, self.uid, *args)
|
||||
return openerp.api.call_kw(model, function.name, args, {})
|
||||
|
||||
def _set_group_values(self, node, values):
|
||||
if node.groups:
|
||||
|
||||
@@ -32,10 +32,10 @@ class Environment(dict):
|
||||
self.model = record.model
|
||||
self.id = record.id
|
||||
self.ids = [record.id]
|
||||
self.obj = openerp.registry(self.cr.dbname)[self.model]
|
||||
|
||||
def __getitem__(self, key):
|
||||
records = self.obj.browse(self.cr, self.uid, self.ids)
|
||||
env = openerp.api.Environment(self.cr, self.uid, {})
|
||||
records = env[self.model].browse(self.ids)
|
||||
if hasattr(records, key):
|
||||
return getattr(records, key)
|
||||
else:
|
||||
@@ -282,10 +282,9 @@ class WorkflowItem(object):
|
||||
'active_id': self.record.id,
|
||||
'active_ids': [self.record.id]
|
||||
}
|
||||
|
||||
ir_actions_server = openerp.registry(self.session.cr.dbname)['ir.actions.server']
|
||||
result = ir_actions_server.run(self.session.cr, self.session.uid, [activity['action_id']], context)
|
||||
|
||||
env = openerp.api.Environment(self.session.cr, self.session.uid, context)
|
||||
action = env['ir.actions.server'].browse(activity['action_id'])
|
||||
result = action.run()
|
||||
return result
|
||||
|
||||
def wkf_expr_execute(self, activity):
|
||||
@@ -307,9 +306,9 @@ class WorkflowItem(object):
|
||||
return False
|
||||
|
||||
if self.session.uid != openerp.SUPERUSER_ID and transition['group_id']:
|
||||
registry = openerp.registry(self.session.cr.dbname)
|
||||
user_groups = registry['res.users'].read(self.session.cr, self.session.uid, [self.session.uid], ['groups_id'])[0]['groups_id']
|
||||
if transition['group_id'] not in user_groups:
|
||||
env = openerp.api.Environment(self.session.cr, self.session.uid, {})
|
||||
user_groups = env.user.groups_id
|
||||
if transition['group_id'] not in user_groups.ids:
|
||||
return False
|
||||
|
||||
return self.wkf_expr_eval_expr(transition['condition'])
|
||||
|
||||
Reference in New Issue
Block a user