Home > Enterprise >  Defining a new Odoo ORM model and creating new records inside a test
Defining a new Odoo ORM model and creating new records inside a test

Time:06-04

I would like to define a new Odoo model and create a new record inside a test. Here is some example code demonstrating what I would like to accomplish:

from odoo.tests.common import TransactionCase
from odoo.fields import Char
from odoo.models import Model

class CreateModelInstanceTest(TransactionCase):
    def test_create_model_instance(self):
        class TestModel(Model):
            _name = "test.model"
            name = Char()

        self.env["test.model"].create([{"name": "Test"}])

However, the test fails with KeyError: 'test.model'. It seems that the model needs to be added to the registry first.

How can I add the new TestModel model to the registry from within a test?

CodePudding user response:

Check out the documentation before diving into this. https://www.odoo.com/documentation/15.0/developer/howtos/backend.html#

You should also watch a couple videos on Odoo's module building. https://www.youtube.com/watch?v=wwIniIlIrAc https://www.youtube.com/watch?v=Az8G4Y5r3Xg

Edit:

Sorry, maybe I'm confused by what you are trying to accomplish. This is how you should set up a test according to the documentation.

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

CodePudding user response:

I got some ideas on how to solve this from reading odoo/modules/registry.py and odoo/models.py. This is how I got the test passing:

class CreateModelInstanceTest(TransactionCase):
    def test_create_model_instance(self):
        class TestModel(Model):
            _name = "test.model"
            name = Char()

        model_name = TestModel._name

        self.registry.models[model_name] = TestModel._build_model(
            self.registry, self.cr
        )
        self.registry.setup_models(self.cr)
        self.registry.init_models(
            self.cr, [model_name], {"module": "test"}, install=True
        )

        name = "Name123"
        instance = self.env[model_name].create([{"name": name}])

        self.assertTrue(isinstance(instance, TestModel))
        self.assertEqual(instance.name, name)

I would be grateful if someone could please advise if this is the right/preferred way of doing it or if there is a more elegant, better solution as this seems very hacky. Are these BaseModel._build_model, Registry.setup_models and Registry.init_models methods and the Registry.models dictionary considered a stable interface by Odoo devs or will this break in future versions?

  • Related