We create a Python subpackage in our module called tests and add a test module with a name starting with test_. This is the convention used by Odoo for test discovery.
In this file, we import the base test class, TransactionCase from odoo.tests.common. This class extends the unittest.TestCase class from the Python standard library to make it suitable for use in Odoo by overloading the setUp() and tearDown() methods of unittest.TestCase:
- The setUp() method initializes the self.env attribute that you can use to perform the usual operations (refer to the recipes in Chapter 6, Basic Server-Side Development)
- The tearDown() method rolls back the database transaction so that the tests are run in insulation
The tests are defined in methods named with a test prefix. The test runner will then run one after the other with a call to setUp() before each test method and a call to tearDown() after each. Inside the method, you can use all the usual assertion methods from unittest.TestCase. Here are the most commonly used ones:
Method |
Checks that |
assertEqual(a, b) |
a == b |
assertNotEqual(a, b) |
a != b |
assertTrue(x) |
bool(x) is True |
assertFalse(x) |
bool(x) is False |
assertIn(a, b) |
a in b |
assertNotIn(a, b) |
a not in b |
assertRaises(exc, fun, *args, **kwargs) |
fun(*args, **kwargs) raises exc |
All these methods except assertRaises() accept an optional msg argument, which will be displayed in the error message when the assertion is not true. Otherwise, a standard error message is used.
assertRaises is best used as a context manager. Suppose you want to test that modifying a record raises a UserError exception. You can write the following test:
class TestCase(TransactionCase): # setUp method defines self.record def testWriteRaisesUserError(self): with self.assertRaises(UserError): self.record.write({'some_field': some_value})
The test will succeed if the exception passed to assertRaises is generated by the block of code, otherwise it will fail.
For more information on unit tests in Python, refer to the standard library documentation at https://docs.python.org/3.5/library/unittest.html#test-cases.
Refer to the Run server tests recipe to see how to run the test.