+1 vote
29 views

Does anyone know how can you write mock tests for Odoo objects?

in Back-end by (10.5k points) | 29 views

1 Answer

+1 vote
Best answer
It can be done. The key is to know where to patch, but I cannot figure a clear rule for this because Odoo does tricks to your package name when it imports your module. So in your case, you may do the following:

from odoo import tests

from mock import patch

from my_module_2.models.ir_translations import IrTranslation

class TestMyModule2(tests.TransactionCase):

    def some_test_1(self):

        my_model = self.env['my.model'].create({})

        with patch.object(IrTranslation, 'force_translation') as mocked_translation:

            my_model.action_copy()

        mocked_translation.assert_called_once()

This works most of the time. If the patch does not work, you may need to import the class using relative import:

from ..models.ir_translations import IrTranslation

If that still does not work, you may need to patch in the setUp() method:

from odoo import tests

from mock import patch

from my_module_2.models.ir_translations import IrTranslation

class TestMyModule2(tests.TransactionCase):

    def setUp(self):

        super().setUp()  # don't forget this

        self._mocked_translation = patch.object(IrTranslation, 'force_translation').start()

        self.addCleanup(patch.stopall)

    def some_test_1(self):

        my_model = self.env['my.model'].create({})

        my_model.action_copy()

        self._mocked_translation.assert_called_once()

Some additional notes to save you some headaches:

If you use pyCharm, don't mock socket objects. It messes with pyCharm's mechanismes. Better to put your calls to socket into a one line method and mock that method instead.

datetime.datetime.now() cannot be mocked, as all builtin types, but fields.Datetime.now() can.
by (5k points)
selected by
205 questions
180 answers
37 comments
222,981 users