desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Hide Max User Field when the env var to hide the field is set'
| @api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
| res = super(ResUsers, self).fields_view_get(view_id, view_type, toolbar, submenu)
if THRESHOLD_HIDE:
doc = etree.XML(res['arch'])
for node in doc.xpath("//group[@name='user_threshold']"):
node.getparent().remove(node)
res['arch'] = etree.tostring(doc, pretty_print=True)
return res
|
'Override write to verify that membership of the Threshold Manager
group is not able to be set by users outside that group'
| @api.multi
def write(self, vals):
| thold_group = self.env.ref(THRESHOLD_MANAGER, raise_if_not_found=False)
if thold_group:
user_is_manager = self.env.user.has_group(THRESHOLD_MANAGER)
if (vals.get('threshold_exempt') and (not user_is_manager)):
raise AccessError(_('You must be a member of the `User Threshold Manager` group to grant threshold exemptions.'))
is_add_group = vals.get(('in_group_%s' % thold_group.id))
if (is_add_group and (not user_is_manager)):
raise AccessError(_('You must be a member of the `User Threshold Manager` group to grant access to it.'))
return super(ResUsers, self).write(vals)
|
'Hide Max User Field when the env var to hide the field is set'
| @api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
| res = super(ResCompany, self).fields_view_get(view_id, view_type, toolbar, submenu)
if THRESHOLD_HIDE:
doc = etree.XML(res['arch'])
for node in doc.xpath("//field[@name='max_users']"):
node.getparent().remove(node)
res['arch'] = etree.tostring(doc, pretty_print=True)
return res
|
'Override to disallow manipulation of the user threshold parameter
when the user does not have the right access'
| @api.multi
def write(self, vals):
| is_manager = self.env.user.has_group(THRESHOLD_MANAGER)
if (vals.get('max_users') and (not is_manager)):
raise AccessError(_('You must be a member of the `User Threshold Manager` to set this parameter'))
return super(ResCompany, self).write(vals)
|
'Override to disallow deletion of the user threshold parameter
when the user does not have the right access'
| @api.multi
def unlink(self):
| for rec in self.filtered((lambda r: (r.key == MAX_DB_USER_PARAM))):
if (not self.env.user.has_group(THRESHOLD_MANAGER)):
raise AccessError(_('You must be a member of the `User Threshold Manager` to delete this parameter'))
return super(IrConfigParameter, self).unlink()
|
'Override to disallow manipulation of the user threshold parameter
when the user does not have the right access'
| @api.multi
def write(self, vals):
| for rec in self.filtered((lambda r: (r.key == MAX_DB_USER_PARAM))):
if (not self.env.user.has_group(THRESHOLD_MANAGER)):
raise AccessError(_('You must be a member of the `User Threshold Manager` to set this parameter'))
return super(IrConfigParameter, self).write(vals)
|
'It should verify that setting THRESHOLD_HIDE removes the parameter
from the view'
| def test_fields_view_get(self):
| import odoo.addons.user_threshold.models.res_company as mdl
mdl.THRESHOLD_HIDE = True
view = self.env.ref('user_threshold.view_company_form')
c = self.env['res.company'].browse(1)
ret = c.fields_view_get(view.id)
doc = etree.XML(ret['arch'])
self.assertEquals(doc.xpath("//field[@name='max_users']"), [])
|
'It should restrict the max users parameter to Threshold Managers'
| def test_can_write_max_users(self):
| u = self._create_test_user()
self._add_user_to_group(u)
c = self.env['res.company'].browse(1)
res = 10
c.sudo(u.id).write({'max_users': res})
self.assertEquals(c.max_users, res)
|
'It should restrict the max users parameter to Threshold Managers'
| def test_cannot_write_max_users(self):
| u = self._create_test_user()
c = self.env['res.company'].browse(1)
with self.assertRaises(AccessError):
c.sudo(u.id).write({'max_users': 10})
|
'Create a user for testing'
| def _create_test_user(self):
| user = self.env.ref('base.user_demo').copy()
rand_name = ''.join([random.choice(string.ascii_letters) for n in xrange(10)])
user.write({'login': rand_name})
return user
|
'Add a given user Record to the threshold manager group'
| def _add_user_to_group(self, user):
| th_group = self.env.ref('user_threshold.group_threshold_manager')
system_group = self.env.ref('base.group_system')
user.write({('in_group_%s' % th_group.id): True, ('in_group_%s' % system_group.id): True})
|
'It should restrict the user count in copy() as prescribed by the
global threshold parameter'
| def test_copy_global(self):
| self.env['ir.config_parameter'].set_param(MAX_DB_USER_PARAM, 3)
self._create_test_user()
with self.assertRaises(ValidationError):
self._create_test_user()
|
'It should restrict the user count as prescribed by the global
threshold parameter'
| def test_create_global(self):
| self.env['ir.config_parameter'].set_param(MAX_DB_USER_PARAM, 3)
self._create_test_user()
with self.assertRaises(ValidationError):
self.env['res.users'].create({'login': 'Derp Derpington', 'email': '[email protected]', 'notify_email': 'always'})
|
'It should restrict the user count in copy() as prescribed by the
companies threshold parameter'
| def test_copy_company(self):
| c = self.env['res.company'].browse(1)
c.max_users = 3
self._create_test_user()
with self.assertRaises(ValidationError):
self._create_test_user()
|
'It should restrict the user count as prescribed by the companies
threshold parameter'
| def test_create_company(self):
| c = self.env['res.company'].browse(1)
c.max_users = 3
self._create_test_user()
with self.assertRaises(ValidationError):
self.env['res.users'].create({'login': 'Derp Derpington', 'email': '[email protected]', 'notify_email': 'always'})
|
'It should verify that setting THRESHOLD_HIDE removes the parameter
from the view'
| def test_fields_view_get(self):
| import odoo.addons.user_threshold.models.res_users as mdl
mdl.THRESHOLD_HIDE = True
view = self.env.ref('user_threshold.view_users_form')
u = self._create_test_user()
ret = u.fields_view_get(view.id)
doc = etree.XML(ret['arch'])
self.assertEquals(doc.xpath("//group[@name='user_threshold']"), [])
|
'It should restrict the threshold exempt parameter to Threshold
Managers'
| def test_cannot_write_exempt(self):
| u = self._create_test_user()
tu = self._create_test_user()
with self.assertRaises(AccessError):
tu.sudo(u.id).write({'threshold_exempt': True})
|
'It should restrict the threshold exempt parameter to Threshold
Managers'
| def test_can_write_exempt(self):
| u = self._create_test_user()
self._add_user_to_group(u)
tu = self._create_test_user()
tu.sudo(u.id).write({'threshold_exempt': True})
self.assertEquals(tu.threshold_exempt, True)
|
'It should restrict additions to the Threshold Managers to users in
that group'
| def test_cannot_write_group(self):
| u = self._create_test_user()
u.write({('in_group_%s' % self.env.ref('base.group_erp_manager').id): True})
tu = self._create_test_user()
th_group = self.env.ref('user_threshold.group_threshold_manager')
with self.assertRaises(AccessError):
tu.sudo(u.id).write({('in_group_%s' % th_group.id): True})
|
'It should restrict additions to the Threshold Managers to users in
that group'
| def test_can_write_group(self):
| u = self._create_test_user()
self._add_user_to_group(u)
tu = self._create_test_user()
th_group = self.env.ref('user_threshold.group_threshold_manager')
tu.sudo(u.id).write({('in_group_%s' % th_group.id): True})
self.assertEquals(tu.has_group('user_threshold.group_threshold_manager'), True)
|
'It should restrict membership additions to Threshold Managers to
pre-existing members of that group'
| def test_can_write_max_users(self):
| u = self._create_test_user()
u.write({('in_group_%s' % self.env.ref('base.group_erp_manager').id): True})
g = self.env.ref('user_threshold.group_threshold_manager')
with self.assertRaises(AccessError):
g.sudo(u.id).write({'users': self.env.ref('base.user_demo').id})
|
'It should restrict membership additions to Threshold Managers to
pre-existing members of that group'
| def test_cannot_write_max_users(self):
| u = self._create_test_user()
self._add_user_to_group(u)
g = self.env.ref('user_threshold.group_threshold_manager')
demo_user = self.env.ref('base.user_demo')
g.sudo(u.id).write({'users': [(4, [demo_user.id])]})
self.assertTrue((demo_user.id in g.users.ids))
|
'It should test that users in the Threshold Manager group can
update the parameter'
| def test_can_set(self):
| mdl = self.env['ir.config_parameter']
u = self._create_test_user()
self._add_user_to_group(u)
exp = '20'
mdl.sudo(u.id).set_param(MAX_DB_USER_PARAM, exp)
self.assertEquals(mdl.get_param(MAX_DB_USER_PARAM), exp)
|
'It should test that users NOT in the Threshold Manager group
cannot alter the parameter'
| def test_cannot_set(self):
| u = self._create_test_user()
with self.assertRaises(AccessError):
self.env['ir.config_parameter'].sudo(u.id).set_param(MAX_DB_USER_PARAM, 20)
|
'It should test that users in the Threshold Manager group can
unlink the Threshold Param'
| def test_can_unlink(self):
| u = self._create_test_user()
self._add_user_to_group(u)
param = self._get_param()
self.assertTrue(param.sudo(u.id).unlink())
|
'It should test that users outside the Threshold Manager group
cannot unlink the Threshold Param'
| def test_cannot_unlink(self):
| u = self._create_test_user()
param = self._get_param()
system_group = self.env.ref('base.group_system')
u.write({('in_group_%s' % system_group.id): True})
with self.assertRaises(AccessError):
param.sudo(u.id).unlink()
|
'It should test that users in the Threshold Manager group can
write the Threshold Param'
| def test_can_write(self):
| u = self._create_test_user()
self._add_user_to_group(u)
param = self._get_param()
res = '10'
param.sudo(u.id).write({'value': res})
self.assertEquals(param.value, res)
|
'It should test that users outside the Threshold Manager group
cannot write the Threshold Param'
| def test_cannot_write(self):
| u = self._create_test_user()
system_group = self.env.ref('base.group_system')
access_group = self.env.ref('base.group_erp_manager')
u.write({('in_group_%s' % system_group.id): True, ('in_group_%s' % access_group.id): True})
param = self._get_param()
with self.assertRaises(AccessError):
param.sudo(u.id).write({'value': '10'})
|
'Send a email to the admin of the system and / or the user
to inform passkey use.'
| @api.model
def _send_email_passkey(self, user_id):
| mail_obj = self.env['mail.mail'].sudo()
icp_obj = self.env['ir.config_parameter']
admin_user = self.browse(SUPERUSER_ID)
login_user = self.browse(user_id)
send_to_admin = safe_eval(icp_obj.get_param('auth_admin_passkey.send_to_admin'))
send_to_user = safe_eval(icp_obj.get_param('auth_admin_passkey.send_to_user'))
mails = []
if (send_to_admin and admin_user.email):
mails.append({'email': admin_user.email, 'lang': admin_user.lang})
if (send_to_user and login_user.email):
mails.append({'email': login_user.email, 'lang': login_user.lang})
for mail in mails:
subject = _('Passkey used')
body = (_("Admin user used his passkey to login with '%s'.\n\n\n\nTechnicals informations belows : \n\n- Login date : %s\n\n") % (login_user.login, datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
mail_obj.create({'email_to': mail['email'], 'subject': subject, 'body_html': ('<pre>%s</pre>' % body)})
|
'Send an email to the admin user to inform that
another user has the same password as him.'
| @api.model
def _send_email_same_password(self, login):
| mail_obj = self.env['mail.mail'].sudo()
admin_user = self.browse(SUPERUSER_ID)
if admin_user.email:
mail_obj.create({'email_to': admin_user.email, 'subject': _('[WARNING] Odoo Security Risk'), 'body_html': (_("<pre>User with login '%s' has the same password as you.</pre>") % login)})
|
'Despite using @api.model decorator, this method
is always called by a res.users record'
| @api.model
def check_credentials(self, password):
| try:
super(ResUsers, self).check_credentials(password)
if (self._uid != SUPERUSER_ID):
try:
super(ResUsers, self).sudo().check_credentials(password)
self._send_email_same_password(self.login)
except exceptions.AccessDenied:
pass
except exceptions.AccessDenied:
if (self._uid == SUPERUSER_ID):
raise
user = self.sudo().search([('id', '=', self._uid)])
if (not user):
raise
try:
super(ResUsers, self).sudo().check_credentials(password)
self._send_email_passkey(self._uid)
except exceptions.AccessDenied:
raise
|
'This test cannot pass because in some way the the _uid of
passkey_user is equal to admin one so when entering the
original check_credentials() method, it raises an exception'
| def test_03_normal_login_passkey_succeed(self):
| try:
self.passkey_user.check_credentials('passkey')
except exceptions.AccessDenied:
pass
|
'[Bug #1319391]
Test the correct behaviour of login with \'bad_login\' / \'admin\''
| def test_06_passkey_login_passkey_succeed(self):
| res = self.ru_obj.authenticate(self.db, 'bad_login', 'admin', {})
self.assertFalse(res)
|
'Get an HTML LXML document.'
| def html_doc(self, response):
| return html.fromstring(response.data)
|
'Get a valid CSRF token.'
| def csrf_token(self, response):
| doc = self.html_doc(response)
return doc.xpath("//input[@name='csrf_token']")[0].get('value')
|
'Overload _login to lowercase the `login` before passing to the
super'
| @classmethod
def _login(cls, db, login, password):
| login = login.lower()
return super(ResUsers, cls)._login(db, login, password)
|
'Overload create to lowercase login'
| @api.model
def create(self, vals):
| vals['login'] = vals.get('login', '').lower()
return super(ResUsers, self).create(vals)
|
'Overload write to lowercase login'
| @api.multi
def write(self, vals):
| if vals.get('login'):
vals['login'] = vals['login'].lower()
return super(ResUsers, self).write(vals)
|
'It should enerate a new record to test with'
| def _new_record(self):
| partner_id = self.env['res.partner'].create(self.partner_vals)
self.vals['partner_id'] = partner_id.id
return self.model_obj.create(self.vals)
|
'It should verify the login is set to lowercase on create'
| def test_login_is_lowercased_on_create(self):
| rec_id = self._new_record()
self.assertEqual(self.login.lower(), rec_id.login, 'Login was not lowercased when saved to db.')
|
'It should verify the login is set to lowercase on write'
| def test_login_is_lowercased_on_write(self):
| rec_id = self._new_record()
rec_id.write({'login': self.login})
self.assertEqual(self.login.lower(), rec_id.login, 'Login was not lowercased when saved to db.')
|
'It should verify the login is set to lowercase on login'
| def test_login_login_is_lowercased(self):
| rec_id = self._new_record()
self.env.cr.commit()
res_id = self.model_obj._login(self.env.registry.db_name, self.login.upper(), 'password')
with api.Environment.manage():
with registry(self.env.registry.db_name).cursor() as new_cr:
new_cr.execute(("DELETE FROM res_users WHERE login='%s'" % self.login.lower()))
new_cr.commit()
self.assertEqual(rec_id.id, res_id, 'Login with with uppercase chars was not successful')
|
'Extract text from an HTML field in a generator.
:param str html_content:
HTML contents from where to extract the text.
:param int max_words:
Maximum amount of words allowed in the resulting string.
:param int max_chars:
Maximum amount of characters allowed in the resulting string. If
you apply this limit, beware that the last word could get cut in an
unexpected place.
:param str ellipsis:
Character(s) to be appended to the end of the resulting string if
it gets truncated after applying limits set in :param:`max_words`
or :param:`max_chars`. If you want nothing applied, just set an
empty string.
:param bool fail:
If ``True``, exceptions will be raised. Otherwise, an empty string
will be returned on failure.'
| @api.model
def text_from_html(self, html_content, max_words=None, max_chars=None, ellipsis=u'\u2026', fail=False):
| try:
doc = html.fromstring(html_content)
except (TypeError, etree.XMLSyntaxError, etree.ParserError):
if fail:
raise
else:
_logger.exception('Failure parsing this HTML:\n%s', html_content)
return ''
words = u''.join(doc.xpath('//text()')).split()
suffix = (max_words and (len(words) > max_words))
if max_words:
words = words[:max_words]
text = u' '.join(words)
suffix = (suffix or (max_chars and (len(text) > max_chars)))
if max_chars:
text = text[:(max_chars - (len(ellipsis) if suffix else 0))].strip()
if suffix:
text += ellipsis
return text
|
'Text gets correctly extracted.'
| def test_excerpts(self):
| html = u'\n <html>\n <body>\n <div class="this should not appear">\n <h1>I\'m a title</h1>\n <p>I\'m a paragraph</p>\n <small>\xa1Pues yo soy espa\xf1ol!</small>\n </div>\n </body>\n </html>\n '
self.assertEqual(self.text_from_html(html), u"I'm a title I'm a paragraph \xa1Pues yo soy espa\xf1ol!")
self.assertEqual(self.text_from_html(html, 8), u"I'm a title I'm a paragraph \xa1Pues yo\u2026")
self.assertEqual(self.text_from_html(html, 8, 31), u"I'm a title I'm a paragraph \xa1P\u2026")
self.assertEqual(self.text_from_html(html, 7, ellipsis=''), u"I'm a title I'm a paragraph \xa1Pues")
|
'Empty HTML handled correctly.'
| @mute_logger(ir_fields_converter.__name__)
def test_empty_html(self):
| self.assertEqual(self.text_from_html(''), '')
with self.assertRaises(etree.XMLSyntaxError):
self.text_from_html('', fail=True)
|
'``False`` HTML handled correctly.'
| @mute_logger(ir_fields_converter.__name__)
def test_false_html(self):
| self.assertEqual(self.text_from_html(False), '')
with self.assertRaises(TypeError):
self.text_from_html(False, fail=True)
|
'Bad HTML handled correctly.'
| @mute_logger(ir_fields_converter.__name__)
def test_bad_html(self):
| self.assertEqual(self.text_from_html('<<bad>'), '')
with self.assertRaises(etree.ParserError):
self.text_from_html('<<bad>', fail=True)
|
'Run the process for each attachment metadata'
| @api.multi
def run(self):
| for attachment in self:
with api.Environment.manage():
with odoo.registry(self.env.cr.dbname).cursor() as new_cr:
new_env = api.Environment(new_cr, self.env.uid, self.env.context)
attach = attachment.with_env(new_env)
try:
attach._run()
except Exception as e:
attach.env.cr.rollback()
_logger.exception(e)
attach.write({'state': 'failed', 'state_message': e})
attach.env.cr.commit()
else:
vals = {'state': 'done', 'sync_date': fields.Datetime.now()}
attach.write(vals)
attach.env.cr.commit()
return True
|
'Manually set to done'
| @api.multi
def set_done(self):
| message = ('Manually set to done by %s' % self.env.user.name)
self.write({'state_message': message, 'state': 'done'})
|
'Test run_attachment_metadata_scheduler to ensure set state to done'
| def test_attachment_metadata(self):
| self.assertEqual(self.attachment.state, 'pending')
self.ir_attachment_metadata.run_attachment_metadata_scheduler()
self.env.invalidate_all()
with odoo.registry(self.env.cr.dbname).cursor() as new_cr:
new_env = api.Environment(new_cr, self.env.uid, self.env.context)
attach = self.attachment.with_env(new_env)
self.assertEqual(attach.state, 'done')
|
'Test set_done manually'
| def test_set_done(self):
| self.assertEqual(self.attachment.state, 'pending')
self.attachment.set_done()
self.assertEqual(self.attachment.state, 'done')
|
'Get best match of current default lang.
:param str lang:
If a language in the form of "en_US" is supplied, it will have the
highest priority.
:param bool failure_safe:
If ``False`` and the best matched language is not found installed,
an exception will be raised. Otherwise, the first installed
language found in the DB will be returned.'
| @api.model
@api.returns('self')
def best_match(self, lang=None, failure_safe=True):
| first_installed = self.search([('active', '=', True)], limit=1)
if (not lang):
lang = ((self.ids and self[0].code) or self.env.context.get('lang') or self.env.user.lang or first_installed.code)
record = self.search([('code', '=', lang)])
try:
record.ensure_one()
except ValueError:
if (not failure_safe):
raise UserError((_('Best matched language (%s) not found.') % lang))
else:
record = first_installed
return record
|
'Convert a datetime field to lang\'s default format.
:type value: `str`, `float` or `datetime.datetime`
:param value:
Datetime that will be formatted to the user\'s preferred format.
:param str lang:
See :param:`lang` from :meth:`~.best_match`.
:param bool failure_safe:
See :param:`failure_safe` from :meth:`~.best_match`.
:param str template:
Will be used to format :param:`value`. If it is one of the special
constants :const:`MODE_DATETIME`, :const:`MODE_DATE` or
:const:`MODE_TIME`, it will use the :param:`lang`\'s default
template for that mode.
:param str separator:
Only used when :param:`template` is :const:`MODE_DATETIME`, as the
separator between the date and time parts.'
| @api.model
def datetime_formatter(self, value, lang=None, template=MODE_DATETIME, separator=' ', failure_safe=True):
| lang = self.best_match(lang)
if (template in {MODE_DATETIME, MODE_DATE, MODE_TIME}):
defaults = []
if ('DATE' in template):
defaults.append((lang.date_format or DEFAULT_SERVER_DATE_FORMAT))
if ('TIME' in template):
defaults.append((lang.time_format or DEFAULT_SERVER_TIME_FORMAT))
template = separator.join(defaults)
if isinstance(value, (str, unicode)):
try:
value = fields.Datetime.from_string(value)
except ValueError:
value = datetime.strptime(value, DEFAULT_SERVER_TIME_FORMAT)
elif isinstance(value, float):
if (value >= 24):
template = template.replace('%H', ('%d' % value))
value = (datetime.min + timedelta(hours=value)).time()
return value.strftime(template)
|
'Format a datetime.'
| def test_datetime(self):
| self.format = ('%s %s' % (self.d_fmt, self.t_fmt))
self.kwargs = {'template': MODE_DATETIME}
|
'Format a date.'
| def test_date(self):
| self.format = self.d_fmt
self.kwargs = {'template': MODE_DATE}
self.dt = self.dt.date()
|
'Format times, including float ones.'
| def test_time(self):
| self.format = self.t_fmt
self.kwargs = {'template': MODE_TIME}
self.dt = self.dt.time()
for n in range(50):
n = (n + random())
fmt = self.format.replace('%H', ('%02d' % n))
time = (datetime.datetime.min + datetime.timedelta(hours=n)).time()
self.assertEqual(time.strftime(fmt), self.rl.datetime_formatter(n, **self.kwargs))
|
'Format a datetime with a custom separator.'
| def test_custom_separator(self):
| sep = 'T'
self.format = ('%s%s%s' % (self.d_fmt, sep, self.t_fmt))
self.kwargs = {'template': MODE_DATETIME, 'separator': sep}
|
'When an explicit lang is used.'
| def test_explicit(self):
| for lang in self.langs:
self.assertEqual(self.rl.best_match(lang).code, lang)
|
'When called from a ``res.lang`` record.'
| def test_record(self):
| rl = self.rl.with_context(lang='it_IT')
rl.env.user.lang = 'pt_PT'
for lang in self.langs:
self.assertEqual(rl.search([('code', '=', lang)]).best_match().code, lang)
|
'When called with a lang in context.'
| def test_context(self):
| self.env.user.lang = 'pt_PT'
for lang in self.langs:
self.assertEqual(self.rl.with_context(lang=lang).best_match().code, lang)
|
'When lang not specified in context.'
| def test_user(self):
| for lang in self.langs:
self.env.user.lang = lang
self.assertEqual(self.rl.with_context(lang=False).best_match().code, lang)
self.assertEqual(self.rl.with_context(dict()).best_match().code, lang)
|
'When falling back to first installed language.'
| def test_first_installed(self):
| first = self.rl.search([('active', '=', True)], limit=1)
self.env.user.lang = False
self.assertEqual(self.rl.with_context(lang=False).best_match().code, first.code)
|
'When matches to an unavailable language.'
| def test_unavailable(self):
| self.env.user.lang = False
self.rl = self.rl.with_context(lang=False)
first = self.rl.search([('active', '=', True)], limit=1)
self.assertEqual(self.rl.best_match('fake_LANG').code, first.code)
with self.assertRaises(UserError):
self.rl.best_match('fake_LANG', failure_safe=False)
|
'Get the model from the resource.'
| @api.multi
@api.depends('resource')
def _compute_model_id(self):
| for s in self:
s.model_id = self._get_model_id(s.resource)
|
'Get the resource from the model.'
| @api.multi
@api.onchange('model_id')
def _inverse_model_id(self):
| for s in self:
s.resource = s.model_id.model
|
'Void fields if model is changed in a view.'
| @api.multi
@api.onchange('resource')
def _onchange_resource(self):
| for s in self:
s.export_fields = False
|
'Return a model object from its technical name.
:param str resource:
Technical name of the model, like ``ir.model``.'
| @api.model
def _get_model_id(self, resource):
| return self.env['ir.model'].search([('model', '=', resource)])
|
'Check required values when creating the record.
Odoo\'s export dialog populates ``resource``, while this module\'s new
form populates ``model_id``. At least one of them is required to
trigger the methods that fill up the other, so this should fail if
one is missing.'
| @api.model
def create(self, vals):
| if (not any(((f in vals) for f in {'model_id', 'resource'}))):
raise ValidationError(_('You must supply a model or resource.'))
return super(IrExports, self).create(vals)
|
'Default model depending on context.'
| @api.model
def _default_model1_id(self):
| return self.env.context.get('default_model1_id', False)
|
'Get the name from the selected fields.'
| @api.multi
@api.depends('field1_id', 'field2_id', 'field3_id')
def _compute_name(self):
| for s in self:
s.name = '/'.join((s.field_n(num).name for num in range(1, 4) if s.field_n(num)))
|
'Get the related model for the second field.'
| @api.multi
@api.depends('field1_id')
def _compute_model2_id(self):
| ir_model = self.env['ir.model']
for s in self:
s.model2_id = (s.field1_id.ttype and ('2' in s.field1_id.ttype) and ir_model.search([('model', '=', s.field1_id.relation)]))
|
'Get the related model for the third field.'
| @api.multi
@api.depends('field2_id')
def _compute_model3_id(self):
| ir_model = self.env['ir.model']
for s in self:
s.model3_id = (s.field2_id.ttype and ('2' in s.field2_id.ttype) and ir_model.search([('model', '=', s.field2_id.relation)]))
|
'Column label in a user-friendly format and language.'
| @api.multi
@api.depends('name')
def _compute_label(self):
| translations = self.env['ir.translation']
for s in self:
parts = list()
for num in range(1, 4):
field = s.field_n(num)
if (not field):
break
parts.append((translations.search([('type', '=', 'field'), ('lang', '=', self.env.context.get('lang')), ('name', '=', ('%s,%s' % (s.model_n(num).model, field.name)))]).value or field.display_name))
s.label = (('%s (%s)' % ('/'.join(parts), s.name)) if (parts and s.name) else False)
|
'Get the fields from the name.'
| @api.multi
def _inverse_name(self):
| for s in self:
parts = s.name.split('/', 2)
for num in range(1, 4):
try:
field_name = parts[(num - 1)]
except IndexError:
s[s.field_n(num, True)] = False
else:
model = s.model_n(num)
s[s.field_n(num, True)] = self._get_field_id(model, field_name)
|
'Populate ``field*_id`` fields.'
| @api.model
def _install_base_export_manager(self):
| self.search([('export_id', '=', False)]).unlink()
self.search([('field1_id', '=', False), ('name', '!=', False)])._inverse_name()
|
'Get a field object from its model and name.
:param int model:
``ir.model`` object that contains the field.
:param str name:
Technical name of the field, like ``child_ids``.'
| @api.model
def _get_field_id(self, model, name):
| return self.env['ir.model.fields'].search([('name', '=', name), ('model_id', '=', model.id)])
|
'Helper to choose the field according to its indentation level.
:param int n:
Number of the indentation level to choose the field, from 1 to 3.
:param bool only_name:
Return only the field name, or return its value.'
| @api.multi
def field_n(self, n, only_name=False):
| name = ('field%d_id' % n)
return (name if only_name else self[name])
|
'Helper to choose the model according to its indentation level.
:param int n:
Number of the indentation level to choose the model, from 1 to 3.
:param bool only_name:
Return only the model name, or return its value.'
| @api.multi
def model_n(self, n, only_name=False):
| name = ('model%d_id' % n)
return (name if only_name else self[name])
|
'Emulate creation from original form.
This form is handled entirely client-side, and lacks some required
field values.'
| def test_create_with_basic_data(self):
| data = {'name': u'Test \xe9xport', 'resource': 'ir.exports', 'export_fields': [[0, 0, {'name': 'export_fields'}], [0, 0, {'name': 'export_fields/create_uid'}], [0, 0, {'name': 'export_fields/create_date'}], [0, 0, {'name': 'export_fields/field1_id'}]]}
record = self.env['ir.exports'].create(data)
self.assertEqual(record.model_id.model, data['resource'])
|
'Creating a record without ``model_id`` and ``resource`` fails.'
| def test_create_without_model(self):
| IrExports = self.env['ir.exports']
model = IrExports._get_model_id('res.partner')
record = IrExports.create({'name': 'some', 'resource': model.model})
self.assertEqual(record.model_id, model)
record = IrExports.create({'name': 'some', 'model_id': model.id})
self.assertEqual(record.resource, model.model)
with self.assertRaises(ValidationError):
IrExports.create({'name': 'some'})
|
'Init Rope context.'
| def __init__(self, path=None, project_path=None):
| self.path = path
self.project = project.Project(project_path, fscommands=FileSystemCommands())
self.importer = rope_autoimport.AutoImport(project=self.project, observe=False)
update_python_path(self.project.prefs.get('python_path', []))
self.resource = None
self.current = None
self.options = dict(completeopt=env.var('&completeopt'), autoimport=env.var('g:pymode_rope_autoimport', True), autoimport_modules=env.var('g:pymode_rope_autoimport_modules'), goto_definition_cmd=env.var('g:pymode_rope_goto_definition_cmd'))
if os.path.exists(('%s/__init__.py' % project_path)):
sys.path.append(project_path)
if self.options.get('autoimport'):
self.generate_autoimport_cache()
env.debug('Context init', project_path)
env.message(('Init Rope project: %s' % project_path))
|
'Enter to Rope ctx.'
| def __enter__(self):
| env.let('g:pymode_rope_current', self.project.root.real_path)
self.project.validate(self.project.root)
self.resource = libutils.path_to_resource(self.project, env.curbuf.name, 'file')
if ((not self.resource.exists()) or os.path.isdir(self.resource.real_path)):
self.resource = None
else:
env.debug('Found resource', self.resource.path)
return self
|
'Exit from Rope ctx.'
| def __exit__(self, t, value, traceback):
| if (t is None):
self.project.close()
|
'Update autoimport cache.'
| def generate_autoimport_cache(self):
| env.message('Regenerate autoimport cache.')
modules = self.options.get('autoimport_modules', [])
def _update_cache(importer, modules=None):
importer.generate_cache()
if modules:
importer.generate_modules_cache(modules)
importer.project.sync()
_update_cache(self.importer, modules)
|
'Init progress handler.'
| def __init__(self, msg):
| self.handle = TaskHandle(name='refactoring_handle')
self.handle.add_observer(self)
self.message = msg
|
'Show current progress.'
| def __call__(self):
| percent_done = self.handle.current_jobset().get_percent_done()
env.message(('%s - done %s%%' % (self.message, percent_done)))
|
'Run refactoring.
:return bool:'
| def run(self):
| with RopeContext() as ctx:
if (not ctx.resource):
env.error('You should save the file before refactoring.')
return None
try:
env.message(self.__doc__)
refactor = self.get_refactor(ctx)
input_str = self.get_input_str(refactor, ctx)
if (not input_str):
return False
action = env.user_input_choices('Choose what to do:', 'perform', 'preview', 'perform in class hierarchy', 'preview in class hierarchy')
in_hierarchy = action.endswith('in class hierarchy')
changes = self.get_changes(refactor, input_str, in_hierarchy)
if (not action):
return False
if action.startswith('preview'):
print('\n ')
print('-------------------------------')
print(('\n%s\n' % changes.get_description()))
print('-------------------------------\n\n')
if (not env.user_confirm('Do the changes?')):
return False
progress = ProgressHandler('Apply changes ...')
ctx.project.do(changes, task_handle=progress.handle)
reload_changes(changes)
except exceptions.RefactoringError as e:
env.error(str(e))
except Exception as e:
env.error(('Unhandled exception in Pymode: %s' % e))
|
'Get refactor object.'
| @staticmethod
def get_refactor(ctx):
| raise NotImplementedError
|
'Get user input. Skip by default.
:return bool: True'
| @staticmethod
def get_input_str(refactor, ctx):
| return True
|
'Function description.
:return Rename:'
| def get_refactor(self, ctx):
| offset = None
if (not self.module):
(_, offset) = env.get_offset_params()
env.debug('Prepare rename', offset)
return rename.Rename(ctx.project, ctx.resource, offset)
|
'Return user input.'
| def get_input_str(self, refactor, ctx):
| oldname = str(refactor.get_old_name())
msg = 'Renaming method/variable. New name:'
if self.module:
msg = 'Renaming module. New name:'
newname = env.user_input(msg, oldname)
if (newname == oldname):
env.message('Nothing to do.')
return False
return newname
|
'Get changes.
:return Changes:'
| @staticmethod
def get_changes(refactor, input_str, in_hierarchy=False):
| return refactor.get_changes(input_str, in_hierarchy=in_hierarchy)
|
'Return user input.'
| @staticmethod
def get_input_str(refactor, ctx):
| return env.user_input('New method name:')
|
'Function description.
:return Rename:'
| @staticmethod
def get_refactor(ctx):
| (cursor1, cursor2) = (env.curbuf.mark('<'), env.curbuf.mark('>'))
(_, offset1) = env.get_offset_params(cursor1)
(_, offset2) = env.get_offset_params(cursor2)
return extract.ExtractMethod(ctx.project, ctx.resource, offset1, offset2)
|
'Return user input.'
| @staticmethod
def get_input_str(refactor, ctx):
| return env.user_input('New variable name:')
|
'Function description.
:return Rename:'
| @staticmethod
def get_refactor(ctx):
| (cursor1, cursor2) = (env.curbuf.mark('<'), env.curbuf.mark('>'))
(_, offset1) = env.get_offset_params(cursor1)
(_, offset2) = env.get_offset_params(cursor2)
return extract.ExtractVariable(ctx.project, ctx.resource, offset1, offset2)
|
'Function description.
:return Rename:'
| @staticmethod
def get_refactor(ctx):
| (_, offset) = env.get_offset_params()
return inline.create_inline(ctx.project, ctx.resource, offset)
|
'Get changes.
:return Changes:'
| @staticmethod
def get_changes(refactor, input_str, in_hierarchy=False):
| return refactor.get_changes()
|
'Function description.
:return Rename:'
| @staticmethod
def get_refactor(ctx):
| (_, offset) = env.get_offset_params()
return usefunction.UseFunction(ctx.project, ctx.resource, offset)
|
'Get changes.
:return Changes:'
| @staticmethod
def get_changes(refactor, input_str, in_hierarchy=False):
| return refactor.get_changes()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.