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

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.

主站蜘蛛池模板: 商城县| 金川县| 云梦县| 呼图壁县| 远安县| 东源县| 云安县| 临湘市| 信丰县| 新营市| 泸西县| 钟山县| 吉安市| 庄浪县| 儋州市| 汶上县| 高尔夫| 来凤县| 太白县| 寿光市| 喀喇沁旗| 华坪县| 诏安县| 聂拉木县| 湖口县| 两当县| 建平县| 镇远县| 澎湖县| 凌海市| 永兴县| 色达县| 麦盖提县| 肇庆市| 柞水县| 小金县| 墨脱县| 昂仁县| 吴桥县| 大化| 静安区|