1:用于向用户显示警告信息。
首先,要导入 Odoo API库,添加对应的 import 及 Odoo Warning异常。这需要编辑.py文件修改前两行:
from odoo import api, fields, models
from odoo.exceptions import Warning
其次,可以在button的函数响应中调用它。
@api.multi
def button_send(self):
self.ensure_one()
#for blcode in self.blcode_id:
raise Warning('Please provide blcode %s' % self.blcode_id.name)
return True
它报的弹框主题是“Odoo Server Error - Warning”。利用它可以打印输出 变量值,比较直观方便。
2:测试异常:
常用的情况是测试是否正确地进行了验证。本例中,我们可以测试向导的一些验证。例如,我们可以测试空消息体抛出错误。要检查是否抛出异常,我们将相应代码放在self.assertRaises()代码块中。
首先在文件顶部导入 Odoo 的异常类:
from odoo import exceptions
然后,在测试类中添加含有测试用例的另一个方法:
def test_button_send_empty_body(self):
"Send button errors on empty body message"
wizard0 = self.Wizard.create({})
with self.assertRaises(exceptions.UserError) as e:
wizard0.button_send()
如果button_send()没有抛出异常,则检测失败。如果抛出了异常,检测成功并将异常存储在 e 变量中,我们可以使用它来做进一步的检测。
3:抛出异常
from odoo import exceptions
raise exceptions.ValidationError('验证失败')
raise exceptions.UserError('业务逻辑错误')
通常所有在方法执行期间的数据操纵在数据库事务中,发生异常时会进行回滚。也就是说在抛出异常时,所有此前对数据的修改都会被取消。
下面就使用本例向导button_send方法来进行举例说明。试想一下如果执行发送消息逻辑时没有选中任何借阅文档是不是不合逻辑?同样如果没有消息体就发送消息也不合逻辑。下面就来在发生这些情况时向用户发出警告。
编辑button_send()方法,在self.ensure_one()一行后加入如下代码:
if not self.checkout_ids:
raise exceptions.UserError(
'请至少选择一条借阅记录来发送消息!')
if not self.message_body:
raise exceptions.UserError(
'请填写要发送的消息体!')
最后,还可以有:
raise ValidationError('%s is an invalid ISBN' % book.isbn)
raise exceptions.UserError('Not allowed to create a checkout in the done state.')