Testing is one of the key phases in Odoo module development. It is not sufficient to validate whether a feature works in the application just once from the user interface. Various changes in the business logic, database actions, controllers, and JavaScript components may cause some bugs elsewhere in the application.
Odoo offers various types of testing to validate these functionalities. Unit tests in Python are primarily used to validate backend actions and business logic. HTTP tests are used to validate controllers and web requests. In order to validate frontend functionality, Odoo 20 makes use of the HOOT testing framework. Tests that require full workflow verification through simulation of user interaction with the app in the browser are called tours.
This blog will focus on testing layers provided in Odoo 20, the usage of these testing layers, and the selection of appropriate tests.
Understanding the Testing Layers in Odoo 20
The odoo test may be broken down into three parts:
- Python Unit Test: Used to test the model methods, the business logic, the database interaction, and all the other functionalities within the backend.
- JavaScript Unit Test: Used to test the frontend objects and the JavaScript functionality separately.
- Integration Tests (Tour): Used to test how the frontend and backend interact in user actions.
The layers have a separate scope within the application. A Python test would determine whether the invoice was calculated correctly, a JavaScript test would determine whether the object reacted to the user action, and a tour would determine whether a user could fill the whole invoice through the Odoo UI.
Python Test Classes
Odoo provides different base classes for writing Python tests. The commonly used classes are TransactionCase, HttpCase, and BaseCommon.
1. TransactionCase
TransactionCase is the common base class used to test backend business logic. It can be used to test the functionality involving ORM, model methods, computed fields, constraints, etc.
All methods in TransactionCase use only one database transaction, which is started at the class level, but each test method uses its own savepoint. At the completion of the test method, the savepoint is rolled back, such that any change made during the test does not have any impact on other tests. The outer transaction is never committed and is finally closed.
This is the way to go when you can test the functionality using Python itself, without an HTTP request or browser interaction.
2. HttpCase
HttpCase inherits from TransactionCase and comes with features to test Odoo with HTTP calls and interactions in a browser environment.
It includes the url_open() method to perform HTTP calls directly and the start_tour() method to start browser-driven tours using Chrome in headless mode. In addition to that, there is the browser_js() method to execute any JavaScript in the browser and the authenticate() method to log into Odoo as a specified user.
HttpCase can be used to test controllers, website routes, portal, and full-blown UI processes. According to its source code, tests that use HttpCase must be marked as post_install.
One key point: any HTTP request outside of the test is automatically blocked during normally marked tests. Any HTTP request from Odoo that does not have localhost as the destination will raise a BlockedRequest exception.
3. BaseCommon
The class BaseCommon can be imported from odoo.addons.base.tests.common. The class inherits from TransactionCase and creates an environment which is far more complete in itself.
Once a test class inherits from BaseCommon, the following things get automatically created for the entire test class:
- An independent company and currency (by default USD).
- A test user whose groups can be configured (by default base.group_user) and can be accessed as self._test_user.
- A test partner (self.partner).
- Shorthand for some common groups like self.group_user, self.group_portal, self.group_system, self.group_public.
- Context keys for mails to prevent any logging and subscriptions.
Then, all test methods run as self._test_user and not as superuser. Hence, BaseCommon becomes useful where there is a requirement to run tests under the permission of real users and not under superuser.
It is not a lightweight mixin for sharing fixtures. It is a complete automated environment constructor which becomes very useful while creating tests for accounting, multi-company, or access control modules.
A Simple Python Unit Test Example
Consider a simple example of testing a custom model in Odoo 20. Suppose there is a model called student.record with a field named name. The following test verifies whether a record can be created successfully.
Test_student.py
from odoo.tests import TransactionCase
class TestStudent(TransactionCase):
def test_create_student(self):
student = self.env['student.record'].create({
'name': 'John',
})
self.assertEqual(student.name, 'John')
What happens in this test:
- The transaction case object TransactionCase offers the test environment and database savepoint management.
- self.env helps to access the Odoo ORM from the superuser context.
- The create() function creates the student record in the savepoint.
- The assertEqual() function verifies the stored name against the expected value.
If the values match, the test passes. After the test method ends, the savepoint is rolled back automatically.
For Odoo to discover the test, the file must be imported through __init__.py.
from . import test_student
The tests package itself must also be imported from the module's root __init__.py.
from . import tests
Additional Utilities for Python Tests
In addition to the basic test classes, Odoo offers additional utilities in odoo.tests which cut down on repetitive coding and deal with special test cases.
Form
The Form utility emulates form view interaction from within Python code. It helps with testing the default value assignment and behaviour of the onchange method, especially when fields are dependent on one another.
from odoo.tests import Form
with Form(self.env['student.record']) as form:
form.name = 'John'
student = form.save()
The form helper handles onchange events and sets default values just like a form view normally would, thus making sure tests simulate real user interaction and not just ORM operations. An ORM write() or create() operation won’t execute onchange methods – this is done only by the Form helper.
new_test_user()
This is a utility method that creates a test user. It takes a login, a string containing XML IDs of the groups separated by commas, and any additional keyword arguments that get passed on to the ORM create() method. This method sets a name, an email, and a password for the new user if they are not specified. By default, the password equals the login string padded up to 8 characters.
from odoo.tests.common import new_test_user
user = new_test_user(
self.env,
login='test_sales',
groups='base.group_user,sales_team.group_sale_salesman',
)
It is useful when testing access rights, record rules, and functionality that behaves differently depending on the logged-in user.
Freeze_time
Time-dependent functionality is difficult to test because results change with the current date. Odoo provides its own freeze_time class (which wraps freezegun) to control the date and time during test execution.
It can be used as a class decorator or as a context manager:
from odoo.tests.common import freeze_time
@freeze_time('2025-01-15')
class TestDeadlines(TransactionCase):
def test_overdue_invoice(self):
# The date is now fixed at 2025-01-15
...Or as a context manager within a test method:
def test_scheduled_action(self):
with freeze_time('2025-06-01'):
# date-sensitive operations here
...
assertQueryCount and assertQueries
These two context managers help verify database query efficiency. assertQueryCount() checks that a block of code executes exactly the expected number of SQL queries:
with self.assertQueryCount(1):
self.env['sale.order'].search([])
If the ORM cache already holds the data from earlier in the same test class, the count may be 0 instead of 1. Call self.env.invalidate_all() before the block to ensure a clean read and get a consistent count.
assertQueries() is more precise: it checks the exact SQL statements executed, with support for case-insensitive matching and a ... wildcard for partial matching. Both are useful for catching unintended N+1 query regressions when modifying ORM logic.
RecordCapturer
RecordCapturer is a context manager that records which records of a given model were created inside the block:
from odoo.tests import RecordCapturer
with RecordCapturer(self.env['student.record']) as capturer:
self.env['student.record'].create({'name': 'Alice'})
self.env['student.record'].create({'name': 'Bob'})
new_records = capturer.records
self.assertEqual(len(new_records), 2)
This is useful when testing methods that create records internally, where the created record IDs are not directly returned.
MockHTTPClient
When a custom module communicates with an external API, real HTTP requests must not be made during tests. MockHTTPClient is a context manager that patches requests.Session.send intercepts outgoing requests that match specified criteria.
from odoo.tests.common import MockHTTPClient
with MockHTTPClient(
url='https://api.example.com/v1/items',
return_json={'id': 1, 'name': 'Widget'},
) as mock:
result = self.env['my.model']._fetch_item(1)
mock.assert_called_once()
self.assertEqual(result['name'], 'Widget')
Multiple MockHTTPClient instances can be nested to mock different endpoints independently in the same test. When a request does not match the inner mock, it falls through to the outer one.
It supports:
- return_json – either a fixed dict or a callable (request) > dict.
- return_status – HTTP status code (default 200).
- return_body – binary data for non-JSON responses.
- side_effect – callable which gets a PreparedRequest object just before sending and returning a response; useful for checking the outgoing requests.
Understanding HOOT in Odoo 20
Python tests can be used to ensure the correctness of backend logic; however, one cannot use them to validate how JavaScript widgets work inside the browser.
For instance, an OWL-based widget that draws a dashboard can have all its backend information correctly represented; nevertheless, one cannot check if this widget renders properly or performs any necessary actions in response to user interaction. This is when HOOT helps.
HOOT is the acronym for Hierarchically Organized Odoo Tests. HOOT is the JavaScript test library for Odoo. The HOOT test runner interface uses OWL, while the HOOT testing engine does not require OWL at all.
The primary exports of @odoo/hoot are the following:
Test structure
- beforeEach() and afterEach() – execute some code before and after each test.
- before() and after() – execute once at the beginning and end of a describe block, respectively.
Assertions
- expect() – the primary assertion function.
Mocks
- mockFetch() – intercept fetch() calls and return responses that you have configured.
- mockDate() – fixes the current date and time for deterministic tests with dates.
- mockTimeZone() – allows you to simulate a time zone.
- mockWebSocket(), mockWorker() – simulate WebSocket and Web Worker functionality.
DOM fixture
- getFixture() – returns a DOM node which is used as the mounting point for tests.
Available Matchers
HOOT does not include Jest or Jasmine matchers. The available matchers on expect() are:
toBe(), toEqual(), toBeCloseTo(), toBeEmpty(), toBeGreaterThan(), toBeLessThan(), toBeOfType(), toBeWithin(), toBeInstanceOf(), toHaveLength(), toInclude(), toMatch(), toMatchObject(), toThrow()
There is no toBeTruthy(), toBeFalsy(), toBeNull(), or toBeUndefined(). Use toBe(true) or toBe(false) where you would use toBeTruthy() or toBeFalsy() in Jest.
A Simple HOOT Test
import { expect, test } from "@odoo/hoot";
test("Basic calculation test", () => {
expect(2 + 2).toBe(4);
});Grouping Tests with describe
import { describe, expect, test, beforeEach } from "@odoo/hoot";
describe("Student record", () => {
let studentName;
beforeEach(() => {
studentName = "Alice";
});
test("name is set correctly", () => {
expect(studentName).toBe("Alice");
});
});mockDate and Timezone Behaviour
mockDate() initializes the clock in UTC format. In case the test is performed using a computer in a timezone ahead of UTC (for instance, UTC+5:30), "2025-08-31T23:59:59" UTC will be translated into September 1 locally, thereby potentially affecting month calculations and resulting in unpredictable failure. The dates used should be sufficiently within the boundaries of a month.
import { mockDate, test, expect } from "@odoo/hoot";
test("enrollment date is in September", () => {
mockDate("2025-09-15T12:00:00");
const today = new Date();
expect(today.getMonth()).toBe(8); // 0-indexed, 8 = September
});Where to Place HOOT Tests
JavaScript test files go inside the static/tests directory of the module:
my_module/
+-- static/
¦ +-- tests/
¦ +-- student.test.js
+-- tests/
¦ +-- __init__.py
¦ +-- test_student.py
+-- __init__.py
+-- __manifest__.py
JavaScript test files must end with .test.js to be recognised by the test runner. They must be included in the web.assets_unit_tests asset bundle in the manifest:
'assets': {
'web.assets_unit_tests': [
'my_module/static/tests/**/*',
],
},Running HOOT Tests in the Browser
Once the module is installed and the test files are registered in web.assets_unit_tests, open the HOOT test runner by navigating to:
http://localhost:8069/web/tests
This page is also available from Debug Menu > Run Unit Tests. The HOOT UI displays the complete framework name in the tooltip of the header: Hierarchically Organized Odoo Tests. The UI has the following sections:
Left panel: Suite tree
Listed in hierarchical order are all registered test suites, grouped first by modules and then by the describe() block. Your module's test suites will be listed under your module's name. Selecting a test suite from the left panel will filter the list to include only those test suites.
Top bar: Controls
The run button runs/starts a new test run from scratch.
The Suite drop-down allows you to choose either a particular suite or a file that you want to run individually.
The filter bar at the top takes the suite name, test name, and tags to filter the results.
Right panel: Results
Displayed in each row is a particular test. A green dot indicates a passing test, while a red dot indicates a failing test, and the expected and received values will be displayed under the row on a new line.
Filtering to your module only
To execute HOOT tests for your module, you have to enter your module name in the filter field at the top of the HOOT UI. The filter matches against the full suite path where the module name acts as a prefix. Another option for the filter field is the filter URL parameter:
http://localhost:8069/web/tests?filter=my_module
In case of the URL parameter, substitute my_module with your module name – the same as it appears in __manifest__.py and --test-tags /my_module. Available filter URL keys are filter (name alias), id (ids alias), and tag (tags alias).
If all the tests are successful, then the counter in the top right corner becomes green and displays the number. In the results pane, each line contains a green dot, the suite path (e.g., Basic assertions / simple arithmetic), and the execution time. The number is displayed in the left pane next to each suite name, in green.
Understanding Tours in Odoo 20
Unit tests for Python and JavaScript validate only certain elements of the program on their own. They cannot provide information about the correct operation of two elements in a workflow together.
Let us take a sales flow as an example: a user opens the Sales module, generates a quotation, adds items, confirms the sale, and validates the delivery. Validation of each element separately will not guarantee the proper work of the whole workflow.
For this reason, Odoo has such a concept as Tours. It represents a predefined list of actions to be performed by a user on the website.
How Tours Work
A tour has two parts:
- A JavaScript file that defines and registers the sequence of steps.
- A Python HttpCase test that launches the tour using start_tour().
JavaScript tour (student_tour.js)
import { registry } from "@web/core/registry";
registry.category("web_tour.tours").add("student_tour", {
steps: () => [
{
trigger: ".o_list_view .o_list_button_add",
content: "Click New to create a student.",
run: "click",
},
{
trigger: ".o_form_view .o_field_widget[name='name'] input",
content: "Type the student name.",
run: "edit TourStudent",
},
{
trigger: ".o_form_button_save",
content: "Save the record.",
run: "click",
},
{
trigger: ".o_form_view:not(.o_form_editable)",
content: "Wait for the save to complete.",
},
{
trigger: ".o_breadcrumb .o_back_button",
content: "Go back to the list.",
run: "click",
},
{
trigger: ".o_list_view .o_data_row td:contains('TourStudent')",
content: "Confirm the record appears in the list.",
},
],
});Python test
from odoo.tests import HttpCase, tagged
from odoo.tests.common import new_test_user
@tagged('post_install', '-at_install')
class TestStudentTour(HttpCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.tour_user = new_test_user(
cls.env,
login='tour_user',
groups='base.group_user,base.group_system',
)
def test_student_tour(self):
self.start_tour(
'/odoo/students',
'student_tour',
login='tour_user',
)
Why new_test_user and not admin
The login="admin" method may not work when there is an auth_passkey module installed on the database. This module interferes with the login process and does not allow logging in using passwords for users. To avoid such a problem, it is recommended to create a separate test user by using new_test_user().
Fields Selection in Tours
Selection fields in Odoo 20 are rendered through the SelectMenu OWL component, but not through the native <select>. Therefore, the action run "select value" will not work since it can be applied only to the native <select> element.
To handle a selection field in the tours, use two actions:
// Step 1: Open the dropdown
{
trigger: ".o_form_view .o_field_widget[name='grade'] .o_select_menu_toggler",
content: "Open the grade dropdown.",
run: "click",
},
// Step 2: Click the option
{
trigger: ".o_field_selection_menu .o_select_menu_item:contains('A')",
content: "Select grade A.",
run: "click",
},
Tours Must Not End on an Open Form
Odoo's test framework checks after the tour succeeds that no unsaved (dirty) form view is still open in the browser. If a tour ends immediately after a save click, the form may still be in edit mode while the save network request is in flight. This causes the test to fail with:
Tour finished with a dirty form view being open.
The tour must always:
- Wait for the form to leave edit mode: trigger: ".o_form_view:not(.o_form_editable)"
- Navigate away from the form (for example, click the breadcrumb back button) before the final step.
Starting the Tour at the Correct URL
Pass the exact URL of the view you want to test to start_tour(). This avoids needing navigation steps inside the tour and makes the tour simpler and more reliable.
self.start_tour('/odoo/students', 'student_tour', login='tour_user')If you start at /odoo and add steps to click through menus to reach the view, those steps break whenever the menu structure changes.
Understanding Test Tags in Odoo 20
Odoo uses a tagging mechanism to control when tests run. The @tagged() decorator assigns tags to test classes. A tag prefixed with - removes a tag.
Default Tags
Every test class that derives from BaseCase (including TransactionCase and HttpCase) automatically receives two default tags: standard and post_install. The standard tag is what --test-tags uses by default: when you specify a module path without a tag, only standard-tagged tests in that module run.
at_install
The at_install tag causes a test to run right after the corresponding module is installed, before subsequent modules are installed. To add at_install and remove the default post_install:
@tagged('at_install', '-post_install')
class TestInstallBehaviour(TransactionCase):
...post_install
The post_install tag (the default) causes a test to run after all modules have been installed. It is the correct choice for most tests, since they generally depend on the full Odoo environment. This is also the only tag appropriate for HttpCase tests; the source logs a warning if an HttpCase test is not tagged post_install.
Running Tests with --test-tags
The filter spec format is:
[-][tag][/module][:class][.method]
Run all standard tests in a module:
odoo-bin --test-tags /my_module -d <db> -u my_module
Run a specific class:
odoo-bin --test-tags /my_module:TestStudent -d <db> -u my_module
Run a specific method:
odoo-bin --test-tags /my_module:TestStudent.test_student_creation -d <db> -u my_module
Using --test-tags automatically enables test execution; there is no need to also pass --test-enable.
-u and -i
-u my_module should be used to update the module, whereas -i my_module should be used to install a new one when the module has been installed in the database. The -i option is simply ignored in case the module is already installed, which means no tests will be performed. By adding the -u option, you force Odoo to update the module and execute tests.
Blocking of HTTP Requests during Tests
Any test tagged with standard blocks all HTTP requests to non-localhost URLs by patching requests.Session.send. Thus, any HTTP request raises an exception, BlockRequest.
The above means that the module's tests cannot accidentally call some API. In order to perform tests in such a case, it is necessary to use MockHTTPClient.
Choosing the Right Test Type
| Testing Requirement | Recommended Approach |
| Testing model methods and business logic | TransactionCase |
| Testing computed fields and constraints | TransactionCase |
| Testing ORM operations and record creation | TransactionCase |
| Testing form defaults and onchange behaviour | Form helper |
| Testing user permissions and access rights | BaseCommon or TransactionCase with new_test_user() |
| Counting and verifying SQL queries | assertQueryCount / assertQueries |
| Capturing records created inside a method | RecordCapturer |
| Freezing dates for time-sensitive logic | freeze_time |
| Testing HTTP controllers and API endpoints | HttpCase |
| Testing website and portal requests | HttpCase |
| Mocking external API calls | MockHTTPClient |
| Testing OWL components and JavaScript | HOOT |
| Testing complete workflows through the browser | Tours with HttpCase |
There is an elaborate Odoo 20 test framework that includes backend, frontend, and workflow tests. The foundation of the Odoo 20 Python test framework is TransactionCase, whose tests run in isolation in a savepoint that automatically rolls back. HttpCase builds upon TransactionCase by providing HTTP and browser testing facilities. BaseCommon provides a complete configuration for tests that need a realistic user and company context. HOOT (Hierarchically Organized Odoo Tests) handles unit testing of JavaScript code, OWL components, and the frontend and shows output on the browser-based HOOT interface at /web/tests. Tests that check frontend-backend integration are conducted using tours provided by HttpCase.
Apart from these base testing classes, there are utilities like MockHTTPClient, freeze_time, assertQueryCount, RecordCapturer, and new_test_user() to meet certain specific testing requirements without writing duplicate code.
Using the appropriate testing layer for the requirement leads to a more efficient and maintainable test framework, which makes isolation of failure scenarios easier.
To read more about A Complete Guide to Testing in Odoo 19, refer to our blog, A Complete Guide to Testing in Odoo 19.