Toggle navigation

测试模块

Odoo中使用unittest来支持模块的测试。

要编写测试,只需在模块中定义 tests 子模块,它将自动检查测试模块。测试模块应该是 以 test_ 开头的名称,并且应该从 tests/__init__.py 文件中导入,例如:

your_module
|-- ...
`-- tests
    |-- __init__.py
    |-- test_bar.py
    `-- test_foo.py

__init__.py 包含:

from . import test_foo, test_bar

Changed in version 8.0: 以前,测试运行器只会运行添加到两个列表 fast_suitechecks 中的模块,并 检入 tests/ __init__.py 文件。在8.0版本中它将运行所有导入的模块

测试运行器将简单地运行测试用例,如官方的 unittest documentation ,所述,但是Odoo提供了许多与测试Odoo内容(主要模块)相关的实用程序和帮助:

class odoo.tests.common.TransactionCase(methodName='runTest')[source]

TestCase in which each test method is run in its own transaction, and with its own cursor. The transaction is rolled back and the cursor is closed after each test.

browse_ref(xid)[source]

Returns a record object for the provided external identifier

Parameters
xid -- fully-qualified external identifier, in the form module.identifier
Raise
ValueError if not found
Returns
BaseModel
ref(xid)[source]

Returns database ID for the provided external identifier, shortcut for get_object_reference

Parameters
xid -- fully-qualified external identifier, in the form module.identifier
Raise
ValueError if not found
Returns
registered id
class odoo.tests.common.SingleTransactionCase(methodName='runTest')[source]

TestCase in which all test methods are run in the same transaction, the transaction is started with the first test method and rolled back at the end of the last.

browse_ref(xid)[source]

Returns a record object for the provided external identifier

Parameters
xid -- fully-qualified external identifier, in the form module.identifier
Raise
ValueError if not found
Returns
BaseModel
ref(xid)[source]

Returns database ID for the provided external identifier, shortcut for get_object_reference

Parameters
xid -- fully-qualified external identifier, in the form module.identifier
Raise
ValueError if not found
Returns
registered id

默认情况下,在安装相应的模块后立即运行测试。测试用例也可以配置为在所有模块安装后运行,而不是在模块安装后立即执行

odoo.tests.common.at_install(flag)[source]

Sets the at-install state of a test, the flag is a boolean specifying whether the test should (True) or should not (False) run during module installation.

By default, tests are run right after installing the module, before starting the installation of the next module.

odoo.tests.common.post_install(flag)[source]

Sets the post-install state of a test. The flag is a boolean specifying whether the test should or should not run after a set of module installations.

By default, tests are not run after installation of all modules in the current installation set.

最常见的情况是使用 TransactionCase 并在每个方法中测试模型的属性:

class TestModelA(common.TransactionCase):
    def test_some_action(self):
        record = self.env['model.a'].create({'field': 'value'})
        record.some_action()
        self.assertEqual(
            record.field,
            expected_field_value)

    # other tests...

运行测试

在安装或更新模块时,将自动运行测试。启动Odoo服务器时启用 --test-enable

从Odoo 8开始,是不支持在安装/更新周期之外运行测试