Skip to content

21. 单元测试 ​

适用版本

Odoo 20 社区版 · 对应官方教程 Safeguard your code with unit tests

第 21 课:单元测试 ​

21.1 目标 ​

约束、计算字段、状态机这些逻辑,手工点一遍只能证明"这次对了"。模块一升级、别人改了一行依赖,旧行为可能悄悄坏掉。测试的作用是把这些规则钉死:以后谁改坏了,一条命令就能定位。

这一章回答三个问题:

  1. 测试文件放哪、叫什么名字才会被执行?
  2. TransactionCase 为什么不用 SavepointCase?
  3. --test-enable、-t、at_install / post_install 分别怎么选?

21.2 Odoo 的做法 ​

21.2.1 目录、命名与加载链 ​

测试放在模块的 tests/ 包里:

text
estate20/
├── __init__.py            # from . import models(另有测试导入见下)
└── tests/
    ├── __init__.py        # from . import test_estate_property
    └── test_estate_property.py

模块根 __init__.py 不用显式导入 tests,框架通过 importlib 找 odoo.addons.<module>.tests。但 tests/__init__.py 必须逐个导入测试模块,且文件名必须以 test_ 开头——源码 odoo/tests/loader.py 只收集名字以 test_ 开头的模块;测试方法名必须以 test 开头。

版本变化(Odoo 20)

from odoo.tests.common import SavepointCase 已不可用——核心里只有 SavepointCaseWithUserDemo,而且它的父类就是 TransactionCase。HttpCaseWithUserDemo 也移到了 odoo.addons.base.tests.common。旧教程照抄会直接导入失败。

21.2.2 TransactionCase:一个事务 + 每方法一个 savepoint ​

TransactionCase 的所有测试方法跑在同一个事务里,每个方法外面套一个 savepoint,结束时游标不提交直接关闭。公共数据放在 setUpClass 里只建一次,比每个方法重建快得多。

测试里禁止调用 commit() / rollback() / close()——框架把它们 patch 成会抛 AssertionError 的函数。确实需要事务边界时回滚到自己的 savepoint,或另开游标。

21.2.3 怎么跑:--test-enable 与 -t ​

命令效果
-u estate20 --test-enable开启测试,隐含 +standard,同时强制 --stop-after-init
-u estate20 -t standard/estate20只跑 estate20 模块的 standard 测试;带 -t 自动开启测试
-u estate20 -t at_install只跑安装阶段测试
-u estate20 -t post_install只跑所有模块加载完之后的测试(默认阶段)

源码 tools/config.py 里 --test-enable 归一化成 test_tags = '+standard';tests/loader.py 在两个时机各筛一次:at_install(每个模块升级后)和 post_install(全部加载完成后)。

测试类默认标签是 standard + post_install,不是老版本的 at_install。想改成安装阶段要显式写:

python
@tagged('at_install', '-post_install')
class TestSomething(TransactionCase):
    ...

-t 的筛选语法是 [-][tag][/module][:class][.method],负号表示排除。

21.2.4 断言与 mock ​

Odoo 重写了 assertRaises / assertRaisesRegex:进入上下文时自动开 savepoint,异常后自动回滚,避免一条测试污染下一条。推荐用上下文写法:

python
with self.assertRaisesRegex(ValidationError, '已售出'):
    rec.write({'state': 'sold'})

mock 用标准库 from unittest.mock import patch,或者框架自带的 self.patch(obj, key, val) / self.startPatcher(patcher),它们会在测试结束时自动撤销。@tagged 用 negation 前缀 - 去掉标签,例如 @tagged('-standard') 让测试默认不被跑。

21.3 开发实践 ​

21.3.1 写测试 ​

tests/test_estate_property.py:

python
from odoo.exceptions import ValidationError
from odoo.tests import TransactionCase, tagged


@tagged('post_install', '-at_install')
class TestEstateProperty(TransactionCase):

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.Property = cls.env['estate.property']
        cls.sample = cls.Property.create({
            'name': '测试房源', 'expected_price': 600000,
        })

    def test_total_area(self):
        rec = self.Property.create({
            'name': '带花园房源', 'expected_price': 100,
            'living_area': 80.5, 'garden_area': 19.5,
        })
        self.assertEqual(rec.total_area, 100.0)

    def test_sold_without_price(self):
        with self.assertRaisesRegex(ValidationError, '成交价'):
            self.sample.write({'state': 'sold'})

setUpClass 里建的 sample 由类级 savepoint 管理,每个测试方法结束后自动回到初始状态。

21.3.2 让测试可重复跑 ​

python
# tests/__init__.py
from . import test_estate_property

配套快照在 D:/workspace/winodoo/samples/ch21,tests/ 包已写好,可直接跑 --test-enable。

shell
cd D:\odoo20
venv\Scripts\activate
python odoo-bin -c odoo.conf -u estate20 --test-enable
python odoo-bin -c odoo.conf -u estate20 -t standard/estate20
sql
SELECT name, state FROM ir_module_module WHERE name = 'estate20';
SELECT count(*) FROM ir_logging WHERE message LIKE '%test_estate_property%';

日志里能看到 0 failed, N passed 才算真跑到了;只看到模块升级成功但没有任何测试输出,通常就是 tests/__init__.py 没导入或文件名不对。

交给 AI(第 21 章 · 单元测试)

把下面这段发给任意 AI 对话(ChatGPT / Claude / Cursor 均可):

我们用的是 Odoo 20 社区版,模块 estate20,模型 estate.property 有 living_area / garden_area(计算字段 total_area)/ state / selling_price,@api.constrains('state','selling_price') 要求 sold 时必须有成交价。请写 tests/test_estate_property.py 与 tests/__init__.py:用 TransactionCase,setUpClass 建一条样本,两个测试方法分别验证 total_area = 100.0 与缺成交价时抛 ValidationError。要求用 assertRaisesRegex、用 @tagged('post_install','-at_install'),并给出 --test-enable 与 -t standard/estate20 两条运行命令。

21.4 总结 ​

验收清单
  • 测试文件名是 test_*.py,且已在 tests/__init__.py 中导入
  • -u estate20 --test-enable 日志里出现测试类与 0 failed
  • 故意把 total_area 计算改错,测试能失败;改回来后恢复通过
  • -t standard/estate20 只跑本模块的测试,不跑全库
  • 测试里没有 commit() / rollback(),也没有导入 SavepointCase

21.5 常见坑与排错 ​

现象原因处理
命令跑完没有任何测试输出文件名不是 test_*.py 或 __init__.py 没导入按命名约定补齐
测试方法没被执行方法名不以 test 开头改名
导入 SavepointCase 报 ImportError20 核心已移除该类用 TransactionCase
测试默认在 post_install 跑,想改阶段默认标签是 standard + post_install@tagged('at_install', '-post_install')
测试里 commit() 抛 AssertionError框架禁止测试内提交/回滚回滚到 savepoint,或另开游标
一条测试失败污染后续测试没用 self.assertRaises 的自动 savepoint改用上下文写法
assertRaisesRegexp 不存在Python 2 遗留名用 assertRaisesRegex
patch 在测试结束后没恢复用了外部 mock 包或手动 patch用 unittest.mock 或 self.startPatcher
-t 没触发测试tag 表达式写错,或类带了 -standard检查 @tagged 与 config.py 的归一化规则

参考与致谢:本章知识结构参考 Odoo 官方教程 Safeguard your code with unit tests (Odoo S.A.,CC BY-SA 4.0)。测试命名规则、两阶段执行与 SavepointCase 移除说明均为本站基于 Odoo 20 社区版源码核对并独立编写。 本站非 Odoo 官方站点,内容不代表 Odoo S.A. 观点。

最近更新