Skip to content

unclecatvn/agent-skills / skills/odoo-19.0

odoo-19

Verified

Odoo 19 development knowledge base with 18 specialized guides covering Actions (ir.actions.*, cron jobs, server actions), Controllers (HTTP routing, endpoints, auth types), Data files (XML/CSV records, shortcuts, noupdate), API Decorators (@api.depends, @api.constrains, @api.ondelete, @api.onchange, @api.model, @api.private), SQL Constraints (models.Constraint replacing _sql_constraints), Database Indexes (models.Index), Module development (manifest, wizards, reports), Field types (Char, Text, Monetary, relational fields), Manifest configuration (__manifest__.py, dependencies, asset bundles), Mixins (mail.thread, mail.activity.mixin, mail.alias.mixin, utm.mixin), ORM Model methods (search, CRUD, domain filters, recordsets, CamelCase model naming), Migration scripts (pre/post/end hooks, data migration), OWL frontend components (hooks, services, lifecycle), Performance optimization (N+1 prevention, batch ops, _read_group), QWeb Reports (PDF/HTML, paper formats, barcodes, t-out), Security/ACL (record rules, field permissions, privilege-based groups, @api.private), Testing (TransactionCase, HttpCase, mocking, query count assertions), Transactions (savepoints, UniqueViolation, serialization failures), Translations (i18n, PO files, translatable fields), XML Views (list/form/search, kanban card templates, xpath inheritance, QWeb templates). Use when writing, reviewing, or debugging any Odoo 19 Python or XML code, creating or modifying modules, fixing performance issues, or looking up Odoo 19 API patterns and best practices. Includes CSS/SCSS asset authoring and review for Odoo addons.

references/odoo-19-testing-guide.md

View on GitHub
# Odoo 19 Testing Guide

Guide for testing Odoo 19: Python unit tests, JS tests, and tours (integration tests).

## Table of Contents
- [Test Types](#test-types)
- [Python Tests](#python-tests)
- [Test Classes](#test-classes)
- [Test Decorators](#test-decorators)
- [Test Selection](#test-selection)
- [JS Tests](#js-tests)
- [Integration Tests (Tours)](#integration-tests-tours)
- [Performance Testing](#performance-testing)
- [Best Practices](#best-practices)

---

## Test Types

Odoo has three kinds of tests:

| Type | Purpose |
|------|---------|
| **Python unit tests** | Test model business logic |
| **JS unit tests** | Test JavaScript code in isolation |
| **Tours** | Integration testing (Python + JS together) |

---

## Python Tests

### Test Structure

Create a `tests` sub-package in your module:

```
your_module/
├── ...
├── tests/
│   ├── __init__.py
│   ├── test_bar.py
│   └── test_foo.py
```

**Important**: Import test modules from `tests/__init__.py`

```python
# tests/__init__.py
from . import test_foo, test_bar
```

### Test Methods

Test methods must start with `test_`:

```python
class TestModelA(TransactionCase):
    def test_some_action(self):
        record = self.env['model.a'].create({'field': 'value'})
        record.some_action()
        self.assertEqual(record.field, expected_value)
```

---

## Test Classes

### TransactionCase

Most common test class. Each test runs in its own transaction, rolled back at the end.

```python
from odoo.tests import TransactionCase

class TestMyModel(TransactionCase):
    def test_create_record(self):
        record = self.env['my.model'].create({'name': 'Test'})
        self.assertTrue(record.id)
        self.assertEqual(record.name, 'Test')
```

### SingleTransactionCase

Runs all tests in a single transaction (not rolled back). Faster, but tests can affect each other.

```python
from odoo.tests import SingleTransactionCase

class TestMyModel(SingleTransactionCase):
    def test_1_first(self):
        # Creates data
        pass

    def test_2_second(self):
        # Can use data from test_1_first
        pass
```

### HttpCase

For web-related tests. Starts a browser (headless Chrome by default).

```python
from odoo.tests import HttpCase

class TestWebsite(HttpCase):
    def test_homepage(self):
        self.url_open('/hello')
```

---

## Test Decorators

### tagged

Add or remove tags from test classes.

```python
from odoo.tests import TransactionCase, tagged

@tagged('-standard', 'nice')
class NiceTest(TransactionCase):
    pass
```

### Default Tags

- `standard` - Default tag (selected by `--test-tags`)
- `at_install` - Run after module installation (default)
- `post_install` - Run after all modules installed

```python
@tagged('-at_install', 'post_install')
class WebsiteVisitorTests(HttpCase):
    def test_create_visitor(self):
        pass
```

---

## Test Selection

### By Tag

```bash
# Run only nice tests
odoo-bin --test-tags nice

# Run nice and standard tests
odoo-bin --test-tags nice,standard

# Run standard except slow
odoo-bin --test-tags standard,-slow
```

### By Module

```bash
# Run only sale module tests
odoo-bin --test-tags /sale

# Run sale module but not slow tests
odoo-bin --test-tags '/sale,-slow'

# Run stock or slow tests
odoo-bin --test-tags '-standard, slow, /stock'
```

### By Specific Test

```bash
# Run specific test function
odoo-bin --test-tags .test_supplier_invoice

# Equivalent (full path)
odoo-bin --test-tags /account:TestAccount.test_supplier_invoice
```

### Tag Format

```
[-][tag][/module][:class][.method]
```

| Prefix | Meaning |
|--------|---------|
| `-` | Deselect/remove tag |
| `+` | Select/add tag (implicit, optional) |
| `/module` | Specific module |
| `:class` | Specific class |
| `.method` | Specific method |

---

## Test Utilities

### browse_ref

Browse an external ID:

```python
record = self.browse_ref('base.user_admin')
self.assertEqual(record.login, 'admin')
```

### ref

Get database ID from external ID:

```python
user_id = self.ref('base.user_admin')
```

### Form

Helper for testing form views:

```python
from odoo.tests import Form

with Form(self.env['sale.order']) as form:
    form.partner_id = self.partner
    form.date_order = '2023-01-01'
    with form.order_line.new() as line:
        line.product_id = self.product
        line.product_uom_qty = 10

order = form.save()
```

---

## JS Tests

Odoo uses Hoot for JS unit testing. See the frontend testing documentation.

Test files go in `static/tests/` and are named `*.test.js`:

```
your_module/
└── static/
    └── tests/
        └── my_test.test.js
```

```javascript
import { describe, expect, test } from "@odoo/hoot";
import { defineModels, fields, models } from "@web/../tests/web_test_helpers";

class MyModel extends models.Model {
    name = fields.Char();
}

defineModels([MyModel]);

describe("My Module", () => {
    test("my test", async () => {
        expect(true).toBe(true);
        // Test code here
    });
});
```

---

## Integration Tests (Tours)

Tours simulate real user scenarios in the browser.

### Tour Structure

```
your_module/
├── static/
│   └── tests/
│       └── tours/
│           └── my_tour.js
├── tests/
│   ├── __init__.py
│   └── test_my_tour.py
└── __manifest__.py
```

### Register Tour (JavaScript)

```javascript
import tour from 'web_tour.tour';

tour.register('my_tour', {
    url: '/web',
}, [
    // Step 1: Show apps menu
    tour.stepUtils.showAppsMenuItem(),
    // Step 2: Click on app
    {
        trigger: '.o_app[data-menu-xmlid="my_module.menu_root"]',
        run: "click",
    },
    // Step 3: Fill form
    {
        trigger: 'input[name="name"]',
        run: "text",
    },
    // Step 4: Verify
    {
        trigger: '.o_data_row:first',
        run: function () {
            // Assertions here
        },
    },
]);
```

### Add to Manifest

```python
'assets': {
    'web.assets_tests': [
        'your_module/static/tests/tours/my_tour.js',
    ],
},
```

### Start Tour (Python)

```python
from odoo.tests import HttpCase

class TestMyTour(HttpCase):
    def test_my_tour(self):
        self.start_tour("/web", "my_tour", login="admin")
```

### Tour Step Options

| Option | Description |
|--------|-------------|
| `trigger` | Selector/element to run action on |
| `run` | Action to perform (see helpers below) |
| `isActive` | Array of conditions (mobile, enterprise, auto/manual) |
| `content` | Tooltip content |
| `tooltipPosition` | `top`, `right`, `bottom`, or `left` |
| `timeout` | Wait time in ms (default: 10000) |

### Run Actions

| Action | Description |
|--------|-------------|
| `click` | Clicks the element |
| `dblclick` | Double-clicks the element |
| `drag_and_drop {target}` | Drags to target |
| `edit {content}` | Clears and fills |
| `editor {content}` | WYSIWYG editor fill |
| `fill {content}` | Fills the element |
| `hover` | Hovers over element |
| `press {content}` | Keyboard input |
| `range {content}` | Range slider value |
| `select {value}` | Select by value |
| `selectByIndex {index}` | Select by index |
| `selectByLabel {label}` | Select by label |
| `check` | Checks checkbox |
| `uncheck` | Unchecks checkbox |
| `clear` | Clears input |

### Run Tour from Browser

```javascript
odoo.startTour("tour_name");
```

Or use `?debug=tests` URL parameter.

### Debug Tours

```python
# Watch mode (opens Chrome window)
self.start_tour("/web", "my_tour", watch=True)

# Debug mode (opens devtools)
self.start_tour("/web", "my_tour", debug=True)
```

### Onboarding Tours

Onboarding tours are interactive guides for users.

Create `web_tour.tour` record:

```xml
<record id="my_tour" model="web_tour.tour">
    <field name="name">my_tour</field>
    <field name="sequence">10</field>
    <field name="rainbow_man_message">Great job!</field>
</record>
```

Add to manifest:

```python
'data': [
    'data/my_tour.xml',
],
'assets': {
    'web.assets_backend': [
        'your_module/static/src/js/tours/my_tour.js',
    ],
},
```

---

## Performance Testing

### Query Count Testing

Use `assertQueryCount` to establish query limits:

```python
with self.assertQueryCount(11):
    do_something()
```

### Per-System Limits

```python
with self.assertQueryCount(__system__=1211):
    do_something()
```

---

## Best Practices

### Regression and error-path coverage

Every reproducible bug fix should include a test that fails before the fix and passes afterward. New behavior should cover its success path and important error paths.

### Lowest practical permissions

Use `new_test_user()` and `@users` to exercise access-sensitive flows as the least privileged user that should be allowed to perform them. This avoids false positives from tests that run as an administrator.

### Deterministic, isolated fixtures

Create the data needed by the test instead of relying on demo records. Database changes are not rolled back between `subTest` cases, so use unique fixtures or explicitly reset state for each case.

Records stored on a class or test instance retain their original `.env` (including user, context, cursor, and sudo state). After changing the test environment, use `record.with_env(self.env)` before asserting access behavior.

Use fixed dates instead of `datetime.now()` or `datetime.today()` in assertions. Odoo 19 provides the helper through `odoo.tests.common`:

```python
from datetime import datetime
from odoo.tests import TransactionCase
from odoo.tests.common import freeze_time

class TestSomething(TransactionCase):
    @freeze_time("2024-01-01 10:10:10")
    def test_creation_time(self):
        partner = self.env["res.partner"].create({"name": "Foo"})
        self.assertEqual(partner.create_date, datetime(2024, 1, 1, 10, 10, 10))
```

### Mock external services by default

Use `self.patch()`, `self.classPatch()`, or `self.startPatcher()` to isolate network and other external services. If a live integration test is necessary, keep it out of the standard test selection with an explicit test tag such as `external`.

### Treat coverage drops as a test signal

When coverage decreases after a change, inspect the uncovered paths and add tests where the behavior is meaningful rather than lowering the expectation.

---

## Running Tests

Enable tests when starting Odoo:

```bash
# Enable tests
odoo-bin --test-enable

# With specific tags
odoo-bin --test-tags post_install

# Specific module
odoo-bin -i my_module --test-enable

# Update and test
odoo-bin -u my_module --test-enable
```

Odoo 19 creates new databases **without** demo data unless `--with-demo` is passed, so a
fresh `-d test_db -i my_module --test-enable` run has no demo records and no `demo` /
`portal` users. Create fixtures in `setUpClass` (e.g. `new_test_user()`) instead of
referencing demo XML IDs.

---

## Screenshot and Screencast

When `HttpCase.browser_js` tests fail:

- Screenshot saved to: `/tmp/odoo_tests/{db_name}/screenshots/`

CLI options:

```bash
odoo-bin --screenshots /tmp/screenshots
odoo-bin --screencasts /tmp/screencasts
```

---

## Special Tags Reference

| Tag | Description |
|-----|-------------|
| `standard` | Default tag for BaseCase subclasses |
| `at_install` | Run after module installation (default) |
| `post_install` | Run after all modules installed |
| `-standard` | Remove from default |
| `-at_install` | Don't run at install (use with `post_install`) |

---

## References

- Source: Odoo 19 documentation `/doc/developer/reference/backend/testing.rst`
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall