官术网_书友最值得收藏!

Adding automated tests

Programming best practices include having automated tests for your code. This is even more important for dynamic languages such as Python. Since there is no compilation step, you can't be sure there are no syntactic errors until the code is actually run by the interpreter. A good editor can help us spot these problems ahead of time, but can't help us ensure the code performs as intended like automated tests can.

Odoo supports two ways to describe tests: either using YAML data files or using Python code, based on the Unittest library. YAML tests are a legacy from older versions and are not recommended. We prefer using Python tests and will add a basic test case to our module.

The test code files should have a name starting with test_ and should be imported from tests/__init__.py. But the tests directory (also a Python submodule) should not be imported from the module's top __init__.py, since it will be automatically discovered and loaded only when tests are executed.

Tests must be placed in the tests/ subdirectory. Add a tests/__init__.py file with the following:

from . import test_todo 

Now add the actual test code, available in the tests/test_todo.py file:

from odoo.tests.common import TransactionCase 
 
class TestTodo(TransactionCase): 
 
    def test_create(self): 
        "Create a simple Todo" 
        Todo = self.env['todo.task'] 
        task = Todo.create({'name': 'Test Task'}) 
        self.assertEqual(task.is_done, False) 

This adds a simple test case to create a new To-Do task and verifies that the Is Done? field has the correct default value.

Now we want to run our tests. This is done by adding the --test-enable option while installing or upgrading the module:

$ ./odoo-bin -d todo -u todo_app --test-enable

The Odoo server will look for a tests/ subdirectory in the upgraded modules and will run them. If any of the tests fail, the server log will show that.

主站蜘蛛池模板: 腾冲县| 胶南市| 黑龙江省| 宁武县| 张家港市| 隆尧县| 永修县| 邛崃市| 三河市| 沙田区| 石屏县| 本溪市| 曲水县| 井冈山市| 定远县| 定州市| 丹巴县| 子洲县| 正安县| 南投县| 江西省| 同德县| 绥化市| 平凉市| 盐边县| 商城县| 双辽市| 凤冈县| 普兰店市| 寿光市| 册亨县| 迭部县| 仁布县| 新田县| 团风县| 安远县| 清镇市| 清流县| 浪卡子县| 龙山县| 永济市|