Odoo 12 Development Essentials
上QQ阅读APP看书,第一时间看更新

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.

Changed in Odoo 12
In previous versions, Odoo also used tests described using YAML data files. YAML data-file support was removed in Odoo 12, so this type of test is not available anymore.

The test-driven development (TDD) method states that we should write tests up front, check that they fail, then develop the code that, in the end, should pass the tests. Inspired by this approach, we will add our module tests now, before we add the actual features:

  1. 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.
  2. Tests must be placed in the tests/ subdirectory. Add a tests/__init__.py file with the following:
from . import test_book
  1. Add the actual test code, available in the tests/test_book.py file:
from odoo.tests.common import TransactionCase 

class TestBook(TransactionCase):
def setUp(self, *args, **kwargs):
result = super().setUp(*args, **kwargs)
self.Book = self.env['library.book']
self.book_ode = self.Book.create({
'name': 'Odoo Development Essentials',
'isbn': '879-1-78439-279-6'})
return result
def test_create(self): "Test Books are active by default" self.assertEqual(self.book_ode.active, True)

This adds a simple test case that creates a new Book and verifies that the active field has the correct default value.

  1. Run the tests by adding the --test-enable option while installing or upgrading the module:
$ ./odoo-bin -d dev12 -u library_app --test-enable
  1. The Odoo server will look for a tests/ subdirectory in the upgraded modules and will run them. At this point, the tests are expected to throw an error, so you should see ERROR messages related to the tests in the server log. This should change once we add the book model to the module.