Odoo:测试唯一约束?

时间:2016-05-28 14:09:05

标签: python unit-testing openerp odoo-8 unique-constraint

看起来Odoo在测试唯一约束时失败了。

我添加了这个约束:

_sql_constraints = [(
    'uniq_line',
    'unique(routing_phase_id, project_id)',
    'Phase have to be unique per Routing!')
]

约束本身有效,但运行unittest,我无法成功测试它。

我试过了:

from psycopg2 import IntegrityError

with self.assertRaises(IntegrityError):
     self.env['project.routing.line'].create(
        self.project_routing_line_1.copy_data()[0])

运行test时出现此错误:

2016-05-28 13:59:16,575 19786 ERROR pas_test openerp.sql_db: bad query: INSERT INTO "project_routing_line" ("id", "routing_phase_id", "sequence", "next_routing_phase_id", "duration", "project_id", "return_routing_phase_id", "need_approve", "create_uid", "write_uid", "create_date", "write_date") VALUES(nextval('project_routing_line_id_seq'), 1, 5, NULL, 10.0, 5, 3, false, 1, 1, (now() at time zone 'UTC'), (now() at time zone 'UTC')) RETURNING id
Traceback (most recent call last):
  File "/home/oerp/openerp80/odoo/openerp/sql_db.py", line 234, in execute
    res = self._obj.execute(query, params)
IntegrityError: duplicate key value violates unique constraint "project_routing_line_uniq_line"
DETAIL:  Key (routing_phase_id, project_id)=(1, 5) already exists

所以我没有得到它,测试捕获IntegrityEror(或者它没有?),但是Odoo仍然试图创建当然失败的记录。我在这里做错了吗?

更新

我开始思考,也许是因为它是SQL约束,python不会在正确的时间捕获这样的异常(比如使用assertRaises),因为它发生在所有python验证之后?这可以解释为什么测试失败。

1 个答案:

答案 0 :(得分:2)

我自己遇到了这个问题,并发现了Odoo自己使用的现有测试。

他们在测试引发IntegrityError的方法上使用openerp.tools.mute_logger('openerp.sql_db')装饰器。

https://github.com/odoo/odoo/blob/7682760dcad232829fbb5d4221f66a1ebb9d6c91/openerp/addons/base/tests/test_views.py#L864

我将装饰器添加到我的测试方法中并且有效。我想记录的IntegrityError会阻止引发异常。