size
int64
0
304k
ext
stringclasses
1 value
lang
stringclasses
1 value
branch
stringclasses
1 value
content
stringlengths
0
304k
avg_line_length
float64
0
238
max_line_length
int64
0
304k
866
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from psycopg2.errorcodes import SERIALIZATION_FAILURE from psycopg2 import OperationalError from odoo import http # Force serialization errors. Patched in some tests. should_fail = None class SerializationFailureError(OperationalError): pgcode = SERIALIZATION_FAILURE class HttpTest(http.Controller): @http.route("/test_http/upload_file", methods=["POST"], type="http", auth="none", csrf=False) def upload_file_retry(self, ufile): global should_fail # pylint: disable=W0603 if should_fail is None: raise ValueError("should_fail should be set.") data = ufile.read() if should_fail: should_fail = False # Fail once raise SerializationFailureError() return data.decode()
29.862069
866
316
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Test HTTP', 'version': '1.0', 'category': 'Hidden/Tests', 'description': """A module to test HTTP""", 'depends': ['base', 'web', 'web_tour'], 'installable': True, 'data': [], 'license': 'LGPL-3', }
28.727273
316
689
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from io import StringIO from unittest.mock import patch from odoo.tests import common, tagged @tagged('-at_install', 'post_install') class TestHttpUpload(common.HttpCase): def test_upload_file_retry(self): from odoo.addons.test_http import controllers # pylint: disable=C0415 with patch.object(controllers, "should_fail", True), StringIO("Hello world!") as file: res = self.url_open("/test_http/upload_file", files={"ufile": file}, timeout=None) self.assertEqual(res.status_code, 200) self.assertEqual(res.text, file.getvalue())
40.529412
689
1,085
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time import sys from odoo import models, api class m(models.Model): """ This model exposes a few methods that will consume between 'almost no resource' and 'a lot of resource'. """ _name = 'test.limits.model' _description = 'Test Limits Model' @api.model def consume_nothing(self): return True @api.model def consume_memory(self, size): l = [0] * size return True @api.model def leak_memory(self, size): if not hasattr(self, 'l'): type(self).l = [] self.l.append([0] * size) return True @api.model def consume_time(self, seconds): time.sleep(seconds) return True @api.model def consume_cpu_time(self, seconds): t0 = time.process_time() t1 = time.process_time() while t1 - t0 < seconds: for i in range(10000000): x = i * i t1 = time.process_time() return True
24.111111
1,085
378
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'test-limits', 'version': '0.1', 'category': 'Hidden/Tests', 'description': """A module with dummy methods.""", 'depends': ['base'], 'data': ['ir.model.access.csv'], 'installable': True, 'auto_install': False, 'license': 'LGPL-3', }
29.076923
378
9,340
py
PYTHON
15.0
# -*- coding: utf-8 -*- from __future__ import division from itertools import count, zip_longest from odoo import api, fields, models, Command class A(models.Model): _name = 'test_testing_utilities.a' _description = 'Testing Utilities A' f1 = fields.Char(required=True) f2 = fields.Integer(default=42) f3 = fields.Integer() f4 = fields.Integer(compute='_compute_f4') f5 = fields.Integer() f6 = fields.Integer() @api.onchange('f2') def _on_change_f2(self): self.f3 = int(self.f2 / 2) self.f5 = self.f2 self.f6 = self.f2 @api.depends('f1', 'f2') def _compute_f4(self): for r in self: r.f4 = r.f2 / (int(r.f1) or 1) class B(models.Model): _name = 'test_testing_utilities.readonly' _description = 'Testing Utilities Readonly' f1 = fields.Integer(default=1, readonly=True) f2 = fields.Integer(compute='_compute_f2') @api.depends('f1') def _compute_f2(self): for r in self: r.f2 = 2 * r.f1 class C(models.Model): _name = 'test_testing_utilities.c' _description = 'Testing Utilities C' name = fields.Char("name", required=True) f2 = fields.Many2one('test_testing_utilities.m2o') @api.onchange('f2') def _on_change_f2(self): self.name = self.f2.name class M2O(models.Model): _name = 'test_testing_utilities.m2o' _description = 'Testing Utilities Many To One' name = fields.Char(required=True) class M2Onchange(models.Model): _name = 'test_testing_utilities.d' _description = 'Testing Utilities D' # used to check that defaults & onchange to m2o work f = fields.Many2one( 'test_testing_utilities.m2o', required=True, default=lambda self: self.env['test_testing_utilities.m2o'].search( [], limit=1 ) ) f2 = fields.Char() @api.onchange('f2') def _on_change_f2(self): self.f = self.env['test_testing_utilities.m2o'].search([ ('name', 'ilike', self.f2), ], limit=1) if self.f2 else False class M2MChange(models.Model): _name = 'test_testing_utilities.e' _description = 'Testing Utilities E' m2m = fields.Many2many('test_testing_utilities.sub2') count = fields.Integer(compute='_m2m_count', inverse='_set_count') @api.depends('m2m') def _m2m_count(self): for r in self: r.count = len(r.m2m) def _set_count(self): for r in self: r.write({ 'm2m': [ Command.create({'name': str(n)}) for n, v in zip_longest(range(r.count), r.m2m or []) if v is None ] }) class M2MSub(models.Model): _name = 'test_testing_utilities.sub2' _description = 'Testing Utilities Subtraction 2' name = fields.Char() m2o_ids = fields.Many2many('test_testing_utilities.m2o') class M2MChange2(models.Model): _name = 'test_testing_utilities.f' _description = 'Testing Utilities F' def _get_some(self): r = self.env['test_testing_utilities.sub2'].search([], limit=2) return r m2m = fields.Many2many( 'test_testing_utilities.sub2', default=_get_some, ) m2o = fields.Many2one('test_testing_utilities.sub2') @api.onchange('m2o') def _on_change_m2o(self): self.m2m = self.m2m | self.m2o class M2MReadonly(models.Model): _name = 'test_testing_utilities.g' _description = 'Testing Utilities G' m2m = fields.Many2many('test_testing_utilities.sub3', readonly=True) class M2MSub3(models.Model): _name = 'test_testing_utilities.sub3' _description = 'Testing Utilities Subtraction 3' name = fields.Char() class O2MChange(models.Model): _name = 'test_testing_utilities.parent' _description = 'Testing Utilities Parent' value = fields.Integer(default=1) v = fields.Integer() subs = fields.One2many('test_testing_utilities.sub', 'parent_id') @api.onchange('value', 'subs') def _onchange_values(self): self.v = self.value + sum(s.value for s in self.subs) class O2MSub(models.Model): _name = 'test_testing_utilities.sub' _description = 'Testing Utilities Subtraction' name = fields.Char(compute='_compute_name') value = fields.Integer(default=2) v = fields.Integer() parent_id = fields.Many2one('test_testing_utilities.parent') has_parent = fields.Boolean() @api.onchange('value') def _onchange_value(self): self.v = self.value @api.depends('v') def _compute_name(self): for r in self: r.name = str(r.v) @api.onchange('has_parent') def _onchange_has_parent(self): if self.has_parent: self.value = self.parent_id.value class O2MDefault(models.Model): _name = 'test_testing_utilities.default' _description = 'Testing Utilities Default' def _default_subs(self): return [ Command.create({'v': 5}) ] value = fields.Integer(default=1) v = fields.Integer() subs = fields.One2many('test_testing_utilities.sub3', 'parent_id', default=_default_subs) class O2MSub3(models.Model): _name = 'test_testing_utilities.sub3' _description = 'Testing Utilities Subtraction 3' name = fields.Char(compute='_compute_name') value = fields.Integer(default=2) v = fields.Integer(default=6) parent_id = fields.Many2one('test_testing_utilities.default') @api.onchange('value') def _onchange_value(self): self.v = self.value @api.depends('v') def _compute_name(self): for r in self: r.name = str(r.v) class O2MRecursive(models.Model): _name = _description = 'test_testing_utilities.recursive' one_to_many_id = fields.Many2one('test_testing_utilities.recursive', readonly=True) many_to_one_ids = fields.One2many('test_testing_utilities.recursive', 'one_to_many_id', readonly=True) class O2MOnchangeParent(models.Model): _name = 'test_testing_utilities.onchange_parent' _description = 'Testing Utilities Onchange Parent' line_ids = fields.One2many('test_testing_utilities.onchange_line', 'parent') @api.onchange('line_ids') def _onchange_line_ids(self): for line in self.line_ids.filtered(lambda l: l.flag): self.env['test_testing_utilities.onchange_line'].new({'parent': self.id}) class M2OOnchangeLine(models.Model): _name = 'test_testing_utilities.onchange_line' _description = 'Testing Utilities Onchange Line' parent = fields.Many2one('test_testing_utilities.onchange_parent') dummy = fields.Float() flag = fields.Boolean(store=False) @api.onchange('dummy') def _onchange_flag(self): self.flag = True class O2MChangeCount(models.Model): _name = 'test_testing_utilities.onchange_count' _description = _name count = fields.Integer() line_ids = fields.One2many('test_testing_utilities.onchange_count_sub', 'parent') @api.onchange('count') def _onchange_count(self): Sub = self.env['test_testing_utilities.onchange_count_sub'] recs = Sub for i in range(self.count): recs |= Sub.new({'name': str(i)}) self.line_ids = recs class O2MChangeSub(models.Model): _name = 'test_testing_utilities.onchange_count_sub' _description = _name parent = fields.Many2one('test_testing_utilities.onchange_count') name = fields.Char() class O2MReadonlySubfield(models.Model): _name = 'o2m_readonly_subfield_parent' _description = _name line_ids = fields.One2many('o2m_readonly_subfield_child', 'parent_id') class O2MReadonlySubfieldChild(models.Model): _name = _description = 'o2m_readonly_subfield_child' name = fields.Char() parent_id = fields.Many2one('o2m_readonly_subfield_parent') f = fields.Integer(compute='_compute_f', inverse='_inverse_f', readonly=True) @api.depends('name') def _compute_f(self): for r in self: r.f = len(r.name) if r.name else 0 def _inverse_f(self): raise AssertionError("Inverse of f should not be called") class ReqBool(models.Model): _name = _description = 'test_testing_utilities.req_bool' f_bool = fields.Boolean(required=True) class O2MChangesParent(models.Model): _name = _description = 'o2m_changes_parent' name = fields.Char() line_ids = fields.One2many('o2m_changes_children', 'parent_id') @api.onchange('name') def _onchange_name(self): for line in self.line_ids: line.line_ids = [Command.delete(l.id) for l in line.line_ids] + [ Command.create({'v': 0, 'vv': 0}) ] class O2MChangesChildren(models.Model): _name = _description = 'o2m_changes_children' name = fields.Char() v = fields.Integer() line_ids = fields.One2many('o2m_changes_children.lines', 'parent_id') parent_id = fields.Many2one('o2m_changes_parent') @api.onchange('v') def _onchange_v(self): for record in self: for line in record.line_ids: line.v = record.v class O2MChangesChildrenLines(models.Model): _name = _description = 'o2m_changes_children.lines' parent_id = fields.Many2one('o2m_changes_children') v = fields.Integer() vv = fields.Integer()
29.556962
9,340
6,079
py
PYTHON
15.0
from lxml.builder import E from odoo import fields, models, api, Command class Product(models.Model): _name = _description = 'ttu.product' class Root(models.Model): _name = _description = 'ttu.root' product_id = fields.Many2one('ttu.product') product_qty = fields.Integer() qty_producing = fields.Integer() qty_produced = fields.Integer(compute='_get_produced_qty') move_raw_ids = fields.One2many('ttu.child', 'root_raw_id') move_finished_ids = fields.One2many('ttu.child', 'root_id') @api.depends('move_finished_ids.move_line_ids.qty_done') def _get_produced_qty(self): for r in self: r.qty_produced = sum(r.mapped('move_finished_ids.move_line_ids.qty_done')) @api.onchange('qty_producing') def _onchange_producing(self): production_move = self.move_finished_ids.filtered( lambda move: move.product_id == self.product_id ) if not production_move: # Happens when opening the mo? return for line in production_move.move_line_ids: line.qty_done = 0 qty_producing = self.qty_producing - self.qty_produced vals = production_move._set_quantity_done_prepare_vals(qty_producing) if vals['to_create']: for res in vals['to_create']: production_move.move_line_ids.new(res) if vals['to_write']: for move_line, res in vals['to_write']: move_line.update(res) for move in (self.move_raw_ids | self.move_finished_ids.filtered(lambda m: m.product_id != self.product_id)): new_qty = qty_producing * move.unit_factor for line in move.move_line_ids: line.qty_done = 0 vals = move._set_quantity_done_prepare_vals(new_qty) if vals['to_create']: for res in vals['to_create']: move.move_line_ids.new(res) if vals['to_write']: for move_line, res in vals['to_write']: move_line.update(res) def _get_default_form_view(self): move_subview = E.tree( {'editable': 'bottom'}, E.field(name='product_id'), E.field(name='unit_factor'), E.field(name='quantity_done'), E.field( {'name': 'move_line_ids', 'invisible': '1'}, E.tree( E.field(name='qty_done', invisible='1'), E.field(name='product_id', invisible='1'), E.field(name='move_id', invisible='1'), E.field(name='id', invisible='1'), ) ) ) t = E.form( E.field(name='product_id'), E.field(name='product_qty'), E.field(name='qty_producing'), E.field({'name': 'move_raw_ids', 'on_change': '1'}, move_subview), E.field({'name': 'move_finished_ids', 'on_change': '1'}, move_subview), ) # deoptimise to ensure we call onchange most of the time, as im the real # case this is done as a result of the metric fuckton of computes, but # here the near complete lack of computes causes most of the onchange # triggers to get disabled for f in t.iter('field'): f.set('on_change', '1') return t class Child(models.Model): _name = _description = 'ttu.child' product_id = fields.Many2one('ttu.product') unit_factor = fields.Integer(default=1, required=True) # should be computed but we can ignore that quantity_done = fields.Integer( compute='_quantity_done_compute', inverse='_quantity_done_set' ) root_raw_id = fields.Many2one('ttu.root') root_id = fields.Many2one('ttu.root') move_line_ids = fields.One2many('ttu.grandchild', 'move_id') def _set_quantity_done_prepare_vals(self, qty): res = {'to_write': [], 'to_create': []} for ml in self.move_line_ids: ml_qty = ml.product_uom_qty - ml.qty_done if ml_qty <= 0: continue taken_qty = min(qty, ml_qty) res['to_write'].append((ml, {'qty_done': ml.qty_done + taken_qty})) qty -= taken_qty if qty <= 0: break if qty > 0: res['to_create'].append({ 'move_id': self.id, 'product_id': self.product_id.id, 'product_uom_qty': 0, 'qty_done': qty, }) return res @api.depends('move_line_ids.qty_done') def _quantity_done_compute(self): for move in self: move.quantity_done = sum(move.mapped('move_line_ids.qty_done')) def _quantity_done_set(self): quantity_done = self[0].quantity_done # any call to create will invalidate `move.quantity_done` for move in self: move_lines = move.move_line_ids if not move_lines: if quantity_done: # do not impact reservation here move_line = self.env['ttu.grandchild'].create({ 'move_id': move.id, 'product_id': move.product_id.id, 'product_uom_qty': 0, 'qty_done': quantity_done, }) move.write({'move_line_ids': [Command.link(move_line.id)]}) elif len(move_lines) == 1: move_lines[0].qty_done = quantity_done else: # Bypass the error if we're trying to write the same value. ml_quantity_done = sum(l.qty_done for l in move_lines) assert quantity_done == ml_quantity_done, "Cannot set the done quantity from this stock move, work directly with the move lines." class Grandchild(models.Model): _name = _description = 'ttu.grandchild' product_id = fields.Many2one('ttu.product') product_uom_qty = fields.Integer() qty_done = fields.Integer() move_id = fields.Many2one('ttu.child')
38.232704
6,079
398
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': "Test testing utilities", 'category': "Hidden/Tests", 'description': """Non-trivial testing utilities can require models & all This here module is useful to validate that they're doing what they're supposed to do """, 'depends': ['base'], 'data': [ 'ir.model.access.csv', 'menu.xml', ], 'license': 'LGPL-3', }
24.875
398
3,465
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import itertools from unittest import mock, TestCase import psycopg2 from odoo.exceptions import AccessError from odoo.sql_db import BaseCursor from odoo.tests import common from odoo.tools import mute_logger class CustomError(Exception): ... class TestBasic(common.TransactionCase): def test_assertRecordValues(self): X1 = {'f1': "X", 'f2': 1} Y2 = {'f1': "Y", 'f2': 2} Y3 = {'f1': "Y", 'f2': 3} records = self.env['test_testing_utilities.a'].create([X1, Y2]) self.assertRecordValues(records, [X1, Y2]) with self.assertRaises(AssertionError): # order should match self.assertRecordValues(records, [Y2, X1]) # fail if wrong size with self.assertRaises(AssertionError): self.assertRecordValues(records, [X1]) with self.assertRaises(AssertionError): self.assertRecordValues(records, [X1, Y2, Y3]) # fail if fields don't match with self.assertRaises(AssertionError): self.assertRecordValues(records, [X1, Y3]) with self.assertRaises(AssertionError): self.assertRecordValues(records, [Y3, X1]) def test_assertRaises_rollbacks(self): """Checks that a "correctly" executing assertRaises (where the expected exception has been raised and caught) will properly rollback. """ self.env.cr.execute("SET LOCAL test_testing_utilities.a_flag = ''") with self.assertRaises(CustomError): self.env.cr.execute("SET LOCAL test_testing_utilities.a_flag = 'yes'") raise CustomError self.env.cr.execute("SHOW test_testing_utilities.a_flag") self.assertEqual(self.env.cr.fetchone(), ('',)) def test_assertRaises_error(self): """Checks that an exception raised during the *setup* of assertRaises bubbles up correctly. Raises an exception when `savepoint()` calls `flush()` during setup. """ # ensure we catch the error with the "base" method to avoid any interference with mock.patch.object(BaseCursor, 'flush', side_effect=CustomError), \ TestCase.assertRaises(self, CustomError): with self.assertRaises(CustomError): raise NotImplementedError @mute_logger('odoo.sql_db') def test_assertRaises_clear_recovery(self): """Checks that the savepoint is correctly rolled back if an error occurs during the assertRaises setup Raises an exception during the first `clear()` calls which immediately follows the initialisation of the savepoint iff we're expecting an AccessError. """ # on the first `clear` call, break the current transaction with nonsense # (on further calls do nothing as savepoint() needs to clear() for its # own recovery) def clear(call_count=itertools.count()): if next(call_count) == 0: self.env.cr.execute('select nonsense') with mock.patch.object(BaseCursor, 'clear', side_effect=clear),\ TestCase.assertRaises(self, psycopg2.Error): with self.assertRaises(AccessError): raise NotImplementedError # check that the transaction has been rolled back and we can perform # queries again self.env.cr.execute('select 1')
38.932584
3,465
2,302
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common from odoo.tools.xml_utils import _check_with_xsd import base64 from lxml.etree import XMLSchemaError class TestLXML(common.TransactionCase): def test_lxml_import_from_filestore(self): resolver_schema_int = b""" <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:etype="http://codespeak.net/lxml/test/external"> <xsd:import namespace="http://codespeak.net/lxml/test/external" schemaLocation="imported_schema.xsd"/> <xsd:element name="a" type="etype:AType"/> </xsd:schema> """ incomplete_schema_int = b""" <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:etype="http://codespeak.net/lxml/test/external"> <xsd:import namespace="http://codespeak.net/lxml/test/external" schemaLocation="non_existing_schema.xsd"/> <xsd:element name="a" type="etype:AType"/> </xsd:schema> """ imported_schema = b""" <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://codespeak.net/lxml/test/external"> <xsd:complexType name="AType"> <xsd:sequence><xsd:element name="b" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/></xsd:sequence> </xsd:complexType> </xsd:schema> """ self.env['ir.attachment'].create([{ 'datas': base64.b64encode(resolver_schema_int), 'name': 'resolver_schema_int.xsd' }, { 'datas': base64.b64encode(incomplete_schema_int), 'name': 'incomplete_schema_int.xsd' }, { 'datas': base64.b64encode(imported_schema), 'name': 'imported_schema.xsd' }]) _check_with_xsd("<a><b></b></a>", 'resolver_schema_int.xsd', self.env) with self.assertRaises(XMLSchemaError): _check_with_xsd("<a><b></b></a>", 'incomplete_schema_int.xsd', self.env) with self.assertRaises(FileNotFoundError): _check_with_xsd("<a><b></b></a>", 'non_existing_schema.xsd', self.env)
42.62963
2,302
25,459
py
PYTHON
15.0
# -*- coding: utf-8 -*- """ Test for the pseudo-form implementation (odoo.tests.common.Form), which should basically be a server-side implementation of form views (though probably not complete) intended for properly validating business "view" flows (onchanges, readonly, required, ...) and make it easier to generate sensible & coherent business objects. """ from operator import itemgetter from odoo.tests.common import TransactionCase, Form from odoo import Command class TestBasic(TransactionCase): def test_defaults(self): """ Checks that we can load a default form view and perform trivial default_get & onchanges & computations """ f = Form(self.env['test_testing_utilities.a']) self.assertEqual(f.id, False, "check that our record is not in db (yet)") self.assertEqual(f.f2, 42) self.assertEqual(f.f3, 21) self.assertEqual(f.f4, 42) f.f1 = '4' self.assertEqual(f.f2, 42) self.assertEqual(f.f3, 21) self.assertEqual(f.f4, 10) f.f2 = 8 self.assertEqual(f.f3, 4) self.assertEqual(f.f4, 2) r = f.save() self.assertEqual( (r.f1, r.f2, r.f3, r.f4), ('4', 8, 4, 2), ) def test_required(self): f = Form(self.env['test_testing_utilities.a']) # f1 no default & no value => should fail with self.assertRaisesRegex(AssertionError, 'f1 is a required field'): f.save() # set f1 and unset f2 => should work f.f1 = '1' f.f2 = False r = f.save() self.assertEqual( (r.f1, r.f2, r.f3, r.f4), ('1', 0, 0, 0) ) def test_required_bool(self): f = Form(self.env['test_testing_utilities.req_bool']) f.f_bool = False r = f.save() self.assertEqual(r.f_bool, 0) f2 = Form(self.env['test_testing_utilities.req_bool']) r2 = f2.save() self.assertEqual(r2.f_bool, 0) def test_readonly(self): """ Checks that fields with readonly modifiers (marked as readonly or computed w/o set) raise an error when set. """ f = Form(self.env['test_testing_utilities.readonly']) with self.assertRaises(AssertionError): f.f1 = '5' with self.assertRaises(AssertionError): f.f2 = 42 def test_readonly_save(self): """ Should not save readonly fields unless they're force_save """ f = Form(self.env['test_testing_utilities.a'], view='test_testing_utilities.non_normalized_attrs') f.f1 = '1' f.f2 = 987 self.assertEqual(f.f5, 987) self.assertEqual(f.f6, 987) r = f.save() self.assertEqual(r.f5, 0) self.assertEqual(r.f6, 987) def test_attrs(self): """ Checks that attrs/modifiers with non-normalized domains work """ f = Form(self.env['test_testing_utilities.a'], view='test_testing_utilities.non_normalized_attrs') # not readonly yet, should work f.f2 = 5 # make f2 readonly f.f1 = '63' f.f3 = 5 with self.assertRaises(AssertionError): f.f2 = 6 class TestM2O(TransactionCase): def test_default_and_onchange(self): """ Checks defaults & onchanges impacting m2o fields """ Sub = self.env['test_testing_utilities.m2o'] a = Sub.create({'name': "A"}) b = Sub.create({'name': "B"}) f = Form(self.env['test_testing_utilities.d']) self.assertFalse( f.f, "The default value gets overridden by the onchange" ) f.f2 = "B" self.assertEqual( f.f, b, "The new m2o value should match the second field by name" ) f.save() def test_set(self): """ Checks that we get/set recordsets for m2o & that set correctly triggers onchange """ r1 = self.env['test_testing_utilities.m2o'].create({'name': "A"}) r2 = self.env['test_testing_utilities.m2o'].create({'name': "B"}) f = Form(self.env['test_testing_utilities.c']) # check that basic manipulations work f.f2 = r1 self.assertEqual(f.f2, r1) self.assertEqual(f.name, 'A') f.f2 = r2 self.assertEqual(f.name, 'B') # can't set an int to an m2o field with self.assertRaises(AssertionError): f.f2 = r1.id self.assertEqual(f.f2, r2) self.assertEqual(f.name, 'B') # can't set a record of the wrong model temp = self.env['test_testing_utilities.readonly'].create({}) with self.assertRaises(AssertionError): f.f2 = temp self.assertEqual(f.f2, r2) self.assertEqual(f.name, 'B') r = f.save() self.assertEqual(r.f2, r2) class TestM2M(TransactionCase): def test_add(self): Sub = self.env['test_testing_utilities.sub2'] f = Form(self.env['test_testing_utilities.e']) r1 = Sub.create({'name': "Item"}) r2 = Sub.create({'name': "Item2"}) f.m2m.add(r1) f.m2m.add(r2) r = f.save() self.assertEqual( r.m2m, r1 | r2 ) def test_remove_by_index(self): Sub = self.env['test_testing_utilities.sub2'] f = Form(self.env['test_testing_utilities.e']) r1 = Sub.create({'name': "Item"}) r2 = Sub.create({'name': "Item2"}) f.m2m.add(r1) f.m2m.add(r2) f.m2m.remove(index=0) r = f.save() self.assertEqual( r.m2m, r2 ) def test_remove_by_id(self): Sub = self.env['test_testing_utilities.sub2'] f = Form(self.env['test_testing_utilities.e']) r1 = Sub.create({'name': "Item"}) r2 = Sub.create({'name': "Item2"}) f.m2m.add(r1) f.m2m.add(r2) f.m2m.remove(id=r1.id) r = f.save() self.assertEqual( r.m2m, r2 ) def test_on_m2m_change(self): Sub = self.env['test_testing_utilities.sub2'] f = Form(self.env['test_testing_utilities.e']) self.assertEqual(f.count, 0) f.m2m.add(Sub.create({'name': 'a'})) self.assertEqual(f.count, 1) f.m2m.add(Sub.create({'name': 'a'})) f.m2m.add(Sub.create({'name': 'a'})) f.m2m.add(Sub.create({'name': 'a'})) self.assertEqual(f.count, 4) f.m2m.remove(index=0) f.m2m.remove(index=0) f.m2m.remove(index=0) self.assertEqual(f.count, 1) def test_m2m_changed(self): r1 = self.env['test_testing_utilities.m2o'].create({'name': "A"}) r2 = self.env['test_testing_utilities.m2o'].create({'name': "B"}) Sub = self.env['test_testing_utilities.sub2'] a = Sub.create({'name': 'a'}) b = Sub.create({'name': 'b'}) c = Sub.create({'name': 'c', 'm2o_ids': [Command.set([r1.id, r2.id])]}) d = Sub.create({'name': 'd'}) f = Form(self.env['test_testing_utilities.f']) # check default_get self.assertEqual(f.m2m[:], a | b) f.m2o = c self.assertEqual(f.m2m[:], a | b | c) f.m2o = d self.assertEqual(f.m2m[:], a | b | c | d) def test_m2m_readonly(self): Sub = self.env['test_testing_utilities.sub3'] a = Sub.create({'name': 'a'}) b = Sub.create({'name': 'b'}) r = self.env['test_testing_utilities.g'].create({ 'm2m': [Command.set(a.ids)] }) f = Form(r) with self.assertRaises(AssertionError): f.m2m.add(b) with self.assertRaises(AssertionError): f.m2m.remove(id=a.id) f.save() self.assertEqual(r.m2m, a) def test_attr(self): f = Form(self.env['test_testing_utilities.e'], view='test_testing_utilities.attrs_using_m2m') with self.assertRaises(AssertionError): f.count = 5 f.m2m.add(self.env['test_testing_utilities.sub2'].create({'name': 'ok'})) f.count = 5 r = f.save() self.assertEqual( r.m2m.mapped('name'), ['ok', '1', '2', '3', '4'] ) get = itemgetter('name', 'value', 'v') class TestO2M(TransactionCase): def test_basic_alterations(self): """ Tests that the o2m proxy allows adding, removing and editing o2m records """ f = Form(self.env['test_testing_utilities.parent'], view='test_testing_utilities.o2m_parent') f.subs.new().save() f.subs.new().save() f.subs.new().save() f.subs.remove(index=0) r = f.save() self.assertEqual( [get(s) for s in r.subs], [("2", 2, 2), ("2", 2, 2)] ) self.assertEqual(r.v, 5) with Form(r, view='test_testing_utilities.o2m_parent') as f: with f.subs.new() as sub: sub.value = 5 f.subs.new().save() with f.subs.edit(index=2) as sub: self.assertEqual(sub.v, 5) f.subs.remove(index=0) self.assertEqual( [get(s) for s in r.subs], [("2", 2, 2), ("5", 5, 5), ("2", 2, 2)] ) self.assertEqual(r.v, 10) with Form(r, view='test_testing_utilities.o2m_parent') as f, \ f.subs.edit(index=0) as sub,\ self.assertRaises(AssertionError): sub.name = "whop whop" def test_o2m_editable_list(self): """ Tests the o2m proxy when the list view is editable rather than delegating to a separate form view """ f = Form(self.env['test_testing_utilities.parent'], view='test_testing_utilities.o2m_parent_ed') custom_tree = self.env.ref('test_testing_utilities.editable_external').id subs_field = f._view['fields']['subs'] tree_view = subs_field['views']['tree'] self.assertEqual(tree_view['type'], 'tree') self.assertEqual( tree_view['view_id'], custom_tree, 'check that the tree view is the one referenced by tree_view_ref' ) self.assertIs(subs_field['views']['edition'], tree_view, "check that the edition view is the tree view") self.assertEqual( subs_field['views']['edition']['view_id'], custom_tree ) with f.subs.new() as s: s.value = 1 with f.subs.new() as s: s.value = 3 with f.subs.new() as s: s.value = 7 r = f.save() self.assertEqual(r.v, 12) self.assertEqual( [get(s) for s in r.subs], [('1', 1, 1), ('3', 3, 3), ('7', 7, 7)] ) def test_o2m_inline(self): """ Tests the o2m proxy when the list and form views are provided inline rather than fetched separately """ f = Form(self.env['test_testing_utilities.parent'], view='test_testing_utilities.o2m_parent_inline') with f.subs.new() as s: s.value = 42 r = f.save() self.assertEqual( [get(s) for s in r.subs], [("0", 42, 0)], "should not have set v (and thus not name)" ) def test_o2m_default(self): """ Tests that default_get can return defaults for the o2m """ f = Form(self.env['test_testing_utilities.default']) with f.subs.edit(index=0) as s: self.assertEqual(s.v, 5) self.assertEqual(s.value, 2) r = f.save() self.assertEqual( [get(s) for s in r.subs], [("5", 2, 5)] ) def test_o2m_inner_default(self): """ Tests that creating an o2m record will get defaults for it """ f = Form(self.env['test_testing_utilities.default']) with f.subs.new() as s: self.assertEqual(s.value, 2) self.assertEqual(s.v, 2, "should have onchanged value to v") def test_o2m_onchange_parent(self): """ Tests that changing o2m content triggers onchange in the parent """ f = Form(self.env['test_testing_utilities.parent']) self.assertEqual(f.value, 1, "value should have its default") self.assertEqual(f.v, 1, "v should be equal to value") f.subs.new().save() self.assertEqual(f.v, 3, "should be sum of value & children v") def test_o2m_onchange_inner(self): """ Tests that editing a field of an o2m record triggers onchange in the o2m record and its parent """ f = Form(self.env['test_testing_utilities.parent']) # only apply the onchange on edition end (?) with f.subs.new() as sub: sub.value = 6 self.assertEqual(sub.v, 6) self.assertEqual(f.v, 1) self.assertEqual(f.v, 7) def test_o2m_parent_content(self): """ Tests that when editing a field of an o2m the data sent contains the parent data """ f = Form(self.env['test_testing_utilities.parent']) # only apply the onchange on edition end (?) with f.subs.new() as sub: sub.has_parent = True self.assertEqual(sub.has_parent, True) self.assertEqual(sub.value, 1) self.assertEqual(sub.v, 1) def test_readonly_o2m(self): """ Tests that o2m fields flagged as readonly (readonly="1" in the view) can't be written to """ r = self.env['test_testing_utilities.parent'].create({ 'subs': [Command.create({})] }) f = Form(r, view='test_testing_utilities.o2m_parent_readonly') with self.assertRaises(AssertionError): f.subs.new() with self.assertRaises(AssertionError): f.subs.edit(index=0) with self.assertRaises(AssertionError): f.subs.remove(index=0) def test_o2m_readonly_subfield(self): """ Tests that readonly is applied to the field of the o2m = not sent as part of the create / write values """ f = Form(self.env['o2m_readonly_subfield_parent']) with f.line_ids.new() as new_line: new_line.name = "ok" self.assertEqual(new_line.f, 2) r = f.save() self.assertEqual( (r.line_ids.name, r.line_ids.f), ('ok', 2) ) def test_o2m_dyn_onchange(self): f = Form(self.env['test_testing_utilities.onchange_parent'], view='test_testing_utilities.m2o_onchange_view') with f.line_ids.new() as new_line: new_line.dummy = 42 self.assertTrue(new_line.flag) with f.line_ids.edit(index=0) as new_line: self.assertTrue(new_line.flag) def test_o2m_remove(self): def commands(): return [c[0] for c in f._values['line_ids']] f = Form(self.env['test_testing_utilities.onchange_count']) self.assertEqual(f.count, 0) self.assertEqual(len(f.line_ids), 0) f.count = 5 self.assertEqual(f.count, 5) self.assertEqual(len(f.line_ids), 5) f.count = 2 self.assertEqual(f.count, 2) self.assertEqual(len(f.line_ids), 2) f.count = 4 r = f.save() previous = r.line_ids self.assertEqual(len(previous), 4) with Form(r) as f: f.count = 2 self.assertEqual(commands(), [0, 0, 2, 2, 2, 2], "Should contain 2 creations and 4 deletions") self.assertEqual(len(r.line_ids), 2) with Form(r) as f: f.line_ids.remove(0) self.assertEqual(commands(), [2, 1]) f.count = 1 self.assertEqual(commands(), [0, 2, 2], "should contain 1 '0' command and 2 deletions") self.assertEqual(len(r.line_ids), 1) def test_o2m_self_recursive(self): Form(self.env['test_testing_utilities.recursive'], view='test_testing_utilities.o2m_recursive_relation_view') def test_o2m_attrs(self): Model = self.env['test_testing_utilities.parent'].with_context( default_subs=[{ 'value': 5, }, { 'value': 7, }] ) f = Form(Model, view='test_testing_utilities.o2m_modifier') f.save() def test_o2m_widget(self): create = self.env['test_testing_utilities.sub'].create a, b, c = create({'v': 1}), create({'v': 2}), create({'v': 3}) f = Form(self.env['test_testing_utilities.parent'], view='test_testing_utilities.o2m_widget_m2m') f.subs.add(a) f.subs.add(b) f.subs.add(c) r = f.save() self.assertEqual( r.subs, a | b | c ) def test_o2m_onchange_change_saved(self): """ If an onchange updates o2m values (in existing sub-records of an existing record), those updated values should be saved, both if the sub-records were touched by the user and not (check that one maybe) """ # create record: line created before v is updated should reflect it, # line created after should not f = Form(self.env['o2m_changes_children']) with f.line_ids.new() as line: line.v = 1 line.vv = 5 f.v = 5 with f.line_ids.new() as line: ... r = f.save() self.assertEqual(r.v, 5) self.assertEqual(r.mapped('line_ids.vv'), [5, 0]) self.assertEqual(r.line_ids[0].v, 5, "onchange should have updated the existing lines") self.assertEqual(r.line_ids[1].v, 0, "onchange should not impact new line") # update record: onchange then touch the lines with Form(r) as f: f.v = 6 with f.line_ids.edit(0) as line: line.vv = 1 with f.line_ids.edit(1) as line: line.vv = 2 self.assertEqual(r.v, 6) self.assertEqual(r.mapped('line_ids.vv'), [1, 2]) self.assertEqual(r.mapped('line_ids.v'), [6, 6], "onchange should have updated vs") # update record: onchange then don't even touch the lines with Form(r) as f: f.v = 7 self.assertEqual(r.v, 7) self.assertEqual(r.mapped('line_ids.vv'), [1, 2]) self.assertEqual(r.mapped('line_ids.v'), [7, 7]) class TestNestedO2M(TransactionCase): def test_id_cannot_be_assigned(self): # MO with: # produces product0 # produces 1 (product_qty) # flexible BOM produces 1 # bom consumes 4x product 1 # bom consumes 1x product 2 product0 = self.env['ttu.product'].create({}).id product1 = self.env['ttu.product'].create({}).id product2 = self.env['ttu.product'].create({}).id # create pseudo-MO in post-asigned state obj = self.env['ttu.root'].create({ 'product_id': product0, 'product_qty': 1.0, # qty_producing=0 (onchange) # qty_produced=0 (computed) 'move_raw_ids': [ Command.create({ 'product_id': product2, # quantity_done=0 (computed) 'move_line_ids': [Command.create({ 'product_id': product2, 'product_uom_qty': 1.0, 'qty_done': 0.0 # -> 1.0 })] # -> new line with qty=0, qty_done=2 }), Command.create({ 'product_id': product1, 'unit_factor': 4, 'move_line_ids': [Command.create({ 'product_id': product1, 'product_uom_qty': 4.0, 'qty_done': 0.0 # -> 4.0 })] # -> new line with qty=0, qty_done=8 }) ], 'move_finished_ids': [Command.create({'product_id': product0})] # -> new line with qty=0, qty_done=3 }) form = Form(obj) form.qty_producing = 1 form._perform_onchange(['move_raw_ids']) form.save() def test_empty_update(self): # MO with: # produces product0 # produces 1 (product_qty) # flexible BOM produces 1 # bom consumes 4x product 1 # bom consumes 1x product 2 product0 = self.env['ttu.product'].create({}).id product1 = self.env['ttu.product'].create({}).id product2 = self.env['ttu.product'].create({}).id product4 = self.env['ttu.product'].create({}) # create pseudo-MO in post-asigned state obj = self.env['ttu.root'].create({ 'product_id': product0, 'product_qty': 1.0, # qty_producing=0 (onchange) # qty_produced=0 (computed) 'move_raw_ids': [ Command.create({ 'product_id': product2, # quantity_done=0 (computed) 'move_line_ids': [Command.create({ 'product_id': product2, 'product_uom_qty': 1.0, 'qty_done': 0.0 # -> 1.0 })] # -> new line with qty=0, qty_done=2 }), Command.create({ 'product_id': product1, 'unit_factor': 4, 'move_line_ids': [Command.create({ 'product_id': product1, 'product_uom_qty': 4.0, 'qty_done': 0.0 # -> 4.0 })] # -> new line with qty=0, qty_done=8 }) ], 'move_finished_ids': [Command.create({'product_id': product0})] # -> new line with qty=0, qty_done=3 }) form = Form(obj) form.qty_producing = 1 form.save() with form.move_raw_ids.new() as move: move.product_id = product4 move.quantity_done = 10 # Check that this new product is not updated by qty_producing form.qty_producing = 2 form.save() def test_remove(self): """ onchanges can remove o2m records which haven't been loaded yet due to lazy loading of o2ms. The removal information should still be retained, otherwise due to the stateful update system we end up retaining records we don't even know exist. """ # create structure with sub-sub-children r = self.env['o2m_changes_parent'].create({ 'name': "A", 'line_ids': [ Command.create({ 'name': 'line 1', 'v': 42, 'line_ids': [Command.create({'v': 1, 'vv': 1})], }) ] }) with Form(r) as f: f.name = 'B' self.assertEqual(len(r.line_ids), 1) self.assertEqual(len(r.line_ids.line_ids), 1) self.assertEqual(r.line_ids.line_ids.v, 0) self.assertEqual(r.line_ids.line_ids.vv, 0) class TestEdition(TransactionCase): """ These use the context manager form as we don't need the record post-save (we already have it) and it's easier to see what bits act on the form (inside `with`) versus outside. That let me catch a few mistakes. """ def test_trivial(self): r = self.env['test_testing_utilities.a'].create({ 'f1': '5', }) with Form(r) as f: self.assertEqual(f.id, r.id) self.assertEqual(f.f1, '5') self.assertEqual(f.f4, 8) f.f2 = 5 self.assertEqual(f.f3, 2) self.assertEqual(f.f4, 1) self.assertEqual(r.f2, 5) self.assertEqual(r.f3, 2) def test_m2o(self): Sub = self.env['test_testing_utilities.m2o'] a = Sub.create({'name': 'a'}) b = Sub.create({'name': 'b'}) c = Sub.create({'name': 'c'}) r = self.env['test_testing_utilities.d'].create({ 'f': c.id, 'f2': "OK", }) with Form(r) as f: # no default/onchange should have run so loading an incoherent # record should still be incoherent self.assertEqual(f.f, c) self.assertEqual(f.f2, 'OK') f.f2 = "b" self.assertEqual(f.f, b) f.f2 = "Whoops" self.assertEqual(f.f, Sub) f.f2 = "a" self.assertEqual(f.f, a) self.assertEqual(r.f2, "a") self.assertEqual(r.f, a) def test_m2m_empty(self): sub = self.env['test_testing_utilities.sub2'].create({'name': 'a'}) r = self.env['test_testing_utilities.f'].create({ 'm2m': [] }) with Form(r) as f: f.m2o = sub self.assertEqual(r.m2o, sub) self.assertEqual(r.m2m, sub) def test_m2m_nonempty(self): Sub = self.env['test_testing_utilities.sub2'] a = Sub.create({'name': 'a'}) b = Sub.create({'name': 'b'}) c = Sub.create({'name': 'c'}) r = self.env['test_testing_utilities.f'].create({ 'm2m': [Command.set((a | b | c).ids)] }) with Form(r) as f: self.assertEqual(f.m2m[:], (a | b | c)) f.m2m.remove(index=0) self.assertEqual(f.m2m[:], (b | c)) self.assertEqual(r.m2m, (b | c))
32.72365
25,459
1,655
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import TransactionCase class TestEnv(TransactionCase): @classmethod def setUpClass(cls): super(TestEnv, cls).setUpClass() user = cls.env['res.users'].create({ 'name': 'superuser', 'login': 'superuser', 'password': 'superuser', 'groups_id': [(6, 0, cls.env.user.groups_id.ids)], }) cls.env = cls.env(user=user) # make sure there is at least another environment in the current transaction cls.sudo_env = cls.env(su=True) def test_env_company_part_01(self): """ The main goal of the test is actually to check the values of the environment after this test execution (see test_env_company_part_02) """ company = self.env['res.company'].create({ "name": "Test Company", }) self.env.user.write({ 'company_id': company.id, 'company_ids': [(4, company.id), (4, self.env.company.id)], }) self.assertEqual(self.env.company, self.env.user.company_id) self.assertTrue(self.env.company.exists()) self.assertEqual(self.sudo_env.company, self.env.user.company_id) self.assertTrue(self.sudo_env.company.exists()) def test_env_company_part_02(self): self.assertEqual(self.env.company, self.env.user.company_id) self.assertTrue(self.env.company.exists()) self.assertEqual(self.sudo_env.company, self.env.user.company_id) self.assertTrue(self.sudo_env.company.exists())
37.613636
1,655
4,785
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from lxml import etree from odoo.tests import common from odoo.tools.xml_utils import cleanup_xml_node class TestXMLTools(common.TransactionCase): def setUp(self): super(TestXMLTools, self).setUp() self.qweb_poor = self.env()['ir.ui.view'].create({ 'type': 'qweb', 'arch_db': """ <h1> <h2/> <h2>text</h2> \t<h2><h3/></h2> <h2> </h2> <!-- comment removed by qweb --> </h1>"""}) def test_cleanup_xml_node_no_modif(self): # Qweb removes comments and any whitespace before first tag, no other content affected expected = """<h1> <h2/> <h2>text</h2> \t<h2><h3/></h2> <h2> </h2> </h1>""" qweb = self.qweb_poor._render() self.check_xml_cleanup_result_is_as_expected(qweb, expected, remove_blank_text=False, remove_blank_nodes=False, indent_level=-1) def test_cleanup_xml_node_indent_level(self): # Indentation level and spacing works as expected, nothing else affected # (quirk: first tag not indented because indent is actually previous tag's tail) expected = """<h1> __<h2/> __<h2>text</h2> __<h2> ___<h3/> __</h2> __<h2> </h2> _</h1> """ qweb = self.qweb_poor._render() self.check_xml_cleanup_result_is_as_expected(qweb, expected, remove_blank_text=False, remove_blank_nodes=False, indent_level=1, indent_space="_") def test_cleanup_xml_node_keep_blank_text(self): # Blank nodes are removed but not nodes containing blank text expected = """<h1> <h2>text</h2> <h2> </h2> </h1> """ qweb = self.qweb_poor._render() self.check_xml_cleanup_result_is_as_expected(qweb, expected, remove_blank_text=False) def test_cleanup_xml_node_keep_blank_nodes(self): # Blank text is removed but blank (empty) nodes remain expected = """<h1> <h2/> <h2>text</h2> <h2> <h3/> </h2> <h2></h2> </h1> """ qweb = self.qweb_poor._render() self.check_xml_cleanup_result_is_as_expected(qweb, expected, remove_blank_nodes=False) def test_cleanup_xml_t_call_indent(self): # Indentation is fixed after t-call (which keeps indentation of called template) template_1 = self.env['ir.ui.view'].create({ 'type': 'qweb', 'arch_db': '''<h1> <content>This is content!</content> </h1> '''}) template_2 = self.env['ir.ui.view'].create({ 'name': 'test', 'type': 'qweb', 'arch_db': f'''<odoo> <data> <t t-call="{template_1.id}"/> </data> </odoo> '''}) expected = """<odoo> <data> <h1> <content>This is content!</content> </h1> </data> </odoo> """ qweb = template_2._render() self.check_xml_cleanup_result_is_as_expected(qweb, expected) def test_qweb_render_values_empty_nodes(self): # Indentation is fixed and empty nodes are removed after conditional rendering template_addresses = self.env['ir.ui.view'].create({ 'type': 'qweb', 'arch_db': '''<t> <street t-esc="address.get('street')"/> <number t-esc="address.get('number')"/> <city t-esc="address.get('city')"/> </t> '''}) template_main = self.env['ir.ui.view'].create({ 'type': 'qweb', 'arch_db': f'''<data> <item t-foreach="items" t-as="item" t-esc="item"/> <addressSender t-call='{template_addresses.id}'> <t t-set="address" t-value="addressSender"/> </addressSender> <addressRecipient t-call='{template_addresses.id}'> <t t-set="address" t-value="addressRecipient"/> </addressRecipient> </data> '''}) expected = """<data> <item>1</item> <item>2</item> <item>Three</item> <addressRecipient> <street>Baker street</street> <number>221B</number> <city>London</city> </addressRecipient> </data> """ qweb = template_main._render({ 'items': [1, 2, "Three", False], 'addressRecipient': { 'number': '221B', 'street': 'Baker street', 'city': 'London', }, 'addressSender': { 'street': ' ' } }) self.check_xml_cleanup_result_is_as_expected(qweb, expected) def check_xml_cleanup_result_is_as_expected(self, original_string, expected_string, **kwargs): result_string = etree.tostring(cleanup_xml_node(original_string, **kwargs)).decode() self.assertEqual(expected_string, result_string) self.assertNotEqual(expected_string, original_string)
31.480263
4,785
2,346
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.exceptions from odoo import models, api from odoo.tools.safe_eval import safe_eval class m(models.Model): """ This model exposes a few methods that will raise the different exceptions that must be handled by the server (and its RPC layer) and the clients. """ _name = 'test.exceptions.model' _description = 'Test Exception Model' def generate_redirect_warning(self): action = self.env.ref('test_exceptions.action_test_exceptions') raise odoo.exceptions.RedirectWarning('description', action.id, 'Go to the redirection') def generate_access_denied(self): raise odoo.exceptions.AccessDenied() def generate_access_error(self): raise odoo.exceptions.AccessError('description') def generate_exc_access_denied(self): raise Exception('AccessDenied') def generate_undefined(self): self.surely_undefined_symbol def generate_user_error(self): raise odoo.exceptions.UserError('description') def generate_missing_error(self): raise odoo.exceptions.MissingError('description') def generate_validation_error(self): raise odoo.exceptions.ValidationError('description') def generate_redirect_warning_safe_eval(self): self.generate_safe_eval(self.generate_redirect_warning) def generate_access_denied_safe_eval(self): self.generate_safe_eval(self.generate_access_denied) def generate_access_error_safe_eval(self): self.generate_safe_eval(self.generate_access_error) def generate_exc_access_denied_safe_eval(self): self.generate_safe_eval(self.generate_exc_access_denied) def generate_undefined_safe_eval(self): self.generate_safe_eval(self.generate_undefined) def generate_user_error_safe_eval(self): self.generate_safe_eval(self.generate_user_error) def generate_missing_error_safe_eval(self): self.generate_safe_eval(self.generate_missing_error) def generate_validation_error_safe_eval(self): self.generate_safe_eval(self.generate_validation_error) def generate_safe_eval(self, f): globals_dict = { 'generate': f } safe_eval("generate()", mode='exec', globals_dict=globals_dict)
35.014925
2,346
398
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'test-exceptions', 'version': '0.1', 'category': 'Hidden/Tests', 'description': """A module to generate exceptions.""", 'depends': ['base'], 'data': ['view.xml', 'ir.model.access.csv'], 'installable': True, 'auto_install': False, 'license': 'LGPL-3', }
30.615385
398
763
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models, fields, _ class m(models.TransientModel): """ A model to provide source strings. """ _name = 'test.translation.import' _description = 'Test: Translation Import' name = fields.Char('1XBUO5PUYH2RYZSA1FTLRYS8SPCNU1UYXMEYMM25ASV7JC2KTJZQESZYRV9L8CGB', size=32, help='Efgh') other_name = fields.Char('Test translation with two code type and model') import_type = fields.Selection([ ('foo', 'Foo Import Type'), ('bar', 'Bar Import Type'), ]) _('Ijkl') # With the name label above, this source string should be generated twice. _('1XBUO5PUYH2RYZSA1FTLRYS8SPCNU1UYXMEYMM25ASV7JC2KTJZQESZYRV9L8CGB') _('Klingon') _('Accounting')
30.52
763
500
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'test-translation-import', 'version': '0.1', 'category': 'Hidden/Tests', 'description': """A module to test translation import.""", 'depends': ['base'], 'data': [ 'security/ir.model.access.csv', 'view.xml' ], 'installable': True, 'auto_install': False, 'assets': { 'web.assets_qweb': [ 'test_translation_import/static/src/xml/js_templates.xml', ], }, 'license': 'LGPL-3', }
25
500
18,977
py
PYTHON
15.0
# -*- coding: utf-8 -*- from contextlib import closing import base64 import io import odoo from odoo.tests import common, tagged from odoo.tools.misc import file_open, mute_logger from odoo.tools.translate import _, _lt, TranslationFileReader, TranslationModuleReader from odoo import Command TRANSLATED_TERM = _lt("Klingon") class TestTermCount(common.TransactionCase): def test_count_term(self): """ Just make sure we have as many translation entries as we wanted. """ self.env['res.lang']._activate_lang('fr_FR') odoo.tools.trans_load(self.cr, 'test_translation_import/i18n/fr.po', 'fr_FR', verbose=False) translations = self.env['ir.translation'].search([ ('lang', '=', 'fr_FR'), ('src', '=', '1XBUO5PUYH2RYZSA1FTLRYS8SPCNU1UYXMEYMM25ASV7JC2KTJZQESZYRV9L8CGB'), ], order='type') self.assertEqual(len(translations), 2) self.assertEqual(translations[0].type, 'code') self.assertEqual(translations[0].module, 'test_translation_import') self.assertEqual(translations[0].name, 'addons/test_translation_import/models.py') self.assertEqual(translations[0].comments, '') self.assertEqual(translations[0].res_id, 15) self.assertEqual(translations[1].type, 'model') self.assertEqual(translations[1].module, 'test_translation_import') self.assertEqual(translations[1].name, 'ir.model.fields,field_description') self.assertEqual(translations[1].comments, '') field = self.env['ir.model.fields'].search([('model', '=', 'test.translation.import'), ('name', '=', 'name')]) self.assertEqual(translations[1].res_id, field.id) def test_count_term_module(self): """ Just make sure we have as many translation entries as we wanted and module deducted from file content """ self.env['res.lang']._activate_lang('fr_FR') odoo.tools.trans_load(self.cr, 'test_translation_import/i18n/fr.po', 'fr_FR', verbose=False) translations = self.env['ir.translation'].search([ ('lang', '=', 'fr_FR'), ('src', '=', 'Ijkl'), ('module', '=', 'test_translation_import'), ]) self.assertEqual(len(translations), 1) self.assertEqual(translations.res_id, 21) def test_noupdate(self): """ Make sure no update do not overwrite translations """ menu = self.env.ref('test_translation_import.menu_test_translation_import') menu.name = "New Name" # install french and change translation content self.env['res.lang']._activate_lang('fr_FR') odoo.tools.trans_load(self.cr, 'test_translation_import/i18n/fr.po', 'fr_FR', verbose=False) menu.with_context(lang='fr_FR').name = "Nouveau nom" # reload with overwrite odoo.tools.trans_load(self.cr, 'test_translation_import/i18n/fr.po', 'fr_FR', verbose=False, overwrite=True) # trans_load invalidates ormcache but not record cache menu.env.cache.invalidate() self.assertEqual(menu.name, "New Name") self.assertEqual(menu.with_context(lang='fr_FR').name, "Nouveau nom") def test_lang_with_base(self): self.env['res.lang']._activate_lang('fr_BE') odoo.tools.trans_load(self.cr, 'test_translation_import/i18n/fr.po', 'fr_BE', verbose=False) odoo.tools.trans_load(self.cr, 'test_translation_import/i18n/fr_BE.po', 'fr_BE', verbose=False, overwrite=True) # language override base language translations = self.env['ir.translation'].search([ ('lang', '=', 'fr_BE'), ('value', '=like', '% belgian french'), ]) self.assertEqual(len(translations), 2) # not specified localized language fallback on base language translations = self.env['ir.translation'].search([ ('lang', '=', 'fr_BE'), ('src', '=', 'Efgh'), ('value', '=', 'Efgh in french'), ]) self.assertEqual(len(translations), 1) translations = self.env['ir.translation'].search([ ('lang', '=', 'fr_BE'), ('src', '=', 'Test translation with a code type but different line number in pot'), ('value', '=', 'Test traduction avec un type code mais différent numéro de ligne dans le pot'), ]) self.assertEqual(len(translations), 1) def test_no_duplicate(self): """ Just make sure we do not create duplicated translation with 'code' type """ self.env['res.lang']._activate_lang('fr_FR') odoo.tools.trans_load(self.cr, 'test_translation_import/i18n/fr.po', 'fr_FR', verbose=False) ids = self.env['ir.translation'].search([ ('lang', '=', 'fr_FR'), ('src', '=', 'Test translation with two code lines'), ]) self.assertEqual(len(ids), 1) ids = self.env['ir.translation'].search([ ('lang', '=', 'fr_FR'), ('src', '=', 'Test translation with a code type but different line number in pot'), ]) self.assertEqual(len(ids), 1) ids = self.env['ir.translation'].search([ ('lang', '=', 'fr_FR'), ('src', '=', 'Test translation with two code type and model'), ]) self.assertEqual(len(ids), 2) self.assertEqual(len(ids.filtered(lambda t: t.type == 'code')), 1) def test_export_empty_string(self): """When the string and the translation is equal the translation is empty""" # Export the translations def update_translations(create_empty_translation=False): self.env['res.lang']._activate_lang('fr_FR') with closing(io.BytesIO()) as bufferobj: odoo.tools.trans_export('fr_FR', ['test_translation_import'], bufferobj, 'po', self.cr) bufferobj.name = 'test_translation_import/i18n/fr.po' odoo.tools.trans_load_data(self.cr, bufferobj, 'po', 'fr_FR', verbose=False, create_empty_translation=create_empty_translation, overwrite=True) # Check that the not translated key is not created update_translations() translation = self.env['ir.translation'].search_count([('src', '=', 'Efgh'), ('value', '=', '')]) self.assertFalse(translation, 'An empty translation is not imported') # Check that "Generate Missing Terms" create empty string for not translated key update_translations(create_empty_translation=True) translation = self.env['ir.translation'].search_count([('src', '=', 'Efgh'), ('value', '=', '')]) self.assertTrue(translation, 'The translation of "Efgh" should be empty') # Modify the value translated for the equal value of the key menu = self.env.ref('test_translation_import.menu_test_translation_import') menu.name = "New Name" menu.with_context(lang='fr_FR').name = "New Name" update_translations() self.assertEqual(menu.with_context(lang='fr_FR').name, "New Name", 'The translation of "New Name" should be "New Name"') # Modify the value translated for another different value menu.name = "New Name" menu.with_context(lang='fr_FR').name = "Nouveau nom" update_translations() self.assertEqual(menu.with_context(lang='fr_FR').name, "Nouveau nom", 'The translation of "New Name" should be "Nouveau nom"') def test_import_from_po_file(self): """Test the import from a single po file works""" with file_open('test_translation_import/i18n/tlh.po', 'rb') as f: po_file = base64.encodebytes(f.read()) import_tlh = self.env["base.language.import"].create({ 'name': 'Klingon', 'code': 'tlh', 'data': po_file, 'filename': 'tlh.po', }) with mute_logger('odoo.addons.base.models.res_lang'): import_tlh.import_lang() tlh_lang = self.env['res.lang']._lang_get('tlh') self.assertTrue(tlh_lang, "The imported language was not creates") trans_count = self.env['ir.translation'].search_count([('lang', '=', 'tlh')]) self.assertEqual(trans_count, 1, "The imported translations were not created") self.env = self.env(context=dict(self.env.context, lang="tlh")) self.assertEqual(_("Klingon"), "tlhIngan", "The code translation was not applied") def test_lazy_translation(self): """Test the import from a single po file works""" with file_open('test_translation_import/i18n/tlh.po', 'rb') as f: po_file = base64.encodebytes(f.read()) import_tlh = self.env["base.language.import"].create({ 'name': 'Klingon', 'code': 'tlh', 'data': po_file, 'filename': 'tlh.po', }) with mute_logger('odoo.addons.base.models.res_lang'): import_tlh.import_lang() context = {'lang': "tlh"} self.assertEqual(_("Klingon"), "tlhIngan", "The direct code translation was not applied") context = None # Comparison of lazy strings must be explicitely casted to string with self.assertRaises(NotImplementedError): TRANSLATED_TERM == "Klingon" self.assertEqual(str(TRANSLATED_TERM), "Klingon", "The translation should not be applied yet") context = {'lang': "tlh"} self.assertEqual(str(TRANSLATED_TERM), "tlhIngan", "The lazy code translation was not applied") self.assertEqual("Do you speak " + TRANSLATED_TERM, "Do you speak tlhIngan", "str + _lt concatenation failed") self.assertEqual(TRANSLATED_TERM + ", I speak it", "tlhIngan, I speak it", "_lt + str concatenation failed") self.assertEqual(TRANSLATED_TERM + TRANSLATED_TERM, "tlhIngantlhIngan", "_lt + _lt concatenation failed") def test_import_from_csv_file(self): """Test the import from a single CSV file works""" with file_open('test_translation_import/i18n/dot.csv', 'rb') as f: po_file = base64.encodebytes(f.read()) import_tlh = self.env["base.language.import"].create({ 'name': 'Dothraki', 'code': 'dot', 'data': po_file, 'filename': 'dot.csv', }) with mute_logger('odoo.addons.base.models.res_lang'): import_tlh.import_lang() dot_lang = self.env['res.lang']._lang_get('dot') self.assertTrue(dot_lang, "The imported language was not creates") trans_count = self.env['ir.translation'].search_count([('lang', '=', 'dot')]) self.assertEqual(trans_count, 1, "The imported translations were not created") self.env.context = dict(self.env.context, lang="dot") self.assertEqual(_("Accounting"), "samva", "The code translation was not applied") def test_export_pollution(self): """ Test that exporting the translation only exports the translations of the module """ with file_open('test_translation_import/i18n/dot.csv', 'rb') as f: csv_file = base64.b64encode(f.read()) # dot.csv only contains one term import_tlh = self.env["base.language.import"].create({ 'name': 'Dothraki', 'code': 'dot', 'data': csv_file, 'filename': 'dot.csv', }) with mute_logger('odoo.addons.base.models.res_lang'): import_tlh.import_lang() # create a translation that has the same src as an existing field but no module # information and a different res_id that the real field # this translation should not be included in the export self.env['ir.translation'].create({ 'src': '1XBUO5PUYH2RYZSA1FTLRYS8SPCNU1UYXMEYMM25ASV7JC2KTJZQESZYRV9L8CGB', 'value': '1XBUO5PUYH2RYZSA1FTLRYS8SPCNU1UYXMEYMM25ASV7JC2KTJZQESZYRV9L8CGB in Dothraki', 'type': 'model', 'name': 'ir.model.fields,field_description', 'res_id': -1, 'lang': 'dot', }) module = self.env.ref('base.module_test_translation_import') export = self.env["base.language.export"].create({ 'lang': 'dot', 'format': 'po', 'modules': [Command.set([module.id])] }) export.act_getfile() po_file = export.data reader = TranslationFileReader(base64.b64decode(po_file).decode(), fileformat='po') for row in reader: if row['value']: # should contains only one row from the csv, not the manual one self.assertEqual(row['src'], "Accounting") self.assertEqual(row['value'], "samva") def test_translation_placeholder(self): """Verify placeholder use in _()""" context = {'lang': "fr_BE"} self.env.ref("base.lang_fr_BE").active = True # translation with positional placeholders translation = self.env['ir.translation'].create({ 'src': 'Text with %s placeholder', 'value': 'Text avec %s marqueur', 'type': 'code', 'name': 'addons/test_translation_import/tests/test_count_term.py', 'res_id': 0, 'lang': 'fr_BE', }) # correctly translate self.assertEqual( _("Text with %s placeholder", 1), "Text avec 1 marqueur", "Translation placeholders were not applied" ) # source error: wrong arguments with self.assertRaises(TypeError), self.cr.savepoint(): _("Text with %s placeholder", 1, "🧀") # translation error: log error and fallback on source translation.value = "Text avec s% marqueur" with self.assertLogs('odoo.tools.translate', 'ERROR'): self.assertEqual( _("Text with %s placeholder", 1), "Text with 1 placeholder", "Fallback to source was not used for bad translation" ) # translation with named placeholders translation = self.env['ir.translation'].create({ 'src': 'Text with %(num)s placeholders %(symbol)s', 'value': 'Text avec %(num)s marqueurs %(symbol)s', 'type': 'code', 'name': 'addons/test_translation_import/tests/test_count_term.py', 'res_id': 0, 'lang': 'fr_BE', }) # correctly translate self.assertEqual( _("Text with %(num)s placeholders %(symbol)s", num=2, symbol="🧀"), "Text avec 2 marqueurs 🧀", "Translation placeholders were not applied" ) # source error: wrong arguments with self.assertRaises(KeyError), self.cr.savepoint(): _("Text with %(num)s placeholders %(symbol)s", symbol="🧀") # translation error: log error and fallback on source translation.value = "Text avec %(num)s marqueurs %(symbole)s" with self.assertLogs('odoo.tools.translate', 'ERROR'): self.assertEqual( _("Text with %(num)s placeholders %(symbol)s", num=2, symbol="🧀"), "Text with 2 placeholders 🧀", "Fallback to source was not used for bad translation" ) @tagged('post_install', '-at_install') class TestTranslationFlow(common.TransactionCase): def test_export_import(self): """ Ensure export+import gives the same result as loading a language """ # load language and generate missing terms to create missing empty terms with mute_logger('odoo.addons.base.models.ir_translation'): self.env["base.language.install"].create({'lang': 'fr_FR', 'overwrite': True}).lang_install() self.env["base.update.translations"].create({'lang': 'fr_FR'}).act_update() translations = self.env["ir.translation"].search([ ('lang', '=', 'fr_FR'), ('module', '=', 'test_translation_import'), ('value', '!=', ''), ]) # minus 3 as the original fr.po contains 3 fake code translations (cf # test_no_duplicate test) which are not found by babel_extract_terms init_translation_count = len(translations) - 3 module = self.env.ref('base.module_test_translation_import') export = self.env["base.language.export"].create({ 'lang': 'fr_FR', 'format': 'po', 'modules': [Command.set([module.id])] }) export.act_getfile() po_file = export.data self.assertIsNotNone(po_file) translations.unlink() import_fr = self.env["base.language.import"].create({ 'name': 'French', 'code': 'fr_FR', 'data': export.data, 'filename': export.name, 'overwrite': False, }) with mute_logger('odoo.addons.base.models.res_lang'): import_fr.import_lang() import_translation = self.env["ir.translation"].search([ ('lang', '=', 'fr_FR'), ('module', '=', 'test_translation_import'), ('value', '!=', ''), ]) self.assertEqual(init_translation_count, len(import_translation)) def test_export_import_csv(self): """ Ensure can reimport exported csv """ self.env.ref("base.lang_fr").active = True module = self.env.ref('base.module_test_translation_import') export = self.env["base.language.export"].create({ 'lang': 'fr_FR', 'format': 'csv', 'modules': [Command.set([module.id])] }) export.act_getfile() po_file = export.data self.assertIsNotNone(po_file) self.env["ir.translation"].search([ ('lang', '=', 'fr_FR'), ('module', '=', 'test_translation_import') ]).unlink() import_fr = self.env["base.language.import"].create({ 'name': 'French', 'code': 'fr_FR', 'data': export.data, 'filename': export.name, 'overwrite': False, }) with mute_logger('odoo.addons.base.models.res_lang'): import_fr.with_context(create_empty_translation=True).import_lang() def test_export_static_templates(self): trans_static = [] po_reader = TranslationModuleReader(self.env.cr, ['test_translation_import']) for line in po_reader: module, ttype, name, res_id, source, value, comments = line if name == "addons/test_translation_import/static/src/xml/js_templates.xml": trans_static.append(source) self.assertNotIn('no export', trans_static) self.assertIn('do export', trans_static) self.assertIn('text node', trans_static) self.assertIn('slot', trans_static) self.assertIn('slot 2', trans_static)
43.57931
18,957
363
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Tests flow of API keys', 'category': 'Tools', 'depends': ['web_tour'], 'assets': { 'web.assets_tests': [ # inside . 'test_apikeys/static/tests/apikey_flow.js', ], }, 'license': 'LGPL-3', }
25.928571
363
1,248
py
PYTHON
15.0
import json from odoo import api from odoo.tests import tagged, HttpCase, get_db_name @tagged('post_install', '-at_install') class TestAPIKeys(HttpCase): def setUp(self): super().setUp() self.messages = [] @api.model def log(inst, *args, **kwargs): self.messages.append((inst, args, kwargs)) self.registry['ir.logging'].send_key = log @self.addCleanup def remove_callback(): del self.registry['ir.logging'].send_key def test_addremove(self): db = get_db_name() self.start_tour('/web', 'apikeys_tour_setup', login='demo') demo_user = self.env['res.users'].search([('login', '=', 'demo')]) self.assertEqual(len(demo_user.api_key_ids), 1, "the demo user should now have a key") [(_, [key], [])] = self.messages uid = self.xmlrpc_common.authenticate(db, 'demo', key, {}) [r] = self.xmlrpc_object.execute_kw( db, uid, key, 'res.users', 'read', [uid, ['login']] ) self.assertEqual( r['login'], 'demo', "the key should be usable as a way to perform RPC calls" ) self.start_tour('/web', 'apikeys_tour_teardown', login='demo')
33.72973
1,248
268
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': "test_search_panel", 'description': "Tests for the search panel python methods", 'category': 'Hidden/Tests', 'version': '0.1', 'depends': ['web'], 'data': ['ir.model.access.csv'], 'license': 'LGPL-3', }
20.615385
268
23,370
py
PYTHON
15.0
# -*- coding: utf-8 -*- import odoo.tests import json SEARCH_PANEL_ERROR = {'error_msg': "Too many items to display.", } @odoo.tests.tagged('post_install', '-at_install') class TestSelectRangeMulti(odoo.tests.TransactionCase): def setUp(self): super().setUp() self.SourceModel = self.env['test_search_panel.source_model'] self.TargetModel = self.env['test_search_panel.filter_target_model'] self.GroupByModel = self.env['test_search_panel.category_target_model'] # Many2one def test_many2one_empty(self): result = self.SourceModel.search_panel_select_multi_range('tag_id') self.assertEqual( result['values'], [], ) def test_many2one(self): folders = self.GroupByModel.create([ {'name': 'Folder 1', }, {'name': 'Folder 2', }, ]) f1_id, f2_id = folders.ids tags = self.TargetModel.create([ {'name': 'Tag 1', 'folder_id': f2_id, 'color': 'Red', 'status': 'cool', }, {'name': 'Tag 2', 'folder_id': f1_id, 'status': 'cool', }, {'name': 'Tag 3', 'color': 'Green', 'status': 'cool', }, ]) t1_id, t2_id, t3_id = tags.ids records = self.SourceModel.create([ {'name': 'Rec 1', 'tag_id': t1_id, }, {'name': 'Rec 2', 'tag_id': t1_id, }, {'name': 'Rec 3', 'tag_id': t2_id, }, {'name': 'Rec 4', }, ]) r1_id, r2_id, _, _ = records.ids # counters, expand, and group_by (many2one case) result = self.SourceModel.search_panel_select_multi_range( 'tag_id', enable_counters=True, expand=True, group_by='folder_id' ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'Tag 1', 'id': t1_id, 'group_id': f2_id, 'group_name': 'Folder 2', }, {'__count': 1, 'display_name': 'Tag 2', 'id': t2_id, 'group_id': f1_id, 'group_name': 'Folder 1', }, {'__count': 0, 'display_name': 'Tag 3', 'id': t3_id, 'group_id': False, 'group_name': 'Not Set', }, ] ) # counters, expand, and group_by (selection case) result = self.SourceModel.search_panel_select_multi_range( 'tag_id', enable_counters=True, expand=True, group_by='status' ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'Tag 1', 'id': t1_id, 'group_id': 'cool', 'group_name': 'Cool', }, {'__count': 1, 'display_name': 'Tag 2', 'id': t2_id, 'group_id': 'cool', 'group_name': 'Cool', }, {'__count': 0, 'display_name': 'Tag 3', 'id': t3_id, 'group_id': 'cool', 'group_name': 'Cool', }, ] ) # counters, expand, and group_by (other cases) result = self.SourceModel.search_panel_select_multi_range( 'tag_id', enable_counters=True, expand=True, group_by='color' ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'Tag 1', 'id': t1_id, 'group_id': 'Red', 'group_name': 'Red', }, {'__count': 1, 'display_name': 'Tag 2', 'id': t2_id, 'group_id': False, 'group_name': 'Not Set', }, {'__count': 0, 'display_name': 'Tag 3', 'id': t3_id, 'group_id': 'Green', 'group_name': 'Green', }, ] ) # counters, expand, and no group_by result = self.SourceModel.search_panel_select_multi_range( 'tag_id', enable_counters=True, expand=True, ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'Tag 1', 'id': t1_id, }, {'__count': 1, 'display_name': 'Tag 2', 'id': t2_id, }, {'__count': 0, 'display_name': 'Tag 3', 'id': t3_id, }, ] ) # counters, expand, no group_by, and search domain result = self.SourceModel.search_panel_select_multi_range( 'tag_id', enable_counters=True, expand=True, search_domain=[['id', 'in', [r1_id, r2_id]]], ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'Tag 1', 'id': t1_id, }, {'__count': 0, 'display_name': 'Tag 2', 'id': t2_id, }, {'__count': 0, 'display_name': 'Tag 3', 'id': t3_id, }, ], ) # counters, expand, no group_by, and limit result = self.SourceModel.search_panel_select_multi_range( 'tag_id', enable_counters=True, expand=True, limit=2, ) self.assertEqual(result, SEARCH_PANEL_ERROR, ) # no counters, expand, and group_by (many2one case) result = self.SourceModel.search_panel_select_multi_range( 'tag_id', expand=True, group_by='folder_id', ) self.assertEqual( result['values'], [ {'display_name': 'Tag 1', 'id': t1_id, 'group_id': f2_id, 'group_name': 'Folder 2', }, {'display_name': 'Tag 2', 'id': t2_id, 'group_id': f1_id, 'group_name': 'Folder 1', }, {'display_name': 'Tag 3', 'id': t3_id, 'group_id': False, 'group_name': 'Not Set', }, ] ) # no counters, expand, and no group_by result = self.SourceModel.search_panel_select_multi_range( 'tag_id', expand=True, ) self.assertEqual( result['values'], [ {'display_name': 'Tag 1', 'id': t1_id, }, {'display_name': 'Tag 2', 'id': t2_id, }, {'display_name': 'Tag 3', 'id': t3_id, }, ], ) # no counters, expand, no group_by, and search domain result = self.SourceModel.search_panel_select_multi_range( 'tag_id', expand=True, search_domain=[['id', 'in', [r1_id, r2_id]]], ) self.assertEqual( result['values'], [ {'display_name': 'Tag 1', 'id': t1_id, }, {'display_name': 'Tag 2', 'id': t2_id, }, {'display_name': 'Tag 3', 'id': t3_id, }, ] ) # counters, no expand, and group_by (many2one case) result = self.SourceModel.search_panel_select_multi_range( 'tag_id', enable_counters=True, group_by='folder_id', ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'Tag 1', 'id': t1_id, 'group_id': f2_id, 'group_name': 'Folder 2', }, {'__count': 1, 'display_name': 'Tag 2', 'id': t2_id, 'group_id': f1_id, 'group_name': 'Folder 1', }, ] ) # counters, no expand, no group_by, and search_domain result = self.SourceModel.search_panel_select_multi_range( 'tag_id', enable_counters=True, search_domain=[['id', 'in', [r1_id, r2_id]]], ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'Tag 1', 'id': t1_id, }, ] ) # counters, no expand, no group_by, and limit result = self.SourceModel.search_panel_select_multi_range( 'tag_id', enable_counters=True, limit=2, ) self.assertEqual(result, SEARCH_PANEL_ERROR, ) # no counters, no expand, group_by (many2one case), and search domain result = self.SourceModel.search_panel_select_multi_range( 'tag_id', group_by='folder_id', ) self.assertEqual( result['values'], [ {'display_name': 'Tag 1', 'id': t1_id, 'group_id': f2_id, 'group_name': 'Folder 2', }, {'display_name': 'Tag 2', 'id': t2_id, 'group_id': f1_id, 'group_name': 'Folder 1', }, ] ) # no counters, no expand, no group_by, and search domain result = self.SourceModel.search_panel_select_multi_range( 'tag_id', search_domain=[['id', 'in', [r1_id, r2_id]]], ) self.assertEqual( result['values'], [ {'display_name': 'Tag 1', 'id': t1_id, }, ] ) # no counters, no expand, no group_by, and comodel domain result = self.SourceModel.search_panel_select_multi_range( 'tag_id', comodel_domain=[['id', 'in', [t2_id, t3_id]]], ) self.assertEqual( result['values'], [ {'display_name': 'Tag 2', 'id': t2_id, }, ] ) # Many2many def test_many2many_empty(self): result = self.SourceModel.search_panel_select_multi_range('tag_ids') self.assertEqual( result['values'], [], ) def test_many2many(self): folders = self.GroupByModel.create([ {'name': 'Folder 1', }, {'name': 'Folder 2', }, ]) f1_id, f2_id = folders.ids tags = self.TargetModel.create([ {'name': 'Tag 1', 'folder_id': f2_id, 'color': 'Red', 'status': 'cool', }, {'name': 'Tag 2', 'folder_id': f1_id, 'status': 'cool', }, {'name': 'Tag 3', 'color': 'Green', 'status': 'cool', }, ]) t1_id, t2_id, t3_id = tags.ids records = self.SourceModel.create([ {'name': 'Rec 1', 'tag_ids': [t1_id, t2_id, t3_id], }, {'name': 'Rec 2', 'tag_ids': [t1_id], }, {'name': 'Rec 3', 'tag_ids': [t2_id, t3_id], }, {'name': 'Rec 4', }, ]) r1_id, r2_id, _, _ = records.ids # counters, expand, and group_by (many2one case) result = self.SourceModel.search_panel_select_multi_range( 'tag_ids', enable_counters=True, expand=True, group_by='folder_id' ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'Tag 1', 'id': t1_id, 'group_id': f2_id, 'group_name': 'Folder 2', }, {'__count': 2, 'display_name': 'Tag 2', 'id': t2_id, 'group_id': f1_id, 'group_name': 'Folder 1', }, {'__count': 2, 'display_name': 'Tag 3', 'id': t3_id, 'group_id': False, 'group_name': 'Not Set', }, ] ) # counters, expand, and group_by (selection case) result = self.SourceModel.search_panel_select_multi_range( 'tag_ids', enable_counters=True, expand=True, group_by='status' ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'Tag 1', 'id': t1_id, 'group_id': 'cool', 'group_name': 'Cool', }, {'__count': 2, 'display_name': 'Tag 2', 'id': t2_id, 'group_id': 'cool', 'group_name': 'Cool', }, {'__count': 2, 'display_name': 'Tag 3', 'id': t3_id, 'group_id': 'cool', 'group_name': 'Cool', }, ] ) # counters, expand, and group_by (other cases) result = self.SourceModel.search_panel_select_multi_range( 'tag_ids', enable_counters=True, expand=True, group_by='color' ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'Tag 1', 'id': t1_id, 'group_id': 'Red', 'group_name': 'Red', }, {'__count': 2, 'display_name': 'Tag 2', 'id': t2_id, 'group_id': False, 'group_name': 'Not Set', }, {'__count': 2, 'display_name': 'Tag 3', 'id': t3_id, 'group_id': 'Green', 'group_name': 'Green', }, ] ) # counters, expand, group_by (many2one case), and group_domain result = self.SourceModel.search_panel_select_multi_range( 'tag_ids', enable_counters=True, expand=True, group_by='folder_id', group_domain={ json.dumps(f1_id): [('tag_ids', 'in', [t1_id]), ], json.dumps(f2_id): [('tag_ids', 'in', [t2_id]), ], json.dumps(False): [('tag_ids', 'in', [t1_id]), ('tag_ids', 'in', [t2_id]), ], } ) self.assertEqual( result['values'], [ {'__count': 1, 'display_name': 'Tag 1', 'id': t1_id, 'group_id': f2_id, 'group_name': 'Folder 2', }, {'__count': 1, 'display_name': 'Tag 2', 'id': t2_id, 'group_id': f1_id, 'group_name': 'Folder 1', }, {'__count': 1, 'display_name': 'Tag 3', 'id': t3_id, 'group_id': False, 'group_name': 'Not Set', }, ] ) # counters, expand, group_by (other cases), and group_domain result = self.SourceModel.search_panel_select_multi_range( 'tag_ids', enable_counters=True, expand=True, group_by='color', group_domain={ json.dumps(False): [('tag_ids', 'in', [t1_id]), ], json.dumps('Green'): [('tag_ids', 'in', [t1_id]), ], } ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'Tag 1', 'id': t1_id, 'group_id': 'Red', 'group_name': 'Red', }, {'__count': 1, 'display_name': 'Tag 2', 'id': t2_id, 'group_id': False, 'group_name': 'Not Set', }, {'__count': 1, 'display_name': 'Tag 3', 'id': t3_id, 'group_id': 'Green', 'group_name': 'Green', }, ] ) # counters, expand, and no group_by result = self.SourceModel.search_panel_select_multi_range( 'tag_ids', enable_counters=True, expand=True, ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'Tag 1', 'id': t1_id, }, {'__count': 2, 'display_name': 'Tag 2', 'id': t2_id, }, {'__count': 2, 'display_name': 'Tag 3', 'id': t3_id, }, ] ) # counters, expand, no group_by, and search domain result = self.SourceModel.search_panel_select_multi_range( 'tag_ids', enable_counters=True, expand=True, search_domain=[['id', 'in', [r1_id, r2_id]]], ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'Tag 1', 'id': t1_id, }, {'__count': 1, 'display_name': 'Tag 2', 'id': t2_id, }, {'__count': 1, 'display_name': 'Tag 3', 'id': t3_id, }, ], ) # no counters, expand, and group_by (many2one case) result = self.SourceModel.search_panel_select_multi_range( 'tag_ids', expand=True, group_by='folder_id', ) self.assertEqual( result['values'], [ {'display_name': 'Tag 1', 'id': t1_id, 'group_id': f2_id, 'group_name': 'Folder 2', }, {'display_name': 'Tag 2', 'id': t2_id, 'group_id': f1_id, 'group_name': 'Folder 1', }, {'display_name': 'Tag 3', 'id': t3_id, 'group_id': False, 'group_name': 'Not Set', }, ] ) # no counters, expand, and no group_by result = self.SourceModel.search_panel_select_multi_range( 'tag_ids', expand=True, ) self.assertEqual( result['values'], [ {'display_name': 'Tag 1', 'id': t1_id, }, {'display_name': 'Tag 2', 'id': t2_id, }, {'display_name': 'Tag 3', 'id': t3_id, }, ], ) # no counters, expand, no group_by, and search_domain result = self.SourceModel.search_panel_select_multi_range( 'tag_ids', expand=True, search_domain=[['id', 'in', [r1_id, r2_id]]], ) self.assertEqual( result['values'], [ {'display_name': 'Tag 1', 'id': t1_id, }, {'display_name': 'Tag 2', 'id': t2_id, }, {'display_name': 'Tag 3', 'id': t3_id, }, ] ) # counters, no expand, group_by (many2one case), and search_domain result = self.SourceModel.search_panel_select_multi_range( 'tag_ids', enable_counters=True, group_by='folder_id', search_domain=[['id', '=', r2_id]], ) self.assertEqual( result['values'], [ {'__count': 1, 'display_name': 'Tag 1', 'id': t1_id, 'group_id': f2_id, 'group_name': 'Folder 2', }, ] ) # counters, no expand, no group_by, and search_domain result = self.SourceModel.search_panel_select_multi_range( 'tag_ids', enable_counters=True, search_domain=[['id', '=', r2_id]], ) self.assertEqual( result['values'], [ {'__count': 1, 'display_name': 'Tag 1', 'id': t1_id, }, ] ) # counters, no expand, no group_by, and category_domain result = self.SourceModel.search_panel_select_multi_range( 'tag_ids', enable_counters=True, category_domain=[['id', '=', r2_id]], ) self.assertEqual( result['values'], [ {'__count': 1, 'display_name': 'Tag 1', 'id': t1_id, }, {'__count': 0, 'display_name': 'Tag 2', 'id': t2_id, }, {'__count': 0, 'display_name': 'Tag 3', 'id': t3_id, }, ] ) # no counters, no expand, group_by (many2one case), and search_domain result = self.SourceModel.search_panel_select_multi_range( 'tag_ids', group_by='folder_id', search_domain=[['id', '=', r2_id]], ) self.assertEqual( result['values'], [ {'display_name': 'Tag 1', 'id': t1_id, 'group_id': f2_id, 'group_name': 'Folder 2', }, ] ) # no counters, no expand, no group_by, and search_domain result = self.SourceModel.search_panel_select_multi_range( 'tag_ids', search_domain=[['id', '=', r2_id]], ) self.assertEqual( result['values'], [ {'display_name': 'Tag 1', 'id': t1_id, }, ] ) # no counters, no expand, no group_by, and search_domain result = self.SourceModel.search_panel_select_multi_range( 'tag_ids', limit=2, ) self.assertEqual(result, SEARCH_PANEL_ERROR, ) # Selection case def test_selection_empty(self): result = self.SourceModel.search_panel_select_multi_range( 'state', expand=True, ) self.assertEqual( result['values'], [ {'display_name': 'A', 'id': 'a', }, {'display_name': 'B', 'id': 'b', }, ] ) def test_selection(self): records = self.SourceModel.create([ {'name': 'Rec 1', 'state': 'a', }, {'name': 'Rec 2', 'state': 'a', }, ]) r1_id, _ = records.ids # counters, expand, and group_by result = self.SourceModel.search_panel_select_multi_range( 'state', enable_counters=True, expand=True, group_by='not_possible_to_group', # no impact expected ) self.assertEqual( result['values'], [ {'display_name': 'A', 'id': 'a', '__count': 2, }, {'display_name': 'B', 'id': 'b', '__count': 0, }, ] ) # counters, expand, and no group_by result = self.SourceModel.search_panel_select_multi_range( 'state', enable_counters=True, expand=True, ) self.assertEqual( result['values'], [ {'display_name': 'A', 'id': 'a', '__count': 2, }, {'display_name': 'B', 'id': 'b', '__count': 0, }, ] ) # counters, expand, and search domain result = self.SourceModel.search_panel_select_multi_range( 'state', enable_counters=True, expand=True, search_domain=[['id', '=', r1_id]], # impact expected ) self.assertEqual( result['values'], [ {'display_name': 'A', 'id': 'a', '__count': 1, }, {'display_name': 'B', 'id': 'b', '__count': 0, }, ] ) # no counters and expand result = self.SourceModel.search_panel_select_multi_range( 'state', expand=True, ) self.assertEqual( result['values'], [ {'display_name': 'A', 'id': 'a', }, {'display_name': 'B', 'id': 'b', }, ] ) # no counters, expand, and search domain result = self.SourceModel.search_panel_select_multi_range( 'state', expand=True, search_domain=[['id', '=', r1_id]], # no impact expected ) self.assertEqual( result['values'], [ {'display_name': 'A', 'id': 'a', }, {'display_name': 'B', 'id': 'b', }, ] ) # counters and no expand result = self.SourceModel.search_panel_select_multi_range( 'state', enable_counters=True, ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'A', 'id': 'a', }, ] ) # no counters and no expand result = self.SourceModel.search_panel_select_multi_range( 'state', ) self.assertEqual( result['values'], [ {'display_name': 'A', 'id': 'a', }, ] )
34.166667
23,370
23,964
py
PYTHON
15.0
# -*- coding: utf-8 -*- import odoo.tests SEARCH_PANEL_ERROR = {'error_msg': "Too many items to display.", } @odoo.tests.tagged('post_install', '-at_install') class TestSelectRange(odoo.tests.TransactionCase): def setUp(self): super().setUp() self.SourceModel = self.env['test_search_panel.source_model'] self.TargetModel = self.env['test_search_panel.category_target_model'] self.TargetModelNoParentName = self.env['test_search_panel.category_target_model_no_parent_name'] # Many2one def test_many2one_empty(self): result = self.SourceModel.search_panel_select_range('folder_id') self.assertEqual( result, { 'parent_field': 'parent_name_id', 'values': [], } ) def test_many2one(self): parent_folders = self.TargetModel.create([ {'name': 'Folder 1', }, {'name': 'Folder 2', }, ]) f1_id, f2_id = parent_folders.ids children_folders = self.TargetModel.create([ {'name': 'Folder 3', 'parent_name_id': f1_id, }, {'name': 'Folder 4', 'parent_name_id': f2_id, }, ]) f3_id, f4_id = children_folders.ids records = self.SourceModel.create([ {'name': 'Rec 1', 'folder_id': f1_id, }, {'name': 'Rec 2', 'folder_id': f3_id, }, {'name': 'Rec 3', 'folder_id': f4_id, }, {'name': 'Rec 4', }, ]) r1_id, _, r3_id, _ = records.ids # counters, expand, and hierarchization result = self.SourceModel.search_panel_select_range( 'folder_id', enable_counters=True, expand=True, ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'Folder 1', 'id': f1_id, 'parent_name_id': False, }, {'__count': 1, 'display_name': 'Folder 2', 'id': f2_id, 'parent_name_id': False, }, {'__count': 1, 'display_name': 'Folder 3', 'id': f3_id, 'parent_name_id': f1_id, }, {'__count': 1, 'display_name': 'Folder 4', 'id': f4_id, 'parent_name_id': f2_id, }, ] ) # counters, expand, hierarchization, and search domain result = self.SourceModel.search_panel_select_range( 'folder_id', enable_counters=True, expand=True, search_domain=[['id', 'in', [r1_id, r3_id]]], # impact expected ) self.assertEqual( result['values'], [ {'__count': 1, 'display_name': 'Folder 1', 'id': f1_id, 'parent_name_id': False, }, {'__count': 1, 'display_name': 'Folder 2', 'id': f2_id, 'parent_name_id': False, }, {'__count': 0, 'display_name': 'Folder 3', 'id': f3_id, 'parent_name_id': f1_id, }, {'__count': 1, 'display_name': 'Folder 4', 'id': f4_id, 'parent_name_id': f2_id, }, ] ) # counters, expand, hierarchization, and reached limit result = self.SourceModel.search_panel_select_range( 'folder_id', enable_counters=True, expand=True, limit=2, ) self.assertEqual(result, SEARCH_PANEL_ERROR, ) # counters, expand, hierarchization, and unreached limit result = self.SourceModel.search_panel_select_range( 'folder_id', enable_counters=True, expand=True, limit=200, ) self.assertEqual( result, { 'parent_field': 'parent_name_id', 'values': [ {'__count': 2, 'display_name': 'Folder 1', 'id': f1_id, 'parent_name_id': False, }, {'__count': 1, 'display_name': 'Folder 2', 'id': f2_id, 'parent_name_id': False, }, {'__count': 1, 'display_name': 'Folder 3', 'id': f3_id, 'parent_name_id': f1_id, }, {'__count': 1, 'display_name': 'Folder 4', 'id': f4_id, 'parent_name_id': f2_id, }, ], } ) # counters, expand, and no hierarchization result = self.SourceModel.search_panel_select_range( 'folder_id', enable_counters=True, expand=True, hierarchize=False, ) self.assertEqual( result['values'], [ {'__count': 1, 'display_name': 'Folder 1', 'id': f1_id, }, {'__count': 0, 'display_name': 'Folder 2', 'id': f2_id, }, {'__count': 1, 'display_name': 'Folder 3', 'id': f3_id, }, {'__count': 1, 'display_name': 'Folder 4', 'id': f4_id, }, ] ) self.assertEqual( result['parent_field'], False ) # no counters, expand, and hierarchization result = self.SourceModel.search_panel_select_range( 'folder_id', expand=True, ) self.assertEqual( result['values'], [ {'display_name': 'Folder 1', 'id': f1_id, 'parent_name_id': False, }, {'display_name': 'Folder 2', 'id': f2_id, 'parent_name_id': False, }, {'display_name': 'Folder 3', 'id': f3_id, 'parent_name_id': f1_id, }, {'display_name': 'Folder 4', 'id': f4_id, 'parent_name_id': f2_id, }, ] ) # no counters, expand, hierarchization, and search domain result = self.SourceModel.search_panel_select_range( 'folder_id', expand=True, search_domain=[['id', 'in', [r1_id, r3_id]]], # no impact expected ) self.assertEqual( result['values'], [ {'display_name': 'Folder 1', 'id': f1_id, 'parent_name_id': False, }, {'display_name': 'Folder 2', 'id': f2_id, 'parent_name_id': False, }, {'display_name': 'Folder 3', 'id': f3_id, 'parent_name_id': f1_id, }, {'display_name': 'Folder 4', 'id': f4_id, 'parent_name_id': f2_id, }, ] ) # no counters, expand, and no hierarchization result = self.SourceModel.search_panel_select_range( 'folder_id', expand=True, hierarchize=False, ) self.assertEqual( result['values'], [ {'display_name': 'Folder 1', 'id': f1_id, }, {'display_name': 'Folder 2', 'id': f2_id, }, {'display_name': 'Folder 3', 'id': f3_id, }, {'display_name': 'Folder 4', 'id': f4_id, }, ] ) # counters, no expand, and hierarchization result = self.SourceModel.search_panel_select_range( 'folder_id', enable_counters=True, ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'Folder 1', 'id': f1_id, 'parent_name_id': False, }, {'__count': 1, 'display_name': 'Folder 2', 'id': f2_id, 'parent_name_id': False, }, {'__count': 1, 'display_name': 'Folder 3', 'id': f3_id, 'parent_name_id': f1_id, }, {'__count': 1, 'display_name': 'Folder 4', 'id': f4_id, 'parent_name_id': f2_id, }, ] ) self.assertEqual( result['parent_field'], 'parent_name_id' ) # counters, no expand, and no hierarchization result = self.SourceModel.search_panel_select_range( 'folder_id', enable_counters=True, hierarchize=False, ) self.assertEqual( result['values'], [ {'__count': 1, 'display_name': 'Folder 1', 'id': f1_id, }, {'__count': 1, 'display_name': 'Folder 3', 'id': f3_id, }, {'__count': 1, 'display_name': 'Folder 4', 'id': f4_id, }, ] ) self.assertEqual( result['parent_field'], False ) # counters, no expand, no hierarchization, and category_domain result = self.SourceModel.search_panel_select_range( 'folder_id', enable_counters=True, hierarchize=False, category_domain=[['id', 'in', [r1_id, r3_id]]], # impact expected ) self.assertEqual( result['values'], [ {'__count': 1, 'display_name': 'Folder 1', 'id': f1_id, }, {'__count': 0, 'display_name': 'Folder 3', 'id': f3_id, }, {'__count': 1, 'display_name': 'Folder 4', 'id': f4_id, }, ] ) self.assertEqual( result['parent_field'], False ) # counters, no expand, no hierarchization, and limit result = self.SourceModel.search_panel_select_range( 'folder_id', enable_counters=True, hierarchize=False, limit=2, ) self.assertEqual(result, SEARCH_PANEL_ERROR, ) # no counters, no expand, and hierarchization result = self.SourceModel.search_panel_select_range( 'folder_id', hierarchize=True, ) self.assertEqual( result['values'], [ {'display_name': 'Folder 1', 'id': f1_id, 'parent_name_id': False, }, {'display_name': 'Folder 2', 'id': f2_id, 'parent_name_id': False, }, {'display_name': 'Folder 3', 'id': f3_id, 'parent_name_id': f1_id, }, {'display_name': 'Folder 4', 'id': f4_id, 'parent_name_id': f2_id, }, ] ) self.assertEqual( result['parent_field'], 'parent_name_id' ) # no counters, no expand, and hierarchization result = self.SourceModel.search_panel_select_range( 'folder_id', search_domain=[(0, '=', 1)], ) self.assertEqual( result, {'parent_field': 'parent_name_id', 'values': [], } # should not be a SEARCH_PANEL_ERROR ) # no counters, no expand, and no hierarchization result = self.SourceModel.search_panel_select_range( 'folder_id', hierarchize=False, ) self.assertEqual( result['values'], [ {'display_name': 'Folder 1', 'id': f1_id, }, {'display_name': 'Folder 3', 'id': f3_id, }, {'display_name': 'Folder 4', 'id': f4_id, }, ] ) self.assertEqual( result['parent_field'], False ) # no counters, no expand, no hierarchization, and category_domain result = self.SourceModel.search_panel_select_range( 'folder_id', hierarchize=False, category_domain=[['id', 'in', [r1_id, r3_id]]], # no impact expected ) self.assertEqual( result['values'], [ {'display_name': 'Folder 1', 'id': f1_id, }, {'display_name': 'Folder 3', 'id': f3_id, }, {'display_name': 'Folder 4', 'id': f4_id, }, ] ) self.assertEqual( result['parent_field'], False ) # no counters, no expand, no hierarchization, and comodel_domain result = self.SourceModel.search_panel_select_range( 'folder_id', hierarchize=False, comodel_domain=[['id', 'in', [f1_id, f4_id]]] ) self.assertEqual( result['values'], [ {'display_name': 'Folder 1', 'id': f1_id, }, {'display_name': 'Folder 4', 'id': f4_id, }, ] ) self.assertEqual( result['parent_field'], False ) def test_many2one_deep_hierarchy(self): folders_level_0 = self.TargetModel.create([ {'name': 'Folder 1', }, {'name': 'Folder 2', }, {'name': 'Folder 3', }, ]) f1_id, f2_id, f3_id = folders_level_0.ids folders_level_1 = self.TargetModel.create([ {'name': 'Folder 4', 'parent_name_id': f1_id, }, {'name': 'Folder 5', 'parent_name_id': f2_id, }, {'name': 'Folder 6', 'parent_name_id': f2_id, }, ]) f4_id, f5_id, f6_id = folders_level_1.ids folders_level_2 = self.TargetModel.create([ {'name': 'Folder 7', 'parent_name_id': f4_id, }, {'name': 'Folder 8', 'parent_name_id': f6_id, }, ]) f7_id, f8_id = folders_level_2.ids folders_level_3 = self.TargetModel.create([ {'name': 'Folder 9', 'parent_name_id': f8_id, }, {'name': 'Folder 10', 'parent_name_id': f8_id, }, ]) f9_id, f10_id = folders_level_3.ids self.SourceModel.create([ {'name': 'Rec 1', 'folder_id': f1_id, }, {'name': 'Rec 2', 'folder_id': f6_id, }, {'name': 'Rec 3', 'folder_id': f7_id, }, {'name': 'Rec 4', 'folder_id': f7_id, }, {'name': 'Rec 5', 'folder_id': f9_id, }, {'name': 'Rec 6', 'folder_id': f10_id, }, ]) """ The folder tree is like this (the numbers are the local counts) f1_id (1) f2_id (0) f3_id (0) | / \ f4_id (0) f5_id (0) f6_id (1) | | f7_id (2) f8_id (0) / \ f9_id (1) f10_id (1) """ # counters, expand, and hierarchization result = self.SourceModel.search_panel_select_range( 'folder_id', enable_counters=True, expand=True, ) self.assertEqual( result['values'], [ {'__count': 3, 'display_name': 'Folder 1', 'id': f1_id, 'parent_name_id': False, }, {'__count': 1, 'display_name': 'Folder 10', 'id': f10_id, 'parent_name_id': f8_id, }, {'__count': 3, 'display_name': 'Folder 2', 'id': f2_id, 'parent_name_id': False, }, {'__count': 0, 'display_name': 'Folder 3', 'id': f3_id, 'parent_name_id': False, }, {'__count': 2, 'display_name': 'Folder 4', 'id': f4_id, 'parent_name_id': f1_id, }, {'__count': 0, 'display_name': 'Folder 5', 'id': f5_id, 'parent_name_id': f2_id, }, {'__count': 3, 'display_name': 'Folder 6', 'id': f6_id, 'parent_name_id': f2_id, }, {'__count': 2, 'display_name': 'Folder 7', 'id': f7_id, 'parent_name_id': f4_id, }, {'__count': 2, 'display_name': 'Folder 8', 'id': f8_id, 'parent_name_id': f6_id, }, {'__count': 1, 'display_name': 'Folder 9', 'id': f9_id, 'parent_name_id': f8_id, }, ] ) # no counters, no expand, hierarchization, and comodel_domain # We add a folder with a single record in it and declare it out of # comodel_domain. That folder should not appear in the final values. extra_folder_level_0 = self.TargetModel.create([ {'name': 'Folder 11', 'parent_name_id': False, }, ]) f11_id = extra_folder_level_0.id self.SourceModel.create([ {'name': 'Rec 7', 'folder_id': f11_id, }, ]) result = self.SourceModel.search_panel_select_range( 'folder_id', comodel_domain=[('id', 'not in', [f8_id, f11_id]) ], # impact expected ) self.assertEqual( result['values'], [ {'display_name': 'Folder 1', 'id': f1_id, 'parent_name_id': False, }, {'display_name': 'Folder 2', 'id': f2_id, 'parent_name_id': False, }, {'display_name': 'Folder 4', 'id': f4_id, 'parent_name_id': f1_id, }, {'display_name': 'Folder 6', 'id': f6_id, 'parent_name_id': f2_id, }, {'display_name': 'Folder 7', 'id': f7_id, 'parent_name_id': f4_id, }, ] ) # Many2one no parent name def test_many2one_empty_no_parent_name(self): result = self.SourceModel.search_panel_select_range('categ_id') self.assertEqual( result, { 'parent_field': False, 'values': [], } ) def test_many2one_no_parent_name(self): categories = self.TargetModelNoParentName.create([ {'name': 'Cat 1'}, {'name': 'Cat 2'}, {'name': 'Cat 3'}, ]) c1_id, c2_id, c3_id = categories.ids records = self.SourceModel.create([ {'name': 'Rec 1', 'categ_id': c1_id, }, {'name': 'Rec 2', 'categ_id': c2_id, }, {'name': 'Rec 3', 'categ_id': c2_id, }, {'name': 'Rec 4', }, ]) r1_id, _, r3_id, _ = records.ids # counters and expand result = self.SourceModel.search_panel_select_range( 'categ_id', enable_counters=True, expand=True, ) self.assertEqual( result['values'], [ {'__count': 0, 'display_name': 'Cat 3', 'id': c3_id, }, {'__count': 2, 'display_name': 'Cat 2', 'id': c2_id, }, {'__count': 1, 'display_name': 'Cat 1', 'id': c1_id, }, ] ) # counters, expand, and search domain result = self.SourceModel.search_panel_select_range( 'categ_id', enable_counters=True, expand=True, search_domain=[['id', 'in', [r1_id, r3_id]]], # impact expected ) self.assertEqual( result['values'], [ {'__count': 0, 'display_name': 'Cat 3', 'id': c3_id, }, {'__count': 1, 'display_name': 'Cat 2', 'id': c2_id, }, {'__count': 1, 'display_name': 'Cat 1', 'id': c1_id, }, ] ) # no counters and expand result = self.SourceModel.search_panel_select_range( 'categ_id', expand=True, ) self.assertEqual( result['values'], [ {'display_name': 'Cat 3', 'id': c3_id, }, {'display_name': 'Cat 2', 'id': c2_id, }, {'display_name': 'Cat 1', 'id': c1_id, }, ] ) # no counters, expand, and search domain result = self.SourceModel.search_panel_select_range( 'categ_id', expand=True, search_domain=[['id', 'in', [r1_id, r3_id]]], # no impact expected ) self.assertEqual( result['values'], [ {'display_name': 'Cat 3', 'id': c3_id, }, {'display_name': 'Cat 2', 'id': c2_id, }, {'display_name': 'Cat 1', 'id': c1_id, }, ] ) # counters and no expand result = self.SourceModel.search_panel_select_range( 'categ_id', enable_counters=True, ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'Cat 2', 'id': c2_id, }, {'__count': 1, 'display_name': 'Cat 1', 'id': c1_id, }, ] ) self.assertEqual( result['parent_field'], False ) # no counters and no expand result = self.SourceModel.search_panel_select_range( 'categ_id', ) self.assertEqual( result['values'], [ {'display_name': 'Cat 2', 'id': c2_id, }, {'display_name': 'Cat 1', 'id': c1_id, }, ] ) self.assertEqual( result['parent_field'], False ) # Selection case def test_selection_empty(self): result = self.SourceModel.search_panel_select_range( 'state', expand=True, ) self.assertEqual( result, { 'parent_field': False, 'values': [ {'display_name': 'A', 'id': 'a', }, {'display_name': 'B', 'id': 'b', }, ] } ) def test_selection(self): records = self.SourceModel.create([ {'name': 'Rec 1', 'state': 'a', }, {'name': 'Rec 2', 'state': 'a', }, ]) r1_id, _ = records.ids # counters and expand result = self.SourceModel.search_panel_select_range( 'state', enable_counters=True, expand=True, ) self.assertEqual( result['values'], [ {'display_name': 'A', 'id': 'a', '__count': 2, }, {'display_name': 'B', 'id': 'b', '__count': 0, }, ] ) # counters, expand, and search domain result = self.SourceModel.search_panel_select_range( 'state', enable_counters=True, expand=True, search_domain=[['id', '=', r1_id]], # impact expected ) self.assertEqual( result['values'], [ {'display_name': 'A', 'id': 'a', '__count': 1, }, {'display_name': 'B', 'id': 'b', '__count': 0, }, ] ) # no counters and expand result = self.SourceModel.search_panel_select_range( 'state', expand=True, ) self.assertEqual( result['values'], [ {'display_name': 'A', 'id': 'a', }, {'display_name': 'B', 'id': 'b', }, ] ) # no counters, expand, and search domain result = self.SourceModel.search_panel_select_range( 'state', expand=True, search_domain=[['id', '=', r1_id]], # no impact expected ) self.assertEqual( result['values'], [ {'display_name': 'A', 'id': 'a', }, {'display_name': 'B', 'id': 'b', }, ] ) # counters and no expand result = self.SourceModel.search_panel_select_range( 'state', enable_counters=True, ) self.assertEqual( result['values'], [ {'__count': 2, 'display_name': 'A', 'id': 'a', }, ] ) # no counters and no expand result = self.SourceModel.search_panel_select_range( 'state', ) self.assertEqual( result['values'], [ {'display_name': 'A', 'id': 'a', }, ] )
33.895332
23,964
1,583
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import fields, models class SourceModel(models.Model): _name = 'test_search_panel.source_model' _description = 'Source Model' name = fields.Char('Name', required=True) state = fields.Selection([('a', "A"), ('b', "B")]) folder_id = fields.Many2one('test_search_panel.category_target_model') categ_id = fields.Many2one( 'test_search_panel.category_target_model_no_parent_name') tag_ids = fields.Many2many( 'test_search_panel.filter_target_model', 'rel_table', string="Tags") tag_id = fields.Many2one('test_search_panel.filter_target_model', string="Tag") class CategoryTargetModel(models.Model): _name = 'test_search_panel.category_target_model' _order = 'name' _description = 'Category target model' _parent_name = 'parent_name_id' name = fields.Char('Name', required=True) parent_name_id = fields.Many2one('test_search_panel.category_target_model') class CategoryTargetModelNoParentName(models.Model): _name = 'test_search_panel.category_target_model_no_parent_name' _order = 'id desc' _description = 'Category target model' name = fields.Char('Name', required=True) class FilterTargetModel(models.Model): _name = 'test_search_panel.filter_target_model' _order = 'name' _description = 'Filter target model' name = fields.Char('Name', required=True) status = fields.Selection( [('cool', "Cool"), ('unknown', 'Unknown')]) color = fields.Char() folder_id = fields.Many2one('test_search_panel.category_target_model')
34.413043
1,583
244
py
PYTHON
15.0
{ 'name': 'test module to test data only modules', 'description': 'Fake module to test data module installation without __init__.py', 'version': '0.0.1', 'category': 'Hidden/Tests', 'sequence': 0, 'license': 'LGPL-3', }
30.5
244
313
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'test-lint', 'version': '0.1', 'category': 'Hidden/Tests', 'description': """A module to test Odoo code with various linters.""", 'maintainer': 'Odoo SA', 'depends': ['base'], 'installable': True, 'auto_install': False, 'license': 'LGPL-3', }
26.083333
313
5,714
py
PYTHON
15.0
import os import astroid from pylint import checkers, interfaces DFTL_CURSOR_EXPR = [ 'self.env.cr', 'self._cr', # new api 'self.cr', # controllers and test 'cr', # old api ] class OdooBaseChecker(checkers.BaseChecker): __implements__ = interfaces.IAstroidChecker name = 'odoo' msgs = { 'E8501': ( 'Possible SQL injection risk.', 'sql-injection', 'See http://www.bobby-tables.com try using ' 'execute(query, tuple(params))', ) } def _get_cursor_name(self, node): expr_list = [] node_expr = node.expr while isinstance(node_expr, astroid.Attribute): expr_list.insert(0, node_expr.attrname) node_expr = node_expr.expr if isinstance(node_expr, astroid.Name): expr_list.insert(0, node_expr.name) cursor_name = '.'.join(expr_list) return cursor_name def _allowable(self, node): """ :type node: NodeNG """ infered = checkers.utils.safe_infer(node) # The package 'psycopg2' must be installed to infer # ignore sql.SQL().format if infered and infered.pytype().startswith('psycopg2'): return True if isinstance(node, astroid.Call): node = node.func # self._thing is OK (mostly self._table), self._thing() also because # it's a common pattern of reports (self._select, self._group_by, ...) return (isinstance(node, astroid.Attribute) and isinstance(node.expr, astroid.Name) and node.attrname.startswith('_') # cr.execute('SELECT * FROM %s' % 'table') is OK since that is a constant or isinstance(node, astroid.Const) ) def _check_concatenation(self, node): node = self.resolve(node) if self._allowable(node): return False if isinstance(node, astroid.BinOp) and node.op in ('%', '+'): if isinstance(node.right, astroid.Tuple): # execute("..." % (self._table, thing)) if not all(map(self._allowable, node.right.elts)): return True elif isinstance(node.right, astroid.Dict): # execute("..." % {'table': self._table} if not all(self._allowable(v) for _, v in node.right.items): return True elif not self._allowable(node.right): # execute("..." % self._table) return True # Consider cr.execute('SELECT ' + operator + ' FROM table' + 'WHERE')" # node.repr_tree() # BinOp( # op='+', # left=BinOp( # op='+', # left=BinOp( # op='+', # left=Const(value='SELECT '), # right=Name(name='operator')), # right=Const(value=' FROM table')), # right=Const(value='WHERE')) # Notice that left node is another BinOp node return self._check_concatenation(node.left) # check execute("...".format(self._table, table=self._table)) if isinstance(node, astroid.Call) \ and isinstance(node.func, astroid.Attribute) \ and node.func.attrname == 'format': return not ( all(map(self._allowable, node.args or [])) and all(self._allowable(keyword.value) for keyword in (node.keywords or [])) ) # check execute(f'foo {...}') if isinstance(node, astroid.JoinedStr): return not all( self._allowable(formatted.value) for formatted in node.nodes_of_class(astroid.FormattedValue) ) def resolve(self, node): # if node is a variable, find how it was built if isinstance(node, astroid.Name): for target in node.lookup(node.name)[1]: # could also be e.g. arguments (if the source is a function parameter) if isinstance(target.parent, astroid.Assign): # FIXME: handle multiple results (e.g. conditional assignment) return target.parent.value # otherwise just return the original node for checking return node def _check_sql_injection_risky(self, node): # Inspired from OCA/pylint-odoo project # Thanks @moylop260 (Moisés López) & @nilshamerlinck (Nils Hamerlinck) current_file_bname = os.path.basename(self.linter.current_file) if not ( # .execute() or .executemany() isinstance(node, astroid.Call) and node.args and isinstance(node.func, astroid.Attribute) and node.func.attrname in ('execute', 'executemany') and # cursor expr (see above) self._get_cursor_name(node.func) in DFTL_CURSOR_EXPR and # cr.execute("select * from %s" % foo, [bar]) -> probably a good reason for string formatting len(node.args) <= 1 and # ignore in test files, probably not accessible not current_file_bname.startswith('test_') ): return False first_arg = node.args[0] is_concatenation = self._check_concatenation(first_arg) if is_concatenation is not None: return is_concatenation return True @checkers.utils.check_messages('sql-injection') def visit_call(self, node): if self._check_sql_injection_risky(node): self.add_message('sql-injection', node=node) def register(linter): linter.register_checker(OdooBaseChecker(linter))
38.08
5,712
3,885
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # pylint: disable=unbalanced-tuple-unpacking import logging import re from odoo import tools from odoo.modules import get_resource_from_path from . import lint_case _logger = logging.getLogger(__name__) TSTRING_RE = re.compile(r'_l?t\(\s*`.*?\s*`\s*\)', re.DOTALL) EXPRESSION_RE = re.compile(r'\$\{.+?\}') UNDERSCORE_RE = re.compile(r'\b_\(\s*[\'"]') class TestJsTranslations(lint_case.LintCase): def check_text(self, text): """ Search for translation errors in the text :param text: The js text to search :return: A list of tuple with line number and invalid template string, or None for underscore errors """ error_list = list() for m in TSTRING_RE.finditer(text): template_string = m.group(0) if EXPRESSION_RE.search(template_string): line_nb = text[:m.start()].count('\n') + 1 error_list.append((line_nb, template_string)) for m in UNDERSCORE_RE.finditer(text): lineno = text[:m.start()].count('\n') + 1 error_list.append((lineno, None)) return error_list def test_regular_expression(self): bad_js = """ const foo = { valid: _lt(`not useful but valid template-string`), invalid: _lt(`invalid template-string that spans multiple lines ${expression}`) }; """ error_list = self.check_text(bad_js) self.assertEqual(len(error_list), 1) [(line, template_string)] = error_list self.assertEqual(line, 4) self.assertIn('invalid template-string', template_string) self.assertNotIn('but valid template-string', template_string) def test_regular_expression_long(self): bad_js = """ thing = _t( `foo ${this + is(a, very) - long == expression}` ); """ error_list = self.check_text(bad_js) self.assertEqual(len(error_list), 1) [(line, template_string)] = error_list self.assertEqual(line, 2) self.assertIn('foo ${this + is(a, very) - long == expression}', template_string) def test_matches_underscore(self): bad_js = """ const thing1 = _('literal0'); const thing0 = _([]); const thing2 = _("literal1"); """ self.assertEqual( self.check_text(bad_js), [(2, None), (4, None)] ) def test_js_translations(self): """ Test that there are no translation of JS template strings or underscore calls misused as translation markers """ counter = 0 failures = 0 for js_file in self.iter_module_files('*.js'): # lodash has string methods and occurrences of `_('text')` in its comments if js_file.endswith('/lodash.js'): continue counter += 1 with tools.file_open(js_file, 'r') as f: js_txt = f.read() error_list = self.check_text(js_txt) for line_number, template_string in error_list: failures += 1 mod, relative_path, _ = get_resource_from_path(js_file) if template_string: prefix = "Translation of a template string" suffix = template_string else: prefix = "underscore.js used as translation function" suffix = "_t and _lt are the JS translation functions" _logger.error("%s found in `%s/%s` at line %s: %s", prefix, mod, relative_path, line_number, suffix) _logger.info('%s files tested', counter) if failures > 0: self.fail("%s invalid template strings found in js files." % failures)
35
3,885
1,800
py
PYTHON
15.0
import ast import itertools import os from . import lint_case class OnchangeChecker(lint_case.NodeVisitor): def matches_onchange(self, node): if isinstance(node, ast.Call): if isinstance(node.func, ast.Attribute): return node.func.attr == 'onchange' if isinstance(node.func, ast.Name): return node.func.id == 'onchange' return False def visit_FunctionDef(self, node): walker = ast.walk(node) if any(map(self.matches_onchange, node.decorator_list)) else [] # can stop at the first match: an @onchange function either mentions # domains or does not return itertools.islice(( n for n in walker if isinstance(n, getattr(ast, 'Str', type(None))) and n.s == 'domain' or isinstance(n, getattr(ast, 'Constant', type(None))) and n.value == 'domain' ), 1) class TestOnchangeDomains(lint_case.LintCase): """ Would ideally have been a pylint module but that's slow as molasses (takes minutes to run, and can blow up entirely depending on the pylint version) """ def test_forbid_domains_in_onchanges(self): """ Dynamic domains (returning a domain from an onchange) are deprecated and should not be used in "standard" Odoo anymore """ checker = OnchangeChecker() rs = [] for path in self.iter_module_files('*.py'): with open(path, 'rb') as f: t = ast.parse(f.read(), path) rs.extend(zip(itertools.repeat(os.path.relpath(path)), checker.visit(t))) rs.sort(key=lambda t: t[0]) assert not rs, "probable domains in onchanges at\n" + '\n'.join( "- %s:%d" % (path, node.lineno) for path, node in rs )
37.5
1,800
1,696
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import ast import itertools import os from . import lint_case class L10nChecker(lint_case.NodeVisitor): def matches_tagged(self, node): if isinstance(node, ast.Call): if isinstance(node.func, ast.Attribute): return node.func.attr == 'tagged' if isinstance(node.func, ast.Name): return node.func.id == 'tagged' return False def visit_ClassDef(self, node): tags = { arg.value for deco in node.decorator_list for arg in deco.args if self.matches_tagged(deco) } if ( (len({'post_install_l10n', 'external_l10n'} & tags) != 1) or ('post_install_l10n' in tags and 'post_install' not in tags) # or ('post_install_l10n' not in tags and 'post_install' in tags) or ('external_l10n' in tags and 'external' not in tags) or ('external_l10n' not in tags and 'external' in tags) ): return [node] return [] class L10nLinter(lint_case.LintCase): def test_l10n_test_tags(self): checker = L10nChecker() rs = [] for path in self.iter_module_files('**/l10n_*/tests/*.py'): with open(path, 'rb') as f: t = ast.parse(f.read(), path) rs.extend(zip(itertools.repeat(os.path.relpath(path)), checker.visit(t))) rs.sort(key=lambda t: t[0]) assert not rs, "missing `post_install_l10n` tag at\n" + '\n'.join( "- %s:%d" % (path, node.lineno) for path, node in rs )
33.254902
1,696
853
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from pathlib import Path from odoo.modules import get_modules, get_module_path from . import lint_case _logger = logging.getLogger(__name__) # whitelist that allow data modules only WHITELIST = ['test_data_module', ] class TestDunderinit(lint_case.LintCase): def test_dunderinit(self): """ Test that __init__.py exists in Odoo modules, otherwise they won't get packaged""" modules_list = [mod for mod in get_modules() if mod not in WHITELIST] for mod in modules_list: dunderinit_path = Path(get_module_path(mod)) / '__init__.py' self.assertTrue(dunderinit_path.is_file(), "Missing `__init__.py ` in module %s" % mod) _logger.info('%s modules checked', len(modules_list))
34.12
853
2,984
py
PYTHON
15.0
import json import os import tempfile import unittest from subprocess import run, PIPE from textwrap import dedent from odoo import tools from odoo.tests.common import TransactionCase try: import pylint except ImportError: pylint = None try: pylint_bin = tools.which('pylint') except IOError: pylint_bin = None HERE = os.path.dirname(os.path.realpath(__file__)) @unittest.skipUnless(pylint and pylint_bin, "testing lints requires pylint") class TestSqlLint(TransactionCase): def check(self, testtext): with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', delete=False) as f: self.addCleanup(os.remove, f.name) f.write(dedent(testtext).strip()) result = run( [pylint_bin, f'--rcfile={os.devnull}', '--load-plugins=_odoo_checker_sql_injection', '--disable=all', '--enable=sql-injection', '--output-format=json', f.name, ], check=False, stdout=PIPE, encoding='utf-8', env={ **os.environ, 'PYTHONPATH': HERE+os.pathsep+os.environ.get('PYTHONPATH', ''), } ) return result.returncode, json.loads(result.stdout) def test_printf(self): r, [err] = self.check(""" def do_the_thing(cr, name): cr.execute('select %s from thing' % name) """) self.assertTrue(r, "should have noticed the injection") self.assertEqual(err['line'], 2, err) r, errs = self.check(""" def do_the_thing(self): self.env.cr.execute("select thing from %s" % self._table) """) self.assertFalse(r, f"underscore-attributes are allowed\n{errs}") r, errs = self.check(""" def do_the_thing(self): query = "select thing from %s" self.env.cr.execute(query % self._table) """) self.assertFalse(r, f"underscore-attributes are allowed\n{errs}") def test_fstring(self): r, [err] = self.check(""" def do_the_thing(cr, name): cr.execute(f'select {name} from thing') """) self.assertTrue(r, "should have noticed the injection") self.assertEqual(err['line'], 2, err) r, errs = self.check(""" def do_the_thing(cr, name): cr.execute(f'select name from thing') """) self.assertFalse(r, f"unnecessary fstring should be innocuous\n{errs}") r, errs = self.check(""" def do_the_thing(cr, name, value): cr.execute(f'select {name} from thing where field = %s', [value]) """) self.assertFalse(r, f"probably has a good reason for the extra arg\n{errs}") r, errs = self.check(""" def do_the_thing(self): self.env.cr.execute(f'select name from {self._table}') """) self.assertFalse(r, f'underscore-attributes are allowable\n{errs}')
32.791209
2,984
1,013
py
PYTHON
15.0
import ast import fnmatch import os j = os.path.join from odoo.modules import get_modules, get_module_path from odoo.tests import BaseCase class LintCase(BaseCase): """ Utility method for lint-type cases """ def iter_module_files(self, *globs): """ Yields the paths of all the module files matching the provided globs (AND-ed) """ for modroot in map(get_module_path, get_modules()): for root, _, fnames in os.walk(modroot): fnames = [j(root, n) for n in fnames] for glob in globs: fnames = fnmatch.filter(fnames, glob) yield from fnames class NodeVisitor(): """Simple NodeVisitor.""" def visit(self, node): method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self.generic_visit) return visitor(node) def generic_visit(self, node): for child in ast.iter_child_nodes(node): yield from self.visit(child)
28.138889
1,013
1,291
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import os import odoo from . import lint_case _logger = logging.getLogger(__name__) MARKERS = [b'<' * 7, b'>' * 7] EXTENSIONS = ('.py', '.js', '.xml', '.less', '.sass') class TestConflictMarkers(lint_case.LintCase): def check_file(self, fullpath_name): with open(fullpath_name, 'rb') as f: content = f.read() self.assertFalse(any(m in content for m in MARKERS), 'Conflict markers found in %s' % fullpath_name) def test_conflict_markers(self): """ Test that there are no conflict markers left in Odoo files """ counter = 0 odoo_path = os.path.abspath(os.path.dirname(odoo.__file__)) paths = odoo.addons.__path__ + [odoo_path] paths.remove(os.path.join(odoo_path, 'addons')) # avoid checking odoo/addons twice for p in paths: for dp, _, file_names in os.walk(p): if 'node_modules' in dp: continue for fn in file_names: if fn.endswith(EXTENSIONS): self.check_file(os.path.join(dp, fn)) counter += 1 _logger.info('%s files tested', counter)
32.275
1,291
2,956
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging try: import pylint except ImportError: pylint = None import subprocess import os from os.path import join from odoo.tests.common import TransactionCase from odoo import tools from odoo.modules import get_modules, get_module_path HERE = os.path.dirname(os.path.realpath(__file__)) _logger = logging.getLogger(__name__) class TestPyLint(TransactionCase): ENABLED_CODES = [ 'used-before-assignment', 'undefined-variable', 'eval-used', 'unreachable', 'function-redefined', # custom checkers 'sql-injection', 'gettext-variable', 'raise-unlink-override', ] BAD_FUNCTIONS = [ 'input', ] BAD_MODULES = [ 'csv', 'urllib', 'cgi', ] + list(tools.SUPPORTED_DEBUGGER) def _skip_test(self, reason): _logger.warning(reason) self.skipTest(reason) def test_pylint(self): if pylint is None: self._skip_test('please install pylint') required_pylint_version = tools.parse_version('1.6.4') if self._python_version >= (3, 6): required_pylint_version = tools.parse_version('1.7.0') if tools.parse_version(getattr(pylint, '__version__', '0.0.1')) < required_pylint_version: self._skip_test('please upgrade pylint to >= %s' % required_pylint_version) paths = [tools.config['root_path']] for module in get_modules(): module_path = get_module_path(module) if not module_path.startswith(join(tools.config['root_path'], 'addons')): paths.append(module_path) options = [ '--rcfile=%s' % os.devnull, '--disable=all', '--enable=%s' % ','.join(self.ENABLED_CODES), '--reports=n', "--msg-template='{msg} ({msg_id}) at {path}:{line}'", '--load-plugins=pylint.extensions.bad_builtin,_odoo_checker_sql_injection,_odoo_checker_gettext,_odoo_checker_unlink_override', '--bad-functions=%s' % ','.join(self.BAD_FUNCTIONS), '--deprecated-modules=%s' % ','.join(self.BAD_MODULES) ] pypath = HERE + os.pathsep + os.environ.get('PYTHONPATH', '') env = dict(os.environ, PYTHONPATH=pypath) try: pylint_bin = tools.which('pylint') process = subprocess.Popen( [pylint_bin] + options + paths, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, ) except (OSError, IOError): self._skip_test('pylint executable not found in the path') else: out, err = process.communicate() if process.returncode: self.fail("pylint test failed:\n" + (b"\n" + out + b"\n" + err).decode('utf-8').strip())
32.130435
2,956
1,455
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import os import re import subprocess from unittest import skipIf from odoo import tools from odoo.modules import get_modules, get_module_path from . import lint_case MAX_ES_VERSION = 'es10' _logger = logging.getLogger(__name__) try: es_check = tools.misc.find_in_path('es-check') except IOError: es_check = None @skipIf(es_check is None, "es-check tool not found on this system") class TestECMAScriptVersion(lint_case.LintCase): longMessage = True def test_ecmascript_version(self): """ Test that there is no unsupported ecmascript in javascript files """ files_to_check = [ p for p in self.iter_module_files('*.js') if 'static/test' not in p if 'static/src/tests' not in p if 'static/lib/qweb/qweb.js' not in p # because this file is not bundled at all if 'py.js/lib/py.js' not in p # because it is not "strict" compliant if 'static/lib/epos-2.12.0.js' not in p # same ] _logger.info('Testing %s js files', len(files_to_check)) cmd = [es_check, MAX_ES_VERSION] + files_to_check + ['--module'] process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = process.communicate() self.assertEqual(process.returncode, 0, msg=out.decode())
32.333333
1,455
1,262
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import Counter from odoo.modules import get_modules, get_resource_path from odoo.tests.common import TransactionCase from odoo.tools.translate import TranslationFileReader class PotLinter(TransactionCase): def test_pot_duplicate_entries(self): def format(entry): # TranslationFileReader only returns those three types if entry['type'] == 'model': return ('model', entry['name'], entry['imd_name']) elif entry['type'] == 'model_terms': return ('model_terms', entry['name'], entry['imd_name'], entry['src']) elif entry['type'] == 'code': return ('code', entry['src']) # retrieve all modules, and their corresponding POT file for module in get_modules(): filename = get_resource_path(module, 'i18n', module + '.pot') if not filename: continue counts = Counter(map(format, TranslationFileReader(filename))) duplicates = [key for key, count in counts.items() if count > 1] self.assertFalse(duplicates, "Duplicate entries found in %s" % filename)
43.517241
1,262
1,842
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import re import subprocess from unittest import skipIf from odoo import tools from . import lint_case RULES = ('{' '"no-undef": "error",' '"no-restricted-globals": ["error", "event", "self"],' '"no-const-assign": ["error"],' '"no-debugger": ["error"],' '"no-dupe-class-members": ["error"]' '}' ) PARSER_OPTIONS = '{ecmaVersion: 2019, sourceType: module}' GLOBAL = ','.join([ 'owl', 'odoo', '$', 'jQuery', '_', 'Chart', 'fuzzy', 'QWeb2', 'Popover', 'StackTrace', 'QUnit', 'luxon', 'moment', 'py', 'ClipboardJS', 'globalThis', ]) _logger = logging.getLogger(__name__) try: eslint = tools.misc.find_in_path('eslint') except IOError: eslint = None @skipIf(eslint is None, "eslint tool not found on this system") class TestESLint(lint_case.LintCase): longMessage = True def test_eslint_version(self): """ Test that there are no eslint errors in javascript files """ files_to_check = [ p for p in self.iter_module_files('**/static/**/*.js') if not re.match('.*/libs?/.*', p) # don't check libraries ] _logger.info('Testing %s js files', len(files_to_check)) # https://eslint.org/docs/user-guide/command-line-interface cmd = [eslint, '--no-eslintrc', '--env', 'browser', '--env', 'es2017', '--parser-options', PARSER_OPTIONS, '--rule', RULES, '--global', GLOBAL] + files_to_check process = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False) self.assertEqual(process.returncode, 0, msg=process.stdout.decode())
28.78125
1,842
856
py
PYTHON
15.0
import os import astroid from pylint import checkers, interfaces class OdooBaseChecker(checkers.BaseChecker): __implements__ = interfaces.IAstroidChecker name = 'odoo' msgs = { 'E8502': ( 'Bad usage of _, _lt function.', 'gettext-variable', 'See https://www.odoo.com/documentation/15.0/developer/misc/i18n/translations.html#variables' ) } @checkers.utils.check_messages('gettext-variable') def visit_call(self, node): if isinstance(node.func, astroid.Name) and node.func.name in ('_', '_lt'): first_arg = node.args[0] if not (isinstance(first_arg, astroid.Const) and isinstance(first_arg.value, str)): self.add_message('gettext-variable', node=node) def register(linter): linter.register_checker(OdooBaseChecker(linter))
30.571429
856
1,230
py
PYTHON
15.0
import astroid from pylint import checkers, interfaces class OdooBaseChecker(checkers.BaseChecker): __implements__ = interfaces.IAstroidChecker name = 'odoo' msgs = { 'E8503': ( 'Raise inside unlink override.', 'raise-unlink-override', 'Raising errors is not allowed inside unlink overrides, ' 'you can create a method and decorate it with ' '@api.ondelete(at_uninstall=False), only use ' 'at_uninstall=True if you know what you are doing.' ) } @staticmethod def _inherits_BaseModel(node): return any(getattr(n, 'name', False) == 'BaseModel' for n in node.ancestors()) def visit_raise(self, node): parent = node.parent while parent: if isinstance(parent, astroid.FunctionDef) and parent.name == 'unlink': parent = parent.parent if isinstance(parent, astroid.ClassDef) and self._inherits_BaseModel(parent): self.add_message('raise-unlink-override', node=node) break continue parent = parent.parent def register(linter): linter.register_checker(OdooBaseChecker(linter))
34.166667
1,230
219
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': "Test Performance", 'version': "1.0", 'category': "Hidden", 'depends': ['base'], 'data': [ 'security/ir.model.access.csv', ], 'license': 'LGPL-3', }
19.909091
219
21,282
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import defaultdict import json from odoo.addons.base.tests.common import SavepointCaseWithUserDemo from odoo.tests.common import TransactionCase, users, warmup, tagged from odoo.tools import mute_logger, json_default from odoo import Command class TestPerformance(SavepointCaseWithUserDemo): @classmethod def setUpClass(cls): super(TestPerformance, cls).setUpClass() cls._load_partners_set() partner3 = cls.env['res.partner'].search([('name', '=', 'AnalytIQ')], limit=1) partner4 = cls.env['res.partner'].search([('name', '=', 'Urban Trends')], limit=1) partner10 = cls.env['res.partner'].search([('name', '=', 'Ctrl-Alt-Fix')], limit=1) partner12 = cls.env['res.partner'].search([('name', '=', 'Ignitive Labs')], limit=1) cls.env['test_performance.base'].create([{ 'name': 'Object 0', 'value': 0, 'partner_id': partner3.id, }, { 'name': 'Object 1', 'value': 10, 'partner_id': partner3.id, }, { 'name': 'Object 2', 'value': 20, 'partner_id': partner4.id, }, { 'name': 'Object 3', 'value': 30, 'partner_id': partner10.id, }, { 'name': 'Object 4', 'value': 40, 'partner_id': partner12.id, }]) @users('__system__', 'demo') @warmup def test_read_base(self): """ Read records. """ records = self.env['test_performance.base'].search([]) self.assertEqual(len(records), 5) with self.assertQueryCount(__system__=2, demo=2): # without cache for record in records: record.partner_id.country_id.name with self.assertQueryCount(0): # with cache for record in records: record.partner_id.country_id.name with self.assertQueryCount(0): # value_pc must have been prefetched, too for record in records: record.value_pc @warmup def test_read_base_depends_context(self): """ Compute in batch even when in cache in another context. """ records = self.env['test_performance.base'].search([]) self.assertEqual(len(records), 5) with self.assertQueryCount(1): for record in records.with_context(key=1): self.assertEqual(record.value_ctx, 1) with self.assertQueryCount(1): for record in records.with_context(key=2): self.assertEqual(record.value_ctx, 2) with self.assertQueryCount(1): for record in records: self.assertEqual(record.with_context(key=3).value_ctx, 3) @users('__system__', 'demo') @warmup def test_write_base(self): """ Write records (no recomputation). """ records = self.env['test_performance.base'].search([]) self.assertEqual(len(records), 5) with self.assertQueryCount(__system__=1, demo=1): records.write({'name': 'X'}) @users('__system__', 'demo') @warmup def test_write_base_with_recomputation(self): """ Write records (with recomputation). """ records = self.env['test_performance.base'].search([]) self.assertEqual(len(records), 5) with self.assertQueryCount(__system__=1, demo=1): records.write({'value': 42}) @mute_logger('odoo.models.unlink') @users('__system__', 'demo') @warmup def test_write_base_one2many(self): """ Write on one2many field. """ rec1 = self.env['test_performance.base'].create({'name': 'X'}) # create N lines on rec1: O(N) queries with self.assertQueryCount(3): rec1.invalidate_cache() rec1.write({'line_ids': [Command.create({'value': 0})]}) self.assertEqual(len(rec1.line_ids), 1) with self.assertQueryCount(15): rec1.invalidate_cache() rec1.write({'line_ids': [Command.create({'value': val}) for val in range(1, 12)]}) self.assertEqual(len(rec1.line_ids), 12) lines = rec1.line_ids # update N lines: O(N) queries with self.assertQueryCount(6): rec1.invalidate_cache() rec1.write({'line_ids': [Command.update(line.id, {'value': 42}) for line in lines[0]]}) self.assertEqual(rec1.line_ids, lines) with self.assertQueryCount(26): rec1.invalidate_cache() rec1.write({'line_ids': [Command.update(line.id, {'value': 42 + line.id}) for line in lines[1:]]}) self.assertEqual(rec1.line_ids, lines) # delete N lines: O(1) queries with self.assertQueryCount(14): rec1.invalidate_cache() rec1.write({'line_ids': [Command.delete(line.id) for line in lines[0]]}) self.assertEqual(rec1.line_ids, lines[1:]) with self.assertQueryCount(12): rec1.invalidate_cache() rec1.write({'line_ids': [Command.delete(line.id) for line in lines[1:]]}) self.assertFalse(rec1.line_ids) self.assertFalse(lines.exists()) rec1.write({'line_ids': [Command.create({'value': val}) for val in range(12)]}) lines = rec1.line_ids # unlink N lines: O(1) queries with self.assertQueryCount(14): rec1.invalidate_cache() rec1.write({'line_ids': [Command.unlink(line.id) for line in lines[0]]}) self.assertEqual(rec1.line_ids, lines[1:]) with self.assertQueryCount(12): rec1.invalidate_cache() rec1.write({'line_ids': [Command.unlink(line.id) for line in lines[1:]]}) self.assertFalse(rec1.line_ids) self.assertFalse(lines.exists()) rec1.write({'line_ids': [Command.create({'value': val}) for val in range(12)]}) lines = rec1.line_ids rec2 = self.env['test_performance.base'].create({'name': 'X'}) # link N lines from rec1 to rec2: O(1) queries with self.assertQueryCount(8): rec1.invalidate_cache() rec2.write({'line_ids': [Command.link(line.id) for line in lines[0]]}) self.assertEqual(rec1.line_ids, lines[1:]) self.assertEqual(rec2.line_ids, lines[0]) with self.assertQueryCount(8): rec1.invalidate_cache() rec2.write({'line_ids': [Command.link(line.id) for line in lines[1:]]}) self.assertFalse(rec1.line_ids) self.assertEqual(rec2.line_ids, lines) with self.assertQueryCount(4): rec1.invalidate_cache() rec2.write({'line_ids': [Command.link(line.id) for line in lines[0]]}) self.assertEqual(rec2.line_ids, lines) with self.assertQueryCount(4): rec1.invalidate_cache() rec2.write({'line_ids': [Command.link(line.id) for line in lines[1:]]}) self.assertEqual(rec2.line_ids, lines) # empty N lines in rec2: O(1) queries with self.assertQueryCount(13): rec1.invalidate_cache() rec2.write({'line_ids': [Command.clear()]}) self.assertFalse(rec2.line_ids) with self.assertQueryCount(3): rec1.invalidate_cache() rec2.write({'line_ids': [Command.clear()]}) self.assertFalse(rec2.line_ids) rec1.write({'line_ids': [Command.create({'value': val}) for val in range(12)]}) lines = rec1.line_ids # set N lines in rec2: O(1) queries with self.assertQueryCount(8): rec1.invalidate_cache() rec2.write({'line_ids': [Command.set(lines[0].ids)]}) self.assertEqual(rec1.line_ids, lines[1:]) self.assertEqual(rec2.line_ids, lines[0]) with self.assertQueryCount(6): rec1.invalidate_cache() rec2.write({'line_ids': [Command.set(lines.ids)]}) self.assertFalse(rec1.line_ids) self.assertEqual(rec2.line_ids, lines) with self.assertQueryCount(4): rec1.invalidate_cache() rec2.write({'line_ids': [Command.set(lines.ids)]}) self.assertEqual(rec2.line_ids, lines) @mute_logger('odoo.models.unlink') def test_write_base_one2many_with_constraint(self): """ Write on one2many field with lines being deleted and created. """ rec = self.env['test_performance.base'].create({'name': 'Y'}) rec.write({'line_ids': [Command.create({'value': val}) for val in range(12)]}) # This write() will raise because of the unique index if the unlink() is # not performed before the create() rec.write({'line_ids': [Command.clear()] + [Command.create({'value': val}) for val in range(6)]}) self.assertEqual(len(rec.line_ids), 6) @mute_logger('odoo.models.unlink') @users('__system__', 'demo') @warmup def test_write_base_many2many(self): """ Write on many2many field. """ rec1 = self.env['test_performance.base'].create({'name': 'X'}) # create N tags on rec1: O(N) queries with self.assertQueryCount(4): rec1.invalidate_cache() rec1.write({'tag_ids': [Command.create({'name': 0})]}) self.assertEqual(len(rec1.tag_ids), 1) with self.assertQueryCount(14): rec1.invalidate_cache() rec1.write({'tag_ids': [Command.create({'name': val}) for val in range(1, 12)]}) self.assertEqual(len(rec1.tag_ids), 12) tags = rec1.tag_ids # update N tags: O(N) queries with self.assertQueryCount(3): rec1.invalidate_cache() rec1.write({'tag_ids': [Command.update(tag.id, {'name': 'X'}) for tag in tags[0]]}) self.assertEqual(rec1.tag_ids, tags) with self.assertQueryCount(3): rec1.invalidate_cache() rec1.write({'tag_ids': [Command.update(tag.id, {'name': 'X'}) for tag in tags[1:]]}) self.assertEqual(rec1.tag_ids, tags) # delete N tags: O(1) queries with self.assertQueryCount(__system__=8, demo=8): rec1.invalidate_cache() rec1.write({'tag_ids': [Command.delete(tag.id) for tag in tags[0]]}) self.assertEqual(rec1.tag_ids, tags[1:]) with self.assertQueryCount(__system__=8, demo=8): rec1.invalidate_cache() rec1.write({'tag_ids': [Command.delete(tag.id) for tag in tags[1:]]}) self.assertFalse(rec1.tag_ids) self.assertFalse(tags.exists()) rec1.write({'tag_ids': [Command.create({'name': val}) for val in range(12)]}) tags = rec1.tag_ids # unlink N tags: O(1) queries with self.assertQueryCount(3): rec1.invalidate_cache() rec1.write({'tag_ids': [Command.unlink(tag.id) for tag in tags[0]]}) self.assertEqual(rec1.tag_ids, tags[1:]) with self.assertQueryCount(3): rec1.invalidate_cache() rec1.write({'tag_ids': [Command.unlink(tag.id) for tag in tags[1:]]}) self.assertFalse(rec1.tag_ids) self.assertTrue(tags.exists()) rec2 = self.env['test_performance.base'].create({'name': 'X'}) # link N tags from rec1 to rec2: O(1) queries with self.assertQueryCount(3): rec1.invalidate_cache() rec2.write({'tag_ids': [Command.link(tag.id) for tag in tags[0]]}) self.assertEqual(rec2.tag_ids, tags[0]) with self.assertQueryCount(3): rec1.invalidate_cache() rec2.write({'tag_ids': [Command.link(tag.id) for tag in tags[1:]]}) self.assertEqual(rec2.tag_ids, tags) with self.assertQueryCount(2): rec1.invalidate_cache() rec2.write({'tag_ids': [Command.link(tag.id) for tag in tags[1:]]}) self.assertEqual(rec2.tag_ids, tags) # empty N tags in rec2: O(1) queries with self.assertQueryCount(3): rec1.invalidate_cache() rec2.write({'tag_ids': [Command.clear()]}) self.assertFalse(rec2.tag_ids) self.assertTrue(tags.exists()) with self.assertQueryCount(2): rec1.invalidate_cache() rec2.write({'tag_ids': [Command.clear()]}) self.assertFalse(rec2.tag_ids) # set N tags in rec2: O(1) queries with self.assertQueryCount(3): rec1.invalidate_cache() rec2.write({'tag_ids': [Command.set(tags.ids)]}) self.assertEqual(rec2.tag_ids, tags) with self.assertQueryCount(3): rec1.invalidate_cache() rec2.write({'tag_ids': [Command.set(tags[:8].ids)]}) self.assertEqual(rec2.tag_ids, tags[:8]) with self.assertQueryCount(4): rec1.invalidate_cache() rec2.write({'tag_ids': [Command.set(tags[4:].ids)]}) self.assertEqual(rec2.tag_ids, tags[4:]) with self.assertQueryCount(3): rec1.invalidate_cache() rec2.write({'tag_ids': [Command.set(tags.ids)]}) self.assertEqual(rec2.tag_ids, tags) with self.assertQueryCount(2): rec1.invalidate_cache() rec2.write({'tag_ids': [Command.set(tags.ids)]}) self.assertEqual(rec2.tag_ids, tags) @users('__system__', 'demo') @warmup def test_create_base(self): """ Create records. """ with self.assertQueryCount(__system__=2, demo=2): self.env['test_performance.base'].create({'name': 'X'}) @users('__system__', 'demo') @warmup def test_create_base_with_lines(self): """ Create records with one2many lines. """ with self.assertQueryCount(__system__=12, demo=12): self.env['test_performance.base'].create({ 'name': 'X', 'line_ids': [Command.create({'value': val}) for val in range(10)], }) @users('__system__', 'demo') @warmup def test_create_base_with_tags(self): """ Create records with many2many tags. """ with self.assertQueryCount(2): self.env['test_performance.base'].create({'name': 'X'}) # create N tags: add O(N) queries with self.assertQueryCount(13): self.env['test_performance.base'].create({ 'name': 'X', 'tag_ids': [Command.create({'name': val}) for val in range(10)], }) # link N tags: add O(1) queries tags = self.env['test_performance.tag'].create([{'name': val} for val in range(10)]) with self.assertQueryCount(3): self.env['test_performance.base'].create({ 'name': 'X', 'tag_ids': [Command.link(tag.id) for tag in tags], }) with self.assertQueryCount(2): self.env['test_performance.base'].create({ 'name': 'X', 'tag_ids': [Command.set([])], }) with self.assertQueryCount(3): self.env['test_performance.base'].create({ 'name': 'X', 'tag_ids': [Command.set(tags.ids)], }) @users('__system__', 'demo') @warmup def test_several_prefetch(self): initial_records = self.env['test_performance.base'].search([]) self.assertEqual(len(initial_records), 5) for _i in range(8): self.env.cr.execute( 'insert into test_performance_base(value) select value from test_performance_base' ) records = self.env['test_performance.base'].search([]) self.assertEqual(len(records), 1280) # should only cause 2 queries thanks to prefetching with self.assertQueryCount(__system__=2, demo=2): records.mapped('value') with self.assertQueryCount(__system__=2, demo=2): records.invalidate_cache(['value']) records.mapped('value') with self.assertQueryCount(__system__=2, demo=2): records.invalidate_cache(['value']) new_recs = records.browse(records.new(origin=record).id for record in records) new_recs.mapped('value') # clean up after each pass self.env.cr.execute( 'delete from test_performance_base where id not in %s', (tuple(initial_records.ids),) ) def expected_read_group(self): groups = defaultdict(list) all_records = self.env['test_performance.base'].search([]) for record in all_records: groups[record.partner_id.id].append(record.value) partners = self.env['res.partner'].search([('id', 'in', all_records.mapped('partner_id').ids)]) return [{ '__domain': [('partner_id', '=', partner.id)], 'partner_id': (partner.id, partner.display_name), 'partner_id_count': len(groups[partner.id]), 'value': sum(groups[partner.id]), } for partner in partners] @users('__system__', 'demo') def test_read_group_with_name_get(self): model = self.env['test_performance.base'] expected = self.expected_read_group() # use read_group and check the expected result with self.assertQueryCount(__system__=2, demo=2): model.invalidate_cache() result = model.read_group([], ['partner_id', 'value'], ['partner_id']) self.assertEqual(result, expected) @users('__system__', 'demo') def test_read_group_without_name_get(self): model = self.env['test_performance.base'] expected = self.expected_read_group() # use read_group and check the expected result with self.assertQueryCount(__system__=1, demo=1): model.invalidate_cache() result = model.read_group([], ['partner_id', 'value'], ['partner_id']) self.assertEqual(len(result), len(expected)) for res, exp in zip(result, expected): self.assertEqual(res['__domain'], exp['__domain']) self.assertEqual(res['partner_id'][0], exp['partner_id'][0]) self.assertEqual(res['partner_id_count'], exp['partner_id_count']) self.assertEqual(res['value'], exp['value']) # now serialize to json, which should force evaluation with self.assertQueryCount(__system__=1, demo=1): json.dumps(result, default=json_default) @tagged('bacon_and_eggs') class TestIrPropertyOptimizations(TransactionCase): def setUp(self): super().setUp() self.Bacon = self.env['test_performance.bacon'] self.Eggs = self.env['test_performance.eggs'] def test_with_falsy_default(self): self.assertFalse(self.env['ir.property']._get('property_eggs', 'test_performance.bacon')) # warmup eggs = self.Eggs.create({}) self.Bacon.create({}) self.Bacon.create({'property_eggs': eggs.id}) # create with default value with self.assertQueryCount(1): self.Bacon.create({}) with self.assertQueryCount(1): self.Bacon.with_context(default_property_eggs=False).create({}) with self.assertQueryCount(1): self.Bacon.create({'property_eggs': False}) # create with another value with self.assertQueryCount(3): self.Bacon.with_context(default_property_eggs=eggs.id).create({}) with self.assertQueryCount(3): self.Bacon.create({'property_eggs': eggs.id}) def test_with_truthy_default(self): eggs = self.Eggs.create({}) self.env['ir.property']._set_default("property_eggs", "test_performance.bacon", eggs) self.assertEqual(eggs, self.env['ir.property']._get('property_eggs', 'test_performance.bacon')) # warmup self.Bacon.create({}) # create with default value with self.assertQueryCount(1): self.Bacon.create({}) with self.assertQueryCount(1): self.Bacon.with_context(default_property_eggs=eggs.id).create({}) with self.assertQueryCount(1): self.Bacon.create({'property_eggs': eggs.id}) # create with another value eggs = self.Eggs.create({}) self.Bacon.create({'property_eggs': eggs.id}) with self.assertQueryCount(3): self.Bacon.with_context(default_property_eggs=eggs.id).create({}) with self.assertQueryCount(3): self.Bacon.create({'property_eggs': eggs.id}) with self.assertQueryCount(3): self.Bacon.with_context(default_property_eggs=False).create({}) with self.assertQueryCount(3): self.Bacon.create({'property_eggs': False}) @tagged('mapped_perf') class TestMapped(TransactionCase): def test_relational_mapped(self): # create 1000 records with one line each recs = self.env['test_performance.base'].create([ {'name': 'foo%d' % index, 'line_ids': [Command.create({'value': index})]} for index in range(1000) ]) recs.flush() recs.invalidate_cache() # expected same performance as recs.line_ids.mapped('value') with self.assertQueryCount(3): for rec in recs: rec.line_ids.mapped('value')
38.139785
21,282
2,140
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api, tools class BaseModel(models.Model): _name = 'test_performance.base' _description = 'Test Performance Base' name = fields.Char() value = fields.Integer(default=0) value_pc = fields.Float(compute="_value_pc", store=True) value_ctx = fields.Float(compute="_value_ctx") partner_id = fields.Many2one('res.partner', string='Customer') line_ids = fields.One2many('test_performance.line', 'base_id') total = fields.Integer(compute="_total", store=True) tag_ids = fields.Many2many('test_performance.tag') @api.depends('value') def _value_pc(self): for record in self: record.value_pc = float(record.value) / 100 @api.depends_context('key') def _value_ctx(self): self.env.cr.execute('SELECT 42') # one dummy query per batch for record in self: record.value_ctx = self.env.context.get('key') @api.depends('line_ids.value') def _total(self): for record in self: record.total = sum(line.value for line in record.line_ids) class LineModel(models.Model): _name = 'test_performance.line' _description = 'Test Performance Line' base_id = fields.Many2one('test_performance.base', required=True, ondelete='cascade') value = fields.Integer() def init(self): # line values should be unique per "base" - useful for testing corner cases with unique lines tools.create_unique_index(self._cr, 'test_performance_line_uniq', self._table, ['base_id', 'value']) class TagModel(models.Model): _name = 'test_performance.tag' _description = 'Test Performance Tag' name = fields.Char() class Bacon(models.Model): _name = 'test_performance.bacon' _description = 'Test Performance Bacon' property_eggs = fields.Many2one( 'test_performance.eggs', company_dependent=True, string='Eggs') class Eggs(models.Model): _name = 'test_performance.eggs' _description = 'Test Performance Eggs' name = fields.Char()
31.014493
2,140
227
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields # We add a field on this model class Unit(models.Model): _inherit = 'test.unit' second_name = fields.Char()
22.7
227
400
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'test-inherits-depends', 'version': '0.1', 'category': 'Hidden/Tests', 'description': """A module to verify the inheritance using _inherits in non-original modules.""", 'depends': ['test_inherits'], 'data': [], 'installable': True, 'auto_install': False, 'license': 'LGPL-3', }
30.769231
400
1,226
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common class test_inherits(common.TransactionCase): def test_ir_model_data_inherits_again(self): """ Re-run test_inherits test to make sure another imd hasn't been created """ IrModelData = self.env['ir.model.data'] field = IrModelData.search([('name', '=', 'field_test_unit__name')]) self.assertEqual(len(field), 1) self.assertEqual(field.module, 'test_inherits') field = IrModelData.search([('name', '=', 'field_test_box__name')]) self.assertEqual(len(field), 1) self.assertEqual(field.module, 'test_inherits') def test_ir_model_data_inherits_depends(self): """ Check the existence of the correct ir.model.data """ IrModelData = self.env['ir.model.data'] field = IrModelData.search([('name', '=', 'field_test_unit__second_name')]) self.assertEqual(len(field), 1) self.assertEqual(field.module, 'test_inherits_depends') field = IrModelData.search([('name', '=', 'field_test_box__second_name')]) self.assertEqual(len(field), 1) self.assertEqual(field.module, 'test_inherits_depends')
42.275862
1,226
4,648
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api # We create a new model class mother(models.Model): _name = 'test.inherit.mother' _description = 'Test Inherit Mother' name = fields.Char(default='Foo') state = fields.Selection([('a', 'A'), ('b', 'B')], default='a') surname = fields.Char(compute='_compute_surname') @api.depends('name') def _compute_surname(self): for rec in self: rec.surname = rec.name or '' # We inherit from the parent model, and we add some fields in the child model class daughter(models.Model): _name = 'test.inherit.daughter' _description = 'Test Inherit Daughter' template_id = fields.Many2one('test.inherit.mother', 'Template', delegate=True, required=True, ondelete='cascade') field_in_daughter = fields.Char('Field1') # We add a new field in the parent model. Because of a recent refactoring, this # feature was broken. These models rely on that feature. class mother2(models.Model): _inherit = 'test.inherit.mother' field_in_mother = fields.Char() partner_id = fields.Many2one('res.partner') # extend the name field: make it required and change its default value name = fields.Char(required=True, default='Bar') # extend the selection of the state field, and discard its default value state = fields.Selection(selection_add=[('c', 'C')], default=None) # override the computed field, and extend its dependencies @api.depends('field_in_mother') def _compute_surname(self): for rec in self: if rec.field_in_mother: rec.surname = rec.field_in_mother else: super(mother, rec)._compute_surname() class mother3(models.Model): _inherit = 'test.inherit.mother' # extend again the selection of the state field: 'd' must precede 'b' state = fields.Selection(selection_add=[('d', 'D'), ('b',)]) class daughter2(models.Model): _inherit = 'test.inherit.daughter' # simply redeclare the field without adding any option template_id = fields.Many2one() # change the default value of an inherited field name = fields.Char(default='Baz') class res_partner(models.Model): _inherit = 'res.partner' # define a one2many field based on the inherited field partner_id daughter_ids = fields.One2many('test.inherit.daughter', 'partner_id') # Check the overriding of property fields by non-property fields. # Contribution by Adrien Peiffer (ACSONE). class test_inherit_property(models.Model): _name = 'test.inherit.property' _description = 'Test Inherit Property' name = fields.Char('Name', required=True) property_foo = fields.Integer(string='Foo', company_dependent=True) property_bar = fields.Integer(string='Bar', company_dependent=True) class test_inherit_property2(models.Model): _inherit = 'test.inherit.property' # override property_foo with a plain normal field property_foo = fields.Integer(company_dependent=False) # override property_bar with a new-api computed field property_bar = fields.Integer(compute='_compute_bar', company_dependent=False) def _compute_bar(self): for record in self: record.property_bar = 42 # # Extend a parent model after is has been inherited in a child model # class Parent1(models.AbstractModel): _name = 'test.inherit.parent' _description = 'Test Inherit Parent' def stuff(self): return 'P1' class Child(models.AbstractModel): _name = 'test.inherit.child' _inherit = 'test.inherit.parent' _description = 'Test Inherit Child' bar = fields.Integer() def stuff(self): return super(Child, self).stuff() + 'C1' class Parent2(models.AbstractModel): _inherit = 'test.inherit.parent' foo = fields.Integer() _sql_constraints = [('unique_foo', 'UNIQUE(foo)', 'foo must be unique')] def stuff(self): return super(Parent2, self).stuff() + 'P2' @api.constrains('foo') def _check_foo(self): pass # # Extend a selection field # class Selection(models.Model): _inherit = 'test_new_api.selection' state = fields.Selection(selection_add=[('bar', 'Bar'), ('baz', 'Baz')]) other = fields.Selection('_other_values') def _other_values(self): return [('baz', 'Baz')] # # Helper model used in test_inherit_depends # class IsPublishedMixin(models.AbstractModel): _name = 'test_inherit.mixin' _description = "Test Inherit Mixin" published = fields.Boolean()
28.869565
4,648
367
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'test-inherit', 'version': '0.1', 'category': 'Hidden/Tests', 'description': """A module to verify the inheritance.""", 'depends': ['base', 'test_new_api'], 'data': [ 'ir.model.access.csv', 'demo_data.xml', ], 'installable': True, 'auto_install': False, 'license': 'LGPL-3', }
24.466667
367
8,031
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.base.tests.common import TransactionCaseWithUserDemo from odoo.tests import common class test_inherits(common.TransactionCase): def test_00_inherits(self): """ Check that a many2one field with delegate=True adds an entry in _inherits """ daughter = self.env['test.inherit.daughter'] self.assertEqual(daughter._inherits, {'test.inherit.mother': 'template_id'}) # the field supporting the inheritance should be auto_join field = daughter._fields['template_id'] self.assertTrue(field.delegate) self.assertTrue(field.auto_join, "delegate fields should be auto_join") def test_10_access_from_child_to_parent_model(self): """ check whether added field in model is accessible from children models (_inherits) """ # This test checks if the new added column of a parent model # is accessible from the child model. This test has been written # to verify the purpose of the inheritance computing of the class # in the openerp.osv.orm._build_model. mother = self.env['test.inherit.mother'] daughter = self.env['test.inherit.daughter'] self.assertIn('field_in_mother', mother._fields) self.assertIn('field_in_mother', daughter._fields) def test_20_field_extension(self): """ check the extension of a field in an inherited model """ mother = self.env['test.inherit.mother'] daughter = self.env['test.inherit.daughter'] # the field mother.name must have required=True and "Bar" as default field = mother._fields['name'] self.assertTrue(field.required) self.assertEqual(field.default(mother), "Bar") self.assertEqual(mother.default_get(['name']), {'name': "Bar"}) # the field daughter.name must have required=False and "Baz" as default field = daughter._fields['name'] self.assertFalse(field.required) self.assertEqual(field.default(daughter), "Baz") self.assertEqual(daughter.default_get(['name']), {'name': "Baz"}) # the field mother.state must have no default value field = mother._fields['state'] self.assertFalse(field.default) self.assertEqual(mother.default_get(['state']), {}) # the field daughter.template_id should have # comodel_name='test.inherit.mother', string='Template', required=True field = daughter._fields['template_id'] self.assertEqual(field.comodel_name, 'test.inherit.mother') self.assertEqual(field.string, "Template") self.assertTrue(field.required) def test_30_depends_extension(self): """ check that @depends on overridden compute methods extends dependencies """ mother = self.env['test.inherit.mother'] field = mother._fields['surname'] # the field dependencies are added self.assertItemsEqual(self.registry.field_depends[field], ['name', 'field_in_mother']) def test_40_selection_extension(self): """ check that attribute selection_add=... extends selection on fields. """ mother = self.env['test.inherit.mother'] # the extra values are added, both in the field and the column self.assertEqual(mother._fields['state'].selection, [('a', 'A'), ('d', 'D'), ('b', 'B'), ('c', 'C')]) def test_41_selection_extension(self): """ check that attribute selection_add=... extends selection on fields. """ model = self.env['test_new_api.selection'] field = model._fields['other'] self.assertIsInstance(field.selection, str) self.assertEqual(field._description_selection(self.env), [('baz', 'Baz')]) class test_inherits_demo(TransactionCaseWithUserDemo): def test_50_search_one2many(self): """ check search on one2many field based on inherited many2one field. """ # create a daughter record attached to partner Demo partner_demo = self.partner_demo daughter = self.env['test.inherit.daughter'].create({'partner_id': partner_demo.id}) self.assertEqual(daughter.partner_id, partner_demo) self.assertIn(daughter, partner_demo.daughter_ids) # search the partner from the daughter record partners = self.env['res.partner'].search([('daughter_ids', 'like', 'not existing daugther')]) self.assertFalse(partners) partners = self.env['res.partner'].search([('daughter_ids', 'not like', 'not existing daugther')]) self.assertIn(partner_demo, partners) partners = self.env['res.partner'].search([('daughter_ids', '!=', False)]) self.assertIn(partner_demo, partners) partners = self.env['res.partner'].search([('daughter_ids', 'in', daughter.ids)]) self.assertIn(partner_demo, partners) class test_override_property(common.TransactionCase): def test_override_with_normal_field(self): """ test overriding a property field by a function field """ record = self.env['test.inherit.property'].create({'name': "Stuff"}) # record.property_foo is not a property field self.assertFalse(record.property_foo) self.assertFalse(type(record).property_foo.company_dependent) self.assertTrue(type(record).property_foo.store) def test_override_with_computed_field(self): """ test overriding a property field by a computed field """ record = self.env['test.inherit.property'].create({'name': "Stuff"}) # record.property_bar is not a property field self.assertEqual(record.property_bar, 42) self.assertFalse(type(record).property_bar.company_dependent) class TestInherit(common.TransactionCase): def test_extend_parent(self): """ test whether a model extension is visible in its children models. """ parent = self.env['test.inherit.parent'] child = self.env['test.inherit.child'] # check fields self.assertIn('foo', parent.fields_get()) self.assertNotIn('bar', parent.fields_get()) self.assertIn('foo', child.fields_get()) self.assertIn('bar', child.fields_get()) # check method overriding self.assertEqual(parent.stuff(), 'P1P2') self.assertEqual(child.stuff(), 'P1P2C1') # check inferred model attributes self.assertEqual(parent._table, 'test_inherit_parent') self.assertEqual(child._table, 'test_inherit_child') self.assertEqual(len(parent._sql_constraints), 1) self.assertEqual(len(child._sql_constraints), 1) # check properties memoized on model self.assertEqual(len(parent._constraint_methods), 1) self.assertEqual(len(child._constraint_methods), 1) class TestXMLIDS(common.TransactionCase): def test_xml_ids(self): """ check XML ids of selection fields. """ field = self.env['test_new_api.selection']._fields['state'] self.assertEqual(field.selection, [('foo', 'Foo'), ('bar', 'Bar'), ('baz', 'Baz')]) ir_field = self.env['ir.model.fields']._get('test_new_api.selection', 'state') xml_ids = ir_field._get_external_ids() self.assertCountEqual(xml_ids.get(ir_field.id), [ 'test_new_api.field_test_new_api_selection__state', 'test_inherit.field_test_new_api_selection__state', ]) foo, bar, baz = ir_field.selection_ids xml_ids = (foo + bar + baz)._get_external_ids() self.assertCountEqual(xml_ids.get(foo.id), [ 'test_new_api.selection__test_new_api_selection__state__foo', ]) self.assertCountEqual(xml_ids.get(bar.id), [ 'test_new_api.selection__test_new_api_selection__state__bar', 'test_inherit.selection__test_new_api_selection__state__bar', ]) self.assertCountEqual(xml_ids.get(baz.id), [ 'test_inherit.selection__test_new_api_selection__state__baz', ])
45.630682
8,031
1,691
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api, SUPERUSER_ID class test_model(models.Model): _name = 'test_converter.test_model' _description = 'Test Converter Model' char = fields.Char() integer = fields.Integer() float = fields.Float() numeric = fields.Float(digits=(16, 2)) many2one = fields.Many2one('test_converter.test_model.sub', group_expand='_gbf_m2o') binary = fields.Binary(attachment=False) date = fields.Date() datetime = fields.Datetime() selection_str = fields.Selection([ ('A', u"Qu'il n'est pas arrivé à Toronto"), ('B', u"Qu'il était supposé arriver à Toronto"), ('C', u"Qu'est-ce qu'il fout ce maudit pancake, tabernacle ?"), ('D', u"La réponse D"), ], string=u"Lorsqu'un pancake prend l'avion à destination de Toronto et " u"qu'il fait une escale technique à St Claude, on dit:") html = fields.Html() text = fields.Text() # `base` module does not contains any model that implement the functionality # `group_expand`; test this feature here... @api.model def _gbf_m2o(self, subs, domain, order): sub_ids = subs._search([], order=order, access_rights_uid=SUPERUSER_ID) return subs.browse(sub_ids) class test_model_sub(models.Model): _name = 'test_converter.test_model.sub' _description = 'Subtraction For Test Model & Test Converter' name = fields.Char() class test_model_monetary(models.Model): _name = 'test_converter.monetary' _description = 'Test Converter Monetary' value = fields.Float(digits=(16, 55))
36.586957
1,683
417
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'test-field-converter', 'version': '0.1', 'category': 'Hidden/Tests', 'description': """Tests of field conversions""", 'maintainer': 'OpenERP SA', 'depends': ['base'], 'data': ['ir.model.access.csv'], 'installable': True, 'auto_install': False, 'license': 'LGPL-3', }
29.785714
417
12,128
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 import datetime import os import re from odoo.tests import common from odoo.tools import html_escape as e directory = os.path.dirname(__file__) class TestExport(common.TransactionCase): _model = None def setUp(self): super(TestExport, self).setUp() self.Model = self.env[self._model] def get_field(self, name): return self.Model._fields[name] def get_converter(self, name, type=None): field = self.get_field(name) for postfix in (type, field.type, ''): fs = ['ir', 'qweb', 'field'] if postfix is None: continue if postfix: fs.append(postfix) try: model = self.env['.'.join(fs)] break except KeyError: pass def converter(value, options=None, context=None): context = context or {} record = self.Model.with_context(context).new({name: value}) # normalise non-newline spaces: some versions of babel use regular # spaces while others use non-break space when formatting timedeltas # to the french locale return re.sub( r'[^\S\n\r]', # no \p{Zs} ' ', model.with_context(context).record_to_html(record, name, options or {}) ) return converter class TestBasicExport(TestExport): _model = 'test_converter.test_model' class TestCharExport(TestBasicExport): def test_char(self): converter = self.get_converter('char') value = converter('foo') self.assertEqual(value, 'foo') value = converter("foo<bar>") self.assertEqual(value, "foo&lt;bar&gt;") class TestIntegerExport(TestBasicExport): def test_integer(self): converter = self.get_converter('integer') value = converter(42) self.assertEqual(value, "42") class TestFloatExport(TestBasicExport): def setUp(self): super(TestFloatExport, self).setUp() self.env['res.lang'].browse(1).write({'grouping': '[3,0]'}) def test_float(self): converter = self.get_converter('float') value = converter(-42.0) self.assertEqual(value, u"-\N{ZERO WIDTH NO-BREAK SPACE}42.0") value = converter(42.0100) self.assertEqual(value, "42.01") value = converter(42.01234) self.assertEqual(value, "42.01234") value = converter(1234567.89) self.assertEqual(value, '1,234,567.89') def test_numeric(self): converter = self.get_converter('numeric') value = converter(42.0) self.assertEqual(value, '42.00') value = converter(42.01234) self.assertEqual(value, '42.01') class TestCurrencyExport(TestExport): _model = 'test_converter.monetary' def setUp(self): super(TestCurrencyExport, self).setUp() self.Currency = self.env['res.currency'] self.base = self.create(self.Currency, name="Source", symbol=u'source') def create(self, model, **values): return model.create(values) def convert(self, obj, dest): converter = self.env['ir.qweb.field.monetary'] options = { 'widget': 'monetary', 'display_currency': dest, } return converter.record_to_html(obj, 'value', options) def test_currency_post(self): currency = self.create(self.Currency, name="Test", symbol=u"test") obj = self.create(self.Model, value=-0.12) converted = self.convert(obj, dest=currency) self.assertEqual( converted, u'<span class="oe_currency_value">-\N{ZERO WIDTH NO-BREAK SPACE}0.12</span>' u'\N{NO-BREAK SPACE}{symbol}'.format( obj=obj, symbol=currency.symbol ),) def test_currency_pre(self): currency = self.create( self.Currency, name="Test", symbol=u"test", position='before') obj = self.create(self.Model, value=0.12) converted = self.convert(obj, dest=currency) self.assertEqual( converted, u'{symbol}\N{NO-BREAK SPACE}' u'<span class="oe_currency_value">0.12</span>'.format( obj=obj, symbol=currency.symbol ),) def test_currency_precision(self): """ Precision should be the currency's, not the float field's """ currency = self.create(self.Currency, name="Test", symbol=u"test",) obj = self.create(self.Model, value=0.1234567) converted = self.convert(obj, dest=currency) self.assertEqual( converted, u'<span class="oe_currency_value">0.12</span>' u'\N{NO-BREAK SPACE}{symbol}'.format( obj=obj, symbol=currency.symbol ),) class TestTextExport(TestBasicExport): maxDiff = None def test_text(self): converter = self.get_converter('text') value = converter("This is my text-kai") self.assertEqual(value, "This is my text-kai") value = converter(""" . The current line (address) in the buffer. $ The last line in the buffer. n The nth, line in the buffer where n is a number in the range [0,$]. $ The last line in the buffer. - The previous line. This is equivalent to -1 and may be repeated with cumulative effect. -n The nth previous line, where n is a non-negative number. + The next line. This is equivalent to +1 and may be repeated with cumulative effect. """) self.assertEqual(value, """<br> . The current line (address) in the buffer.<br> $ The last line in the buffer.<br> n The nth, line in the buffer where n is a number in the range [0,$].<br> $ The last line in the buffer.<br> - The previous line. This is equivalent to -1 and may be repeated with cumulative effect.<br> -n The nth previous line, where n is a non-negative number.<br> + The next line. This is equivalent to +1 and may be repeated with cumulative effect.<br> """) value = converter(""" fgdkls;hjas;lj <b>fdslkj</b> d;lasjfa lkdja <a href=http://spam.com>lfks</a> fldkjsfhs <i style="color: red"><a href="http://spamspam.com">fldskjh</a></i> """) self.assertEqual(value, """<br> fgdkls;hjas;lj &lt;b&gt;fdslkj&lt;/b&gt; d;lasjfa lkdja &lt;a href=http://spam.com&gt;lfks&lt;/a&gt;<br> fldkjsfhs &lt;i style=&#34;color: red&#34;&gt;&lt;a href=&#34;http://spamspam.com&#34;&gt;fldskjh&lt;/a&gt;&lt;/i&gt;<br> """) class TestMany2OneExport(TestBasicExport): def test_many2one(self): Sub = self.env['test_converter.test_model.sub'] converter = self.get_converter('many2one') value = converter(Sub.create({'name': "Foo"}).id) self.assertEqual(value, "Foo") value = converter(Sub.create({'name': "Fo<b>o</b>"}).id) self.assertEqual(value, "Fo&lt;b&gt;o&lt;/b&gt;") class TestBinaryExport(TestBasicExport): def test_image(self): converter = self.env['ir.qweb.field.image'] with open(os.path.join(directory, 'test_vectors', 'image'), 'rb') as f: content = f.read() encoded_content = base64.b64encode(content) value = converter.value_to_html(encoded_content, {}) self.assertEqual( value, u'<img src="data:image/jpeg;base64,%s">' % encoded_content.decode('ascii')) with open(os.path.join(directory, 'test_vectors', 'pdf'), 'rb') as f: content = f.read() with self.assertRaises(ValueError): converter.value_to_html(base64.b64encode(content), {}) with open(os.path.join(directory, 'test_vectors', 'pptx'), 'rb') as f: content = f.read() with self.assertRaises(ValueError): converter.value_to_html(base64.b64encode(content), {}) class TestSelectionExport(TestBasicExport): def test_selection(self): converter = self.get_converter('selection_str') value = converter('C') self.assertEqual(value, u"Qu&#39;est-ce qu&#39;il fout ce maudit pancake, tabernacle ?") class TestHTMLExport(TestBasicExport): def test_html(self): converter = self.get_converter('html') input = '<span>span</span>' value = converter(input) self.assertEqual(value, input) class TestDatetimeExport(TestBasicExport): def setUp(self): super(TestDatetimeExport, self).setUp() # set user tz to known value self.env.user.write({'tz': 'Pacific/Niue'}) def test_date(self): converter = self.get_converter('date') value = converter('2011-05-03') # default lang/format is US self.assertEqual(value, '05/03/2011') def test_datetime(self): converter = self.get_converter('datetime') value = converter('2011-05-03 11:12:13') # default lang/format is US self.assertEqual(value, '05/03/2011 00:12:13') def test_custom_format(self): converter = self.get_converter('datetime') converter2 = self.get_converter('date') opts = {'format': 'MMMM d'} value = converter('2011-03-02 11:12:13', options=opts) value2 = converter2('2001-03-02', options=opts) self.assertEqual( value, 'March 2' ) self.assertEqual( value2, 'March 2' ) class TestDurationExport(TestBasicExport): def setUp(self): super(TestDurationExport, self).setUp() # needs to have lang installed otherwise falls back on en_US self.env['res.lang']._activate_lang('fr_FR') def test_default_unit(self): converter = self.get_converter('float', 'duration') self.assertEqual(converter(4), u'4 seconds') def test_negative(self): converter = self.get_converter('float', 'duration') self.assertEqual(converter(-4), u'- 4 seconds') def test_negative_with_round(self): converter = self.get_converter('float', 'duration') result = converter(-4.678, {'unit': 'year', 'round': 'hour'}, {'lang': 'fr_FR'}) self.assertEqual(result, u'- 4 ans 8 mois 1 semaine 11 heures') def test_basic(self): converter = self.get_converter('float', 'duration') result = converter(4, {'unit': 'hour'}, {'lang': 'fr_FR'}) self.assertEqual(result, u'4 heures') result = converter(50, {'unit': 'second'}, {'lang': 'fr_FR'}) self.assertEqual(result, u'50 secondes') def test_multiple(self): converter = self.get_converter('float', 'duration') result = converter(1.5, {'unit': 'hour'}, {'lang': 'fr_FR'}) self.assertEqual(result, u"1 heure 30 minutes") result = converter(72, {'unit': 'second'}, {'lang': 'fr_FR'}) self.assertEqual(result, u"1 minute 12 secondes") def test_negative_digital(self): converter = self.get_converter('float', 'duration') result = converter(-90, {'unit': 'minute', 'round': 'minute', 'digital': True}, {'lang': 'fr_FR'}) self.assertEqual(result, u'-01:30') class TestRelativeDatetime(TestBasicExport): # not sure how a test based on "current time" should be tested. Even less # so as it would mostly be a test of babel... def setUp(self): super(TestRelativeDatetime, self).setUp() # needs to have lang installed otherwise falls back on en_US self.env['res.lang']._activate_lang('fr_FR') def test_basic(self): converter = self.get_converter('datetime', 'relative') t = datetime.datetime.utcnow() - datetime.timedelta(hours=1) result = converter(t, context={'lang': 'fr_FR'}) self.assertEqual(result, u"il y a 1 heure")
34.067416
12,128
865
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common class TestGBF(common.TransactionCase): def test_group_by_full(self): Sub = self.env['test_converter.test_model.sub'] TM = self.env['test_converter.test_model'] # remove all existing subs (no need to panic, it will be rollbacked...) Sub.search([]).unlink() subs_ids = [Sub.create({'name': 'sub%d' % i}).id for i in range(5)] tm_ids = [TM.create({'many2one': subs_ids[i]}).id for i in range(3)] domain = [('id', 'in', tuple(tm_ids))] rg = TM.read_group(domain, fields=['many2one'], groupby=['many2one']) self.assertEqual(len(rg), len(subs_ids)) rg_subs = sorted(g['many2one'][0] for g in rg) self.assertListEqual(rg_subs, sorted(subs_ids))
39.318182
865
2,290
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'test-assetsbundle', 'version': '0.1', 'category': 'Hidden/Tests', 'description': """A module to verify the Assets Bundle mechanism.""", 'maintainer': 'Odoo SA', 'depends': ['base'], 'installable': True, 'data': [ "data/ir_asset.xml", "views/views.xml", ], 'auto_install': False, 'assets': { 'test_assetsbundle.bundle2': [ 'test_assetsbundle/static/src/css/test_cssfile1.css', ], 'test_assetsbundle.bundle3': [ 'test_assetsbundle/static/src/scss/test_file1.scss', ], 'test_assetsbundle.bundle4': [ 'test_assetsbundle/static/src/js/test_jsfile1.js', 'test_assetsbundle/static/src/js/test_jsfile2.js', 'http://test.external.link/javascript1.js', 'test_assetsbundle/static/src/css/test_cssfile1.css', 'http://test.external.link/style1.css', 'test_assetsbundle/static/src/css/test_cssfile2.css', 'test_assetsbundle/static/src/js/test_jsfile3.js', 'http://test.external.link/javascript2.js', 'http://test.external.link/style2.css', ], 'test_assetsbundle.manifest1': [ 'test_assetsbundle/static/src/*/**', ], 'test_assetsbundle.manifest2': [ 'test_assetsbundle/static/src/js/test_jsfile1.js', 'test_assetsbundle/static/src/*/**', ], 'test_assetsbundle.manifest3': [ 'test_assetsbundle/static/src/js/test_jsfile3.js', 'test_assetsbundle/static/src/*/**', ], 'test_assetsbundle.manifest4': [ 'test_assetsbundle/static/src/js/test_jsfile3.js', ], 'test_assetsbundle.manifest5': [ 'test_assetsbundle/static/src/js/test_jsfile1.js', 'test_assetsbundle/static/src/js/test_jsfile2.js', 'test_assetsbundle/static/src/js/test_jsfile3.js', 'test_assetsbundle/static/src/js/test_jsfile4.js', ], 'test_assetsbundle.manifest6': [ ('include', 'test_assetsbundle.manifest4'), ], 'test_assetsbundle.manifest_multi_module1': [], }, 'license': 'LGPL-3', }
36.349206
2,290
80,378
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import Counter from lxml import etree import os import time from unittest import skip from unittest.mock import patch import textwrap import pathlib import lxml import base64 from odoo import api, http from odoo.addons import __path__ as ADDONS_PATH from odoo.addons.base.models.assetsbundle import AssetsBundle from odoo.addons.base.models.ir_asset import AssetPaths from odoo.addons.base.models.ir_attachment import IrAttachment from odoo.modules.module import get_resource_path, read_manifest from odoo.tests import HttpCase, tagged from odoo.tests.common import TransactionCase from odoo.addons.base.models.qweb import QWebException from odoo.tools import mute_logger, func GETMTINE = os.path.getmtime class TestAddonPaths(TransactionCase): def test_operations(self): asset_paths = AssetPaths() self.assertFalse(asset_paths.list) asset_paths.append(['a', 'c', 'd'], 'module1', 'bundle1') self.assertEqual(asset_paths.list, [ ('a', 'module1', 'bundle1'), ('c', 'module1', 'bundle1'), ('d', 'module1', 'bundle1'), ]) # append with a duplicate of 'c' asset_paths.append(['c', 'f'], 'module2', 'bundle2') self.assertEqual(asset_paths.list, [ ('a', 'module1', 'bundle1'), ('c', 'module1', 'bundle1'), ('d', 'module1', 'bundle1'), ('f', 'module2', 'bundle2'), ]) # insert with a duplicate of 'c' after 'c' asset_paths.insert(['c', 'e'], 'module3', 'bundle3', 3) self.assertEqual(asset_paths.list, [ ('a', 'module1', 'bundle1'), ('c', 'module1', 'bundle1'), ('d', 'module1', 'bundle1'), ('e', 'module3', 'bundle3'), ('f', 'module2', 'bundle2'), ]) # insert with a duplicate of 'd' before 'd' asset_paths.insert(['b', 'd'], 'module4', 'bundle4', 1) self.assertEqual(asset_paths.list, [ ('a', 'module1', 'bundle1'), ('b', 'module4', 'bundle4'), ('c', 'module1', 'bundle1'), ('d', 'module1', 'bundle1'), ('e', 'module3', 'bundle3'), ('f', 'module2', 'bundle2'), ]) # remove asset_paths.remove(['c', 'd', 'g'], 'module5', 'bundle5') self.assertEqual(asset_paths.list, [ ('a', 'module1', 'bundle1'), ('b', 'module4', 'bundle4'), ('e', 'module3', 'bundle3'), ('f', 'module2', 'bundle2'), ]) class AddonManifestPatched(TransactionCase): test_assetsbundle_manifest = None for path in ADDONS_PATH: manifest = read_manifest(path, 'test_assetsbundle') if manifest: manifest['addons_path'] = path test_assetsbundle_manifest = manifest break def tearDown(self): super().tearDown() self.env.registry._init_modules = self.__genuine_registry_modules http.addons_manifest = self.__genuine_addons_manifest def setUp(self): super().setUp() self.__genuine_registry_modules = self.env.registry._init_modules self.env.registry._init_modules = func.lazy(lambda: set(self.installed_modules)) self.__genuine_addons_manifest = http.addons_manifest http.addons_manifest = func.lazy(lambda: self.manifests) self.installed_modules = ['base', 'test_assetsbundle'] self.manifests = { 'test_assetsbundle': self.test_assetsbundle_manifest, } class FileTouchable(AddonManifestPatched): def setUp(self): super(FileTouchable, self).setUp() self.touches = {} def _touch(self, filepath, touch_time=None): self.touches[filepath] = touch_time or time.time() return patch('os.path.getmtime', lambda filename: self.touches.get(filename) or GETMTINE(filename)) class TestJavascriptAssetsBundle(FileTouchable): def setUp(self): super(TestJavascriptAssetsBundle, self).setUp() self.jsbundle_name = 'test_assetsbundle.bundle1' self.cssbundle_name = 'test_assetsbundle.bundle2' self.env['res.lang']._activate_lang('ar_SY') def _get_asset(self, bundle, env=None): env = (env or self.env) files, _ = env['ir.qweb']._get_asset_content(bundle) return AssetsBundle(bundle, files, env=env) def _any_ira_for_bundle(self, extension, lang=None): """ Returns all ir.attachments associated to a bundle, regardless of the verion. """ user_direction = self.env['res.lang']._lang_get(lang or self.env.user.lang).direction bundle = self.jsbundle_name if extension in ['js', 'min.js'] else self.cssbundle_name rtl = 'rtl/' if extension in ['css', 'min.css'] and user_direction == 'rtl' else '' url = f'/web/assets/%-%/{rtl}{bundle}.{extension}' domain = [('url', '=like', url)] return self.env['ir.attachment'].search(domain) def _node_to_list(self, nodes): res = [] for index, (tagName, t_attrs, content) in enumerate(nodes): for name, value in t_attrs.items(): res.append(value) return res def test_01_generation(self): """ Checks that a bundle creates an ir.attachment record when its `js` method is called for the first time and this ir.attachment is different depending on `is_minified` param. """ self.bundle = self._get_asset(self.jsbundle_name, env=self.env) # there shouldn't be any minified attachment associated to this bundle self.assertEqual(len(self._any_ira_for_bundle('min.js')), 0, "there shouldn't be any minified attachment associated to this bundle") self.assertEqual(len(self.bundle.get_attachments('min.js')), 0, "there shouldn't be any minified attachment associated to this bundle") # trigger the first generation and, thus, the first save in database self.bundle.js() # there should be one minified attachment associated to this bundle self.assertEqual(len(self._any_ira_for_bundle('min.js')), 1, "there should be one minified attachment associated to this bundle") self.assertEqual(len(self.bundle.get_attachments('min.js')), 1, "there should be one minified attachment associated to this bundle") # there shouldn't be any non-minified attachment associated to this bundle self.assertEqual(len(self._any_ira_for_bundle('js')), 0, "there shouldn't be any non-minified attachment associated to this bundle") self.assertEqual(len(self.bundle.get_attachments('js')), 0, "there shouldn't be any non-minified attachment associated to this bundle") # trigger the first generation and, thus, the first save in database for the non-minified version. self.bundle.js(is_minified=False) # there should be one non-minified attachment associated to this bundle self.assertEqual(len(self._any_ira_for_bundle('js')), 1, "there should be one non-minified attachment associated to this bundle") self.assertEqual(len(self.bundle.get_attachments('js')), 1, "there should be one non-minified attachment associated to this bundle") def test_02_access(self): """ Checks that the bundle's cache is working, i.e. that the bundle creates only one ir.attachment record when rendered multiple times. """ bundle0 = self._get_asset(self.jsbundle_name) bundle0.js() self.assertEqual(len(self._any_ira_for_bundle('min.js')), 1, "there should be one minified attachment associated to this bundle") version0 = bundle0.version ira0 = self._any_ira_for_bundle('min.js') date0 = ira0.create_date bundle1 = self._get_asset(self.jsbundle_name) bundle1.js() self.assertEqual(len(self._any_ira_for_bundle('min.js')), 1, "there should be one minified attachment associated to this bundle") version1 = bundle1.version ira1 = self._any_ira_for_bundle('min.js') date1 = ira1.create_date self.assertEqual(version0, version1, "the version should not be changed because the bundle hasn't changed") self.assertEqual(date0, date1, "the date of creation of the ir.attachment should not change because the bundle is unchanged") def test_03_date_invalidation(self): """ Checks that a bundle is invalidated when one of its assets' modification date is changed. """ bundle0 = self._get_asset(self.jsbundle_name) bundle0.js() last_modified0 = bundle0.last_modified version0 = bundle0.version path = get_resource_path('test_assetsbundle', 'static', 'src', 'js', 'test_jsfile1.js') bundle1 = self._get_asset(self.jsbundle_name) with self._touch(path): bundle1.js() last_modified1 = bundle1.last_modified version1 = bundle1.version self.assertNotEqual(last_modified0, last_modified1, "the creation date of the ir.attachment should change because the bundle has changed.") self.assertNotEqual(version0, version1, "the version must should because the bundle has changed.") # check if the previous attachment is correctly cleaned self.assertEqual(len(self._any_ira_for_bundle('min.js')), 1, "there should be one minified attachment associated to this bundle") def test_04_content_invalidation(self): """ Checks that a bundle is invalidated when its content is modified by adding a file to source. """ bundle0 = self._get_asset(self.jsbundle_name) bundle0.js() files0 = bundle0.files version0 = bundle0.version self.assertEqual(len(self._any_ira_for_bundle('min.js')), 1, "there should be one minified attachment associated to this bundle") self.env['ir.asset'].create({ 'name': 'test bundle inheritance', 'bundle': self.jsbundle_name, 'path': 'test_assetsbundle/static/src/js/test_jsfile4.js', }) bundle1 = self._get_asset(self.jsbundle_name) bundle1.js() files1 = bundle1.files version1 = bundle1.version self.assertNotEqual(files0, files1, "the list of files should be different because a file has been added to the bundle") self.assertNotEqual(version0, version1, "the version should be different because a file has been added to the bundle") # check if the previous attachment are correctly cleaned self.assertEqual(len(self._any_ira_for_bundle('min.js')), 1, "there should be one minified attachment associated to this bundle") def test_05_normal_mode(self): """ Checks that a bundle rendered in normal mode outputs minified assets and create a minified ir.attachment. """ debug_bundle = self._get_asset(self.jsbundle_name) nodes = debug_bundle.to_node() content = self._node_to_list(nodes) # there should be a minified file self.assertEqual(content[3].count('test_assetsbundle.bundle1.min.js'), 1) # there should be one minified assets created in normal mode self.assertEqual(len(self._any_ira_for_bundle('min.js')), 1, "there should be one minified assets created in normal mode") # there shouldn't be any non-minified assets created in normal mode self.assertEqual(len(self._any_ira_for_bundle('js')), 0, "there shouldn't be any non-minified assets created in normal mode") def test_06_debug(self): """ Checks that a bundle rendered in debug 1 mode outputs non-minified assets and create an non-minified ir.attachment. """ debug_bundle = self._get_asset(self.jsbundle_name) nodes = debug_bundle.to_node(debug='1') content = self._node_to_list(nodes) # there should be a minified file self.assertEqual(content[3].count('test_assetsbundle.bundle1.min.js'), 1, "there should be one minified assets created in debug mode") # there should be one minified assets created in debug mode self.assertEqual(len(self._any_ira_for_bundle('min.js')), 1, "there should be one minified assets created in debug mode") # there shouldn't be any non-minified assets created in debug mode self.assertEqual(len(self._any_ira_for_bundle('js')), 0, "there shouldn't be any non-minified assets created in debug mode") def test_07_debug_assets(self): """ Checks that a bundle rendered in debug assets mode outputs non-minified assets and create an non-minified ir.attachment at the . """ debug_bundle = self._get_asset(self.jsbundle_name) nodes = debug_bundle.to_node(debug='assets') content = self._node_to_list(nodes) # there should be a non-minified file (not .min.js) self.assertEqual(content[3].count('test_assetsbundle.bundle1.js'), 1, "there should be one non-minified assets created in debug assets mode") # there shouldn't be any minified assets created in debug mode self.assertEqual(len(self._any_ira_for_bundle('min.js')), 0, "there shouldn't be any minified assets created in debug assets mode") # there should be one non-minified assets created in debug mode self.assertEqual(len(self._any_ira_for_bundle('js')), 1, "there should be one non-minified assets without a version in its url created in debug assets mode") def test_08_css_generation3(self): # self.cssbundle_xlmid contains 3 rules (not checked below) self.bundle = self._get_asset(self.cssbundle_name) self.bundle.css() self.assertEqual(len(self._any_ira_for_bundle('min.css')), 1) self.assertEqual(len(self.bundle.get_attachments('min.css')), 1) def test_09_css_access(self): """ Checks that the bundle's cache is working, i.e. that a bundle creates only enough ir.attachment records when rendered multiple times. """ bundle0 = self._get_asset(self.cssbundle_name) bundle0.css() self.assertEqual(len(self._any_ira_for_bundle('min.css')), 1) version0 = bundle0.version ira0 = self._any_ira_for_bundle('min.css') date0 = ira0.create_date bundle1 = self._get_asset(self.cssbundle_name) bundle1.css() self.assertEqual(len(self._any_ira_for_bundle('min.css')), 1) version1 = bundle1.version ira1 = self._any_ira_for_bundle('min.css') date1 = ira1.create_date self.assertEqual(version0, version1) self.assertEqual(date0, date1) def test_11_css_content_invalidation(self): """ Checks that a bundle is invalidated when its content is modified by adding a file to source. """ bundle0 = self._get_asset(self.cssbundle_name) bundle0.css() files0 = bundle0.files version0 = bundle0.version self.assertEqual(len(self._any_ira_for_bundle('min.css')), 1) self.env['ir.asset'].create({ 'name': 'test bundle inheritance', 'bundle': self.cssbundle_name, 'path': 'test_assetsbundle/static/src/css/test_cssfile2.css', }) bundle1 = self._get_asset(self.cssbundle_name) bundle1.css() files1 = bundle1.files version1 = bundle1.version self.assertNotEqual(files0, files1) self.assertNotEqual(version0, version1) # check if the previous attachment are correctly cleaned self.assertEqual(len(self._any_ira_for_bundle('min.css')), 1) def test_12_css_debug(self): """ Check that a bundle in debug mode outputs non-minified assets. """ debug_bundle = self._get_asset(self.cssbundle_name) nodes = debug_bundle.to_node(debug='assets') content = self._node_to_list(nodes) # find back one of the original asset file self.assertIn('/web/assets/debug/test_assetsbundle.bundle2.css', content) # there should be one css asset created in debug mode self.assertEqual(len(self._any_ira_for_bundle('css')), 1, 'there should be one css asset created in debug mode') def test_14_duplicated_css_assets(self): """ Checks that if the bundle's ir.attachment record is duplicated, the bundle is only sourced once. This could happen if multiple transactions try to render the bundle simultaneously. """ bundle0 = self._get_asset(self.cssbundle_name) bundle0.css() self.assertEqual(len(self._any_ira_for_bundle('min.css')), 1) # duplicate the asset bundle ira0 = self._any_ira_for_bundle('min.css') ira1 = ira0.copy() self.assertEqual(len(self._any_ira_for_bundle('min.css')), 2) self.assertEqual(ira0.store_fname, ira1.store_fname) # the ir.attachment records should be deduplicated in the bundle's content nodes = bundle0.to_node() content = self._node_to_list(nodes) self.assertEqual(content[2].count('test_assetsbundle.bundle2.min.css'), 1) # Language direction specific tests def test_15_rtl_css_generation(self): """ Checks that a bundle creates an ir.attachment record when its `css` method is called for the first time for language with different direction and separate bundle is created for rtl direction. """ self.bundle = self._get_asset(self.cssbundle_name, env=self.env(context={'lang': 'ar_SY'})) # there shouldn't be any attachment associated to this bundle self.assertEqual(len(self._any_ira_for_bundle('min.css', lang='ar_SY')), 0) self.assertEqual(len(self.bundle.get_attachments('min.css')), 0) # trigger the first generation and, thus, the first save in database self.bundle.css() # there should be one attachment associated to this bundle self.assertEqual(len(self._any_ira_for_bundle('min.css', lang='ar_SY')), 1) self.assertEqual(len(self.bundle.get_attachments('min.css')), 1) def test_16_ltr_and_rtl_css_access(self): """ Checks that the bundle's cache is working, i.e. that the bundle creates only one ir.attachment record when rendered multiple times for rtl direction also check we have two css bundles, one for ltr and one for rtl. """ # Assets access for en_US language ltr_bundle0 = self._get_asset(self.cssbundle_name) ltr_bundle0.css() self.assertEqual(len(self._any_ira_for_bundle('min.css')), 1) ltr_version0 = ltr_bundle0.version ltr_ira0 = self._any_ira_for_bundle('min.css') ltr_date0 = ltr_ira0.create_date ltr_bundle1 = self._get_asset(self.cssbundle_name) ltr_bundle1.css() self.assertEqual(len(self._any_ira_for_bundle('min.css')), 1) ltr_version1 = ltr_bundle1.version ltr_ira1 = self._any_ira_for_bundle('min.css') ltr_date1 = ltr_ira1.create_date self.assertEqual(ltr_version0, ltr_version1) self.assertEqual(ltr_date0, ltr_date1) # Assets access for ar_SY language rtl_bundle0 = self._get_asset(self.cssbundle_name, env=self.env(context={'lang': 'ar_SY'})) rtl_bundle0.css() self.assertEqual(len(self._any_ira_for_bundle('min.css', lang='ar_SY')), 1) rtl_version0 = rtl_bundle0.version rtl_ira0 = self._any_ira_for_bundle('min.css', lang='ar_SY') rtl_date0 = rtl_ira0.create_date rtl_bundle1 = self._get_asset(self.cssbundle_name, env=self.env(context={'lang': 'ar_SY'})) rtl_bundle1.css() self.assertEqual(len(self._any_ira_for_bundle('min.css', lang='ar_SY')), 1) rtl_version1 = rtl_bundle1.version rtl_ira1 = self._any_ira_for_bundle('min.css', lang='ar_SY') rtl_date1 = rtl_ira1.create_date self.assertEqual(rtl_version0, rtl_version1) self.assertEqual(rtl_date0, rtl_date1) # Checks rtl and ltr bundles are different self.assertNotEqual(ltr_ira1.id, rtl_ira1.id) # Check two bundles are available, one for ltr and one for rtl css_bundles = self.env['ir.attachment'].search([ ('url', '=like', '/web/assets/%-%/{0}%.{1}'.format(self.cssbundle_name, 'min.css')) ]) self.assertEqual(len(css_bundles), 2) def test_17_css_bundle_date_invalidation(self): """ Checks that both css bundles are invalidated when one of its assets' modification date is changed """ # Assets access for en_US language ltr_bundle0 = self._get_asset(self.cssbundle_name) ltr_bundle0.css() ltr_last_modified0 = ltr_bundle0.last_modified ltr_version0 = ltr_bundle0.version # Assets access for ar_SY language rtl_bundle0 = self._get_asset(self.cssbundle_name, env=self.env(context={'lang': 'ar_SY'})) rtl_bundle0.css() rtl_last_modified0 = rtl_bundle0.last_modified rtl_version0 = rtl_bundle0.version # Touch test_cssfile1.css # Note: No lang specific context given while calling _get_asset so it will load assets for en_US path = get_resource_path('test_assetsbundle', 'static', 'src', 'css', 'test_cssfile1.css') ltr_bundle1 = self._get_asset(self.cssbundle_name) with self._touch(path): ltr_bundle1.css() ltr_last_modified1 = ltr_bundle1.last_modified ltr_version1 = ltr_bundle1.version ltr_ira1 = self._any_ira_for_bundle('min.css') self.assertNotEqual(ltr_last_modified0, ltr_last_modified1) self.assertNotEqual(ltr_version0, ltr_version1) rtl_bundle1 = self._get_asset(self.cssbundle_name, env=self.env(context={'lang': 'ar_SY'})) rtl_bundle1.css() rtl_last_modified1 = rtl_bundle1.last_modified rtl_version1 = rtl_bundle1.version rtl_ira1 = self._any_ira_for_bundle('min.css', lang='ar_SY') self.assertNotEqual(rtl_last_modified0, rtl_last_modified1) self.assertNotEqual(rtl_version0, rtl_version1) # Checks rtl and ltr bundles are different self.assertNotEqual(ltr_ira1.id, rtl_ira1.id) # check if the previous attachment is correctly cleaned css_bundles = self.env['ir.attachment'].search([ ('url', '=like', '/web/assets/%-%/{0}%.{1}'.format(self.cssbundle_name, 'min.css')) ]) self.assertEqual(len(css_bundles), 2) def test_18_css_bundle_content_invalidation(self): """ Checks that a bundle is invalidated when its content is modified by adding a file to source. """ # Assets for en_US ltr_bundle0 = self._get_asset(self.cssbundle_name) ltr_bundle0.css() ltr_files0 = ltr_bundle0.files ltr_version0 = ltr_bundle0.version rtl_bundle0 = self._get_asset(self.cssbundle_name, env=self.env(context={'lang': 'ar_SY'})) rtl_bundle0.css() rtl_files0 = rtl_bundle0.files rtl_version0 = rtl_bundle0.version css_bundles = self.env['ir.attachment'].search([ ('url', '=like', '/web/assets/%-%/{0}%.{1}'.format(self.cssbundle_name, 'min.css')) ]) self.assertEqual(len(css_bundles), 2) self.env['ir.asset'].create({ 'name': 'test bundle inheritance', 'bundle': self.cssbundle_name, 'path': 'test_assetsbundle/static/src/css/test_cssfile3.css', }) ltr_bundle1 = self._get_asset(self.cssbundle_name) ltr_bundle1.css() ltr_files1 = ltr_bundle1.files ltr_version1 = ltr_bundle1.version ltr_ira1 = self._any_ira_for_bundle('min.css') self.assertNotEqual(ltr_files0, ltr_files1) self.assertNotEqual(ltr_version0, ltr_version1) rtl_bundle1 = self._get_asset(self.cssbundle_name, env=self.env(context={'lang': 'ar_SY'})) rtl_bundle1.css() rtl_files1 = rtl_bundle1.files rtl_version1 = rtl_bundle1.version rtl_ira1 = self._any_ira_for_bundle('min.css', lang='ar_SY') self.assertNotEqual(rtl_files0, rtl_files1) self.assertNotEqual(rtl_version0, rtl_version1) # Checks rtl and ltr bundles are different self.assertNotEqual(ltr_ira1.id, rtl_ira1.id) # check if the previous attachment are correctly cleaned css_bundles = self.env['ir.attachment'].search([ ('url', '=like', '/web/assets/%-%/{0}%.{1}'.format(self.cssbundle_name, 'min.css')) ]) self.assertEqual(len(css_bundles), 2) def test_19_css_in_debug_assets(self): """ Checks that a bundle rendered in debug mode(assets) with right to left language direction stores css files in assets bundle. """ debug_bundle = self._get_asset(self.cssbundle_name, env=self.env(context={'lang': 'ar_SY'})) nodes = debug_bundle.to_node(debug='assets') content = self._node_to_list(nodes) # there should be an css assets bundle in /debug/rtl if user's lang direction is rtl and debug=assets self.assertIn('/web/assets/debug/rtl/{0}.css'.format(self.cssbundle_name), content, "there should be an css assets bundle in /debug/rtl if user's lang direction is rtl and debug=assets") # there should be an css assets bundle created in /rtl if user's lang direction is rtl and debug=assets css_bundle = self.env['ir.attachment'].search([ ('url', '=like', '/web/assets/%-%/rtl/{0}.css'.format(self.cssbundle_name)) ]) self.assertEqual(len(css_bundle), 1, "there should be an css assets bundle created in /rtl if user's lang direction is rtl and debug=assets") def test_20_external_lib_assets(self): html = self.env['ir.ui.view']._render_template('test_assetsbundle.template2') attachments = self.env['ir.attachment'].search([('url', '=like', '/web/assets/%-%/test_assetsbundle.bundle4.%')]) self.assertEqual(len(attachments), 2) asset_data_css = etree.HTML(html).xpath('//*[@data-asset-bundle]')[0] asset_data_js = etree.HTML(html).xpath('//*[@data-asset-bundle]')[1] format_data = { "js": attachments[0].url, "css": attachments[1].url, "asset_bundle_css": asset_data_css.attrib.get('data-asset-bundle'), "asset_version_css": asset_data_css.attrib.get('data-asset-version'), "asset_bundle_js": asset_data_js.attrib.get('data-asset-bundle'), "asset_version_js": asset_data_js.attrib.get('data-asset-version'), } self.assertEqual(html.strip(), ("""<!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="http://test.external.link/style1.css"/> <link type="text/css" rel="stylesheet" href="http://test.external.link/style2.css"/> <link type="text/css" rel="stylesheet" href="%(css)s" data-asset-bundle="%(asset_bundle_css)s" data-asset-version="%(asset_version_css)s"/> <meta/> <script type="text/javascript" src="http://test.external.link/javascript1.js"></script> <script type="text/javascript" src="http://test.external.link/javascript2.js"></script> <script type="text/javascript" src="%(js)s" data-asset-bundle="%(asset_bundle_js)s" data-asset-version="%(asset_version_js)s"></script> </head> <body> </body> </html>""" % format_data)) def test_21_external_lib_assets_debug_mode(self): html = self.env['ir.ui.view']._render_template('test_assetsbundle.template2', {"debug": "assets"}) attachments = self.env['ir.attachment'].search([('url', '=like', '%/test_assetsbundle.bundle4.js')]) self.assertEqual(len(attachments), 1) asset_data_css = etree.HTML(html).xpath('//*[@data-asset-bundle]')[0] asset_data_js = etree.HTML(html).xpath('//*[@data-asset-bundle]')[1] format_data = { "asset_bundle_css": asset_data_css.attrib.get('data-asset-bundle'), "asset_version_css": asset_data_css.attrib.get('data-asset-version'), "asset_bundle_js": asset_data_js.attrib.get('data-asset-bundle'), "asset_version_js": asset_data_js.attrib.get('data-asset-version'), "css": '/web/assets/debug/test_assetsbundle.bundle4.css', "js": '/web/assets/debug/test_assetsbundle.bundle4.js', } self.assertEqual(html.strip(), ("""<!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="http://test.external.link/style1.css"/> <link type="text/css" rel="stylesheet" href="http://test.external.link/style2.css"/> <link type="text/css" rel="stylesheet" href="%(css)s" data-asset-bundle="%(asset_bundle_css)s" data-asset-version="%(asset_version_css)s"/> <meta/> <script type="text/javascript" src="http://test.external.link/javascript1.js"></script> <script type="text/javascript" src="http://test.external.link/javascript2.js"></script> <script type="text/javascript" src="%(js)s" data-asset-bundle="%(asset_bundle_js)s" data-asset-version="%(asset_version_js)s"></script> </head> <body> </body> </html>""" % format_data)) @tagged('-at_install', 'post_install') class TestAssetsBundleInBrowser(HttpCase): def test_01_js_interpretation(self): """ Checks that the javascript of a bundle is correctly interpreted. """ self.browser_js( "/test_assetsbundle/js", "a + b + c === 6 ? console.log('test successful') : console.log('error')", login="admin" ) @skip("Feature Regression") def test_02_js_interpretation_inline(self): """ Checks that the javascript of a bundle is correctly interpretet when mixed with inline. """ view_arch = """ <data> <xpath expr="." position="inside"> <script type="text/javascript"> var d = 4; </script> </xpath> </data> """ self.env['ir.ui.view'].create({ 'name': 'test bundle inheritance inline js', 'type': 'qweb', 'arch': view_arch, 'inherit_id': self.browse_ref('test_assetsbundle.bundle1').id, }) self.env.user.flush() self.browser_js( "/test_assetsbundle/js", "a + b + c + d === 10 ? console.log('test successful') : console.log('error')", login="admin", ) # LPE Fixme # Review point @al: is this really what we want people to do ? def test_03_js_interpretation_recommended_new_method(self): """ Checks the feature of test_02 is still produceable, but in another way '/web/content/<int:id>/<string: filename.js>', """ code = b'const d = 4;' attach = self.env['ir.attachment'].create({ 'name': 'CustomJscode.js', 'mimetype': 'text/javascript', 'datas': base64.b64encode(code), }) # Use this route (filename is necessary) custom_url = '/web/content/%s/%s' % (attach.id, attach.name) attach.url = custom_url self.env['ir.asset'].create({ 'name': 'lol', 'bundle': 'test_assetsbundle.bundle1', 'path': custom_url, }) self.browser_js( "/test_assetsbundle/js", "a + b + c + d === 10 ? console.log('test successful') : console.log('error')", login="admin", ) class TestAssetsBundleWithIRAMock(FileTouchable): def setUp(self): super(TestAssetsBundleWithIRAMock, self).setUp() self.stylebundle_name = 'test_assetsbundle.bundle3' self.counter = counter = Counter() # patch methods 'create' and 'unlink' of model 'ir.attachment' origin_create = IrAttachment.create origin_unlink = AssetsBundle._unlink_attachments @api.model def create(self, vals): counter.update(['create']) return origin_create(self, vals) def unlink(self, attachments): counter.update(['unlink']) return origin_unlink(self, attachments) self.patch(IrAttachment, 'create', create) self.patch(AssetsBundle, '_unlink_attachments', unlink) def _get_asset(self): files, _ = self.env['ir.qweb']._get_asset_content(self.stylebundle_name) return AssetsBundle(self.stylebundle_name, files, env=self.env) def _bundle(self, asset, should_create, should_unlink): self.counter.clear() asset.to_node(debug='assets') self.assertEqual(self.counter['create'], 2 if should_create else 0) self.assertEqual(self.counter['unlink'], 2 if should_unlink else 0) def test_01_debug_mode_assets(self): """ Checks that the ir.attachments records created for compiled assets in debug mode are correctly invalidated. """ # Compile for the first time self._bundle(self._get_asset(), True, False) # Compile a second time, without changes self._bundle(self._get_asset(), False, False) # Touch the file and compile a third time path = get_resource_path('test_assetsbundle', 'static', 'src', 'scss', 'test_file1.scss') t = time.time() + 5 asset = self._get_asset() with self._touch(path, t): self._bundle(asset, True, True) # Because we are in the same transaction since the beginning of the test, the first asset # created and the second one have the same write_date, but the file's last modified date # has really been modified. If we do not update the write_date to a posterior date, we are # not able to reproduce the case where we compile this bundle again without changing # anything. self.env['ir.attachment'].flush(['checksum', 'write_date']) self.cr.execute("update ir_attachment set write_date=clock_timestamp() + interval '10 seconds' where id = (select max(id) from ir_attachment)") self.env['ir.attachment'].invalidate_cache(['write_date']) # Compile a fourth time, without changes self._bundle(self._get_asset(), False, False) @tagged('assets_manifest') class TestAssetsManifest(AddonManifestPatched): def make_asset_view(self, asset_key, t_call_assets_attrs=None): default_attrs = { 't-js': 'true', 't-css': 'false', } if t_call_assets_attrs: default_attrs.update(t_call_assets_attrs) attrs = ' '.join(['%s="%s"' % (k, v) for k, v in default_attrs.items()]) arch = ''' <div> <t t-call-assets="%(asset_key)s" %(attrs)s /> </div> ''' % { 'asset_key': asset_key, 'attrs': attrs } view = self.env['ir.ui.view'].create({ 'name': 'test asset', 'arch': arch, 'type': 'qweb', }) return view def assertStringEqual(self, reference, tested): tested = textwrap.dedent(tested).strip() reference = reference.strip() self.assertEqual(tested, reference) def test_01_globmanifest(self): view = self.make_asset_view('test_assetsbundle.manifest1') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest1.min.js')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.manifest1' */ var a=1;; /* /test_assetsbundle/static/src/js/test_jsfile2.js defined in bundle 'test_assetsbundle.manifest1' */ var b=2;; /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.manifest1' */ var c=3;; /* /test_assetsbundle/static/src/js/test_jsfile4.js defined in bundle 'test_assetsbundle.manifest1' */ var d=4; ''' ) def test_02_globmanifest_no_duplicates(self): view = self.make_asset_view('test_assetsbundle.manifest2') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest2.min.js')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.manifest2' */ var a=1;; /* /test_assetsbundle/static/src/js/test_jsfile2.js defined in bundle 'test_assetsbundle.manifest2' */ var b=2;; /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.manifest2' */ var c=3;; /* /test_assetsbundle/static/src/js/test_jsfile4.js defined in bundle 'test_assetsbundle.manifest2' */ var d=4; ''' ) def test_03_globmanifest_file_before(self): view = self.make_asset_view('test_assetsbundle.manifest3') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest3.min.js')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.manifest3' */ var c=3;; /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.manifest3' */ var a=1;; /* /test_assetsbundle/static/src/js/test_jsfile2.js defined in bundle 'test_assetsbundle.manifest3' */ var b=2;; /* /test_assetsbundle/static/src/js/test_jsfile4.js defined in bundle 'test_assetsbundle.manifest3' */ var d=4; ''' ) def test_04_globmanifest_with_irasset(self): view = self.make_asset_view('test_assetsbundle.manifest4') self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'bundle': 'test_assetsbundle.manifest4', 'path': 'test_assetsbundle/static/src/js/test_jsfile1.js', }) view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest4.min.js')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.manifest4' */ var c=3;; /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.manifest4' */ var a=1; ''' ) def test_05_only_irasset(self): view = self.make_asset_view('test_assetsbundle.irasset1') self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'bundle': 'test_assetsbundle.irasset1', 'path': 'test_assetsbundle/static/src/js/test_jsfile1.js', }) view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.irasset1.min.js')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.irasset1' */ var a=1; ''' ) def test_06_replace(self): view = self.make_asset_view('test_assetsbundle.manifest1') self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'bundle': 'test_assetsbundle.manifest1', 'directive': 'replace', 'target': 'test_assetsbundle/static/src/js/test_jsfile1.js', 'path': 'http://external.link/external.js', }) rendered = view._render() html_tree = lxml.etree.fromstring(rendered) scripts = html_tree.findall('script') self.assertEqual(len(scripts), 2) self.assertEqual(scripts[0].get('src'), 'http://external.link/external.js') attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest1')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile2.js defined in bundle 'test_assetsbundle.manifest1' */ var b=2;; /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.manifest1' */ var c=3;; /* /test_assetsbundle/static/src/js/test_jsfile4.js defined in bundle 'test_assetsbundle.manifest1' */ var d=4; ''' ) def test_06_2_replace(self): view = self.make_asset_view('test_assetsbundle.manifest4') self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'bundle': 'test_assetsbundle.manifest4', 'directive': 'replace', 'path': 'test_assetsbundle/static/src/js/test_jsfile1.js', 'target': 'test_assetsbundle/static/src/js/test_jsfile3.js', }) view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest4')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.manifest4' */ var a=1; ''' ) def test_06_3_replace_globs(self): view = self.make_asset_view('test_assetsbundle.manifest4') self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'directive': 'prepend', 'bundle': 'test_assetsbundle.manifest4', 'path': 'test_assetsbundle/static/src/js/test_jsfile4.js', }) # asset is now: js_file4 ; js_file3 self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'bundle': 'test_assetsbundle.manifest4', 'directive': 'replace', 'path': 'test_assetsbundle/static/src/js/test_jsfile[12].js', 'target': 'test_assetsbundle/static/src/js/test_jsfile[45].js', }) # asset is now: js_file1 ; js_file2 ; js_file3 # because js_file is replaced by 1 and 2 view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest4')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.manifest4' */ var a=1;; /* /test_assetsbundle/static/src/js/test_jsfile2.js defined in bundle 'test_assetsbundle.manifest4' */ var b=2;; /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.manifest4' */ var c=3; ''' ) def test_07_remove(self): view = self.make_asset_view('test_assetsbundle.manifest5') self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'bundle': 'test_assetsbundle.manifest5', 'directive': 'remove', 'path': 'test_assetsbundle/static/src/js/test_jsfile2.js', }) view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest5')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.manifest5' */ var a=1;; /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.manifest5' */ var c=3;; /* /test_assetsbundle/static/src/js/test_jsfile4.js defined in bundle 'test_assetsbundle.manifest5' */ var d=4; ''' ) def test_08_remove_inexistent_file(self): self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'bundle': 'test_assetsbundle.remove_error', 'path': '/test_assetsbundle/static/src/js/test_jsfile1.js', }) view = self.make_asset_view('test_assetsbundle.remove_error') self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'bundle': 'test_assetsbundle.remove_error', 'directive': 'remove', 'path': 'test_assetsbundle/static/src/js/test_doesntexist.js', }) with self.assertRaises(Exception) as cm: view._render() self.assertTrue( "['test_assetsbundle/static/src/js/test_doesntexist.js'] not found" in cm.exception.message ) def test_09_remove_wholeglob(self): view = self.make_asset_view('test_assetsbundle.manifest2') self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'bundle': 'test_assetsbundle.manifest2', 'directive': 'remove', 'path': 'test_assetsbundle/static/src/**/*', }) view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest2.js')], order='create_date DESC', limit=1) # indeed everything in the bundle matches the glob, so there is no attachment self.assertFalse(attach) def test_10_prepend(self): view = self.make_asset_view('test_assetsbundle.manifest4') self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'directive': 'prepend', 'bundle': 'test_assetsbundle.manifest4', 'path': 'test_assetsbundle/static/src/js/test_jsfile1.js', }) view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest4')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.manifest4' */ var a=1;; /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.manifest4' */ var c=3; ''' ) def test_11_include(self): view = self.make_asset_view('test_assetsbundle.irasset_include1') self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'directive': 'include', 'bundle': 'test_assetsbundle.irasset_include1', 'path': 'test_assetsbundle.manifest6', }) view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.irasset_include1')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.irasset_include1' */ var c=3; ''' ) def test_12_include2(self): view = self.make_asset_view('test_assetsbundle.manifest6') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest6')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.manifest6' */ var c=3; ''' ) def test_13_include_circular(self): view = self.make_asset_view('test_assetsbundle.irasset_include1') self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'directive': 'include', 'bundle': 'test_assetsbundle.irasset_include1', 'path': 'test_assetsbundle.irasset_include2', }) self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'directive': 'include', 'bundle': 'test_assetsbundle.irasset_include2', 'path': 'test_assetsbundle.irasset_include1', }) with self.assertRaises(QWebException) as cm: view._render() self.assertTrue(cm.exception.error) self.assertFalse(isinstance(cm.exception.error, RecursionError)) self.assertTrue( 'Circular assets bundle declaration:' in cm.exception.message ) def test_13_2_include_recursive_sibling(self): view = self.make_asset_view('test_assetsbundle.irasset_include1') self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'directive': 'include', 'bundle': 'test_assetsbundle.irasset_include1', 'path': 'test_assetsbundle.irasset_include2', }) self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'directive': 'include', 'bundle': 'test_assetsbundle.irasset_include2', 'path': 'test_assetsbundle.irasset_include3', }) self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'directive': 'include', 'bundle': 'test_assetsbundle.irasset_include2', 'path': 'test_assetsbundle.irasset_include4', }) self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'directive': 'include', 'bundle': 'test_assetsbundle.irasset_include4', 'path': 'test_assetsbundle.irasset_include3', }) self.env['ir.asset'].create({ 'name': 'test_jsfile4', 'bundle': 'test_assetsbundle.irasset_include3', 'path': 'test_assetsbundle/static/src/js/test_jsfile1.js', }) view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.irasset_include1')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.irasset_include1' */ var a=1; ''' ) def test_14_other_module(self): self.installed_modules.append('test_other') self.manifests['test_other'] = { 'name': 'test_other', 'depends': ['test_assetsbundle'], 'addons_path': pathlib.Path(__file__).resolve().parent, 'assets': { 'test_other.mockmanifest1': [ ('include', 'test_assetsbundle.manifest4'), ] } } view = self.make_asset_view('test_other.mockmanifest1') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_other.mockmanifest1')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_other.mockmanifest1' */ var c=3; ''' ) def test_15_other_module_append(self): self.installed_modules.append('test_other') self.manifests['test_other'] = { 'name': 'test_other', 'depends': ['test_assetsbundle'], 'addons_path': pathlib.Path(__file__).resolve().parent, 'assets': { 'test_assetsbundle.manifest4': [ 'test_assetsbundle/static/src/js/test_jsfile1.js', ] } } view = self.make_asset_view('test_assetsbundle.manifest4') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest4')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.manifest4' */ var c=3;; /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.manifest4' */ var a=1; ''' ) def test_16_other_module_prepend(self): self.installed_modules.append('test_other') self.manifests['test_other'] = { 'name': 'test_other', 'depends': ['test_assetsbundle'], 'addons_path': pathlib.Path(__file__).resolve().parent, 'assets': { 'test_assetsbundle.manifest4': [ ('prepend', 'test_assetsbundle/static/src/js/test_jsfile1.js'), ] } } view = self.make_asset_view('test_assetsbundle.manifest4') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest4')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.manifest4' */ var a=1;; /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.manifest4' */ var c=3; ''' ) def test_17_other_module_replace(self): self.installed_modules.append('test_other') self.manifests['test_other'] = { 'name': 'test_other', 'depends': ['test_assetsbundle'], 'addons_path': pathlib.Path(__file__).resolve().parent, 'assets': { 'test_assetsbundle.manifest4': [ ('replace', 'test_assetsbundle/static/src/js/test_jsfile3.js', 'test_assetsbundle/static/src/js/test_jsfile1.js'), ] } } view = self.make_asset_view('test_assetsbundle.manifest4') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest4')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.manifest4' */ var a=1; ''' ) def test_17_other_module_remove(self): self.installed_modules.append('test_other') self.manifests['test_other'] = { 'name': 'test_other', 'depends': ['test_assetsbundle'], 'addons_path': pathlib.Path(__file__).resolve().parent, 'assets': { 'test_assetsbundle.manifest4': [ ('remove', 'test_assetsbundle/static/src/js/test_jsfile3.js'), ('append', 'test_assetsbundle/static/src/js/test_jsfile1.js'), ] } } view = self.make_asset_view('test_assetsbundle.manifest4') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest4')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.manifest4' */ var a=1; ''' ) def test_18_other_module_external(self): self.installed_modules.append('test_other') self.manifests['test_other'] = { 'name': 'test_other', 'depends': ['test_assetsbundle'], 'addons_path': pathlib.Path(__file__).resolve().parent, 'assets': { 'test_assetsbundle.manifest4': [ 'http://external.link/external.js', ] } } view = self.make_asset_view('test_assetsbundle.manifest4') rendered = view._render() html_tree = lxml.etree.fromstring(rendered) scripts = html_tree.findall('script') self.assertEqual(len(scripts), 2) self.assertEqual(scripts[0].get('src'), 'http://external.link/external.js') attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest4')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.manifest4' */ var c=3; ''' ) # # LPE Fixme: Warning, this matches a change in behavior # Before this, each node within an asset could have a "media" and/or a "direction" # attribute to tell the browser to take preferably the css resource # in the relevant viewport or text direction # # with the new ir_assert mechanism, these attributes are only evaluated at the t-call-asset # step, that is, a step earlier than before, implicating a more restrictive usage # def test_19_css_specific_attrs_in_tcallassets(self): self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.irasset2', 'path': 'http://external.css/externalstyle.css', }) self.env['ir.asset'].create({ 'name': '2', 'bundle': 'test_assetsbundle.irasset2', 'path': 'test_assetsbundle/static/src/css/test_cssfile1.css', }) view = self.make_asset_view('test_assetsbundle.irasset2', { 't-js': 'false', 't-css': 'true', 'media': 'print', }) rendered = view._render() html_tree = lxml.etree.fromstring(rendered) stylesheets = html_tree.findall('link') self.assertEqual(len(stylesheets), 2) self.assertEqual(stylesheets[0].get('href'), 'http://external.css/externalstyle.css') self.assertEqual(stylesheets[0].get('media'), 'print') attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.irasset2')], order='create_date DESC', limit=1) self.assertEqual(len(attach), 1) def test_20_css_base(self): self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.irasset2', 'path': 'http://external.css/externalstyle.css', }) self.env['ir.asset'].create({ 'name': '2', 'bundle': 'test_assetsbundle.irasset2', 'path': 'test_assetsbundle/static/src/scss/test_file1.scss', }) view = self.make_asset_view('test_assetsbundle.irasset2', { 't-js': 'false', 't-css': 'true', }) rendered = view._render() html_tree = lxml.etree.fromstring(rendered) stylesheets = html_tree.findall('link') self.assertEqual(len(stylesheets), 2) self.assertEqual(stylesheets[0].get('href'), 'http://external.css/externalstyle.css') for css in stylesheets: self.assertFalse(css.get('media')) attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.irasset2')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/scss/test_file1.scss defined in bundle 'test_assetsbundle.irasset2' */ .rule1{color: black;} ''' ) def test_21_js_before_css(self): '''Non existing target node: ignore the manifest line''' self.installed_modules.append('test_other') self.manifests['test_other'] = { 'name': 'test_other', 'depends': ['test_assetsbundle'], 'addons_path': pathlib.Path(__file__).resolve().parent, 'assets': { 'test_other.bundle4': [ ('before', 'test_assetsbundle/static/src/css/test_cssfile1.css', '/test_assetsbundle/static/src/js/test_jsfile4.js') ] } } view = self.make_asset_view('test_assetsbundle.bundle4') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.bundle4')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.bundle4' */ var a=1;; /* /test_assetsbundle/static/src/js/test_jsfile2.js defined in bundle 'test_assetsbundle.bundle4' */ var b=2;; /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.bundle4' */ var c=3; ''' ) def test_22_js_before_js(self): self.installed_modules.append('test_other') self.manifests['test_other'] = { 'name': 'test_other', 'depends': ['test_assetsbundle'], 'addons_path': pathlib.Path(__file__).resolve().parent, 'assets': { 'test_assetsbundle.bundle4': [ ('before', '/test_assetsbundle/static/src/js/test_jsfile3.js', '/test_assetsbundle/static/src/js/test_jsfile4.js') ] } } view = self.make_asset_view('test_assetsbundle.bundle4') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.bundle4')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.bundle4' */ var a=1;; /* /test_assetsbundle/static/src/js/test_jsfile2.js defined in bundle 'test_assetsbundle.bundle4' */ var b=2;; /* /test_assetsbundle/static/src/js/test_jsfile4.js defined in bundle 'test_assetsbundle.bundle4' */ var d=4;; /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.bundle4' */ var c=3; ''' ) def test_23_js_after_css(self): '''Non existing target node: ignore the manifest line''' self.installed_modules.append('test_other') self.manifests['test_other'] = { 'name': 'test_other', 'depends': ['test_assetsbundle'], 'addons_path': pathlib.Path(__file__).resolve().parent, 'assets': { 'test_other.bundle4': [ ('after', 'test_assetsbundle/static/src/css/test_cssfile1.css', '/test_assetsbundle/static/src/js/test_jsfile4.js') ] } } view = self.make_asset_view('test_assetsbundle.bundle4') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.bundle4')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.bundle4' */ var a=1;; /* /test_assetsbundle/static/src/js/test_jsfile2.js defined in bundle 'test_assetsbundle.bundle4' */ var b=2;; /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.bundle4' */ var c=3; ''' ) def test_24_js_after_js(self): self.installed_modules.append('test_other') self.manifests['test_other'] = { 'name': 'test_other', 'depends': ['test_assetsbundle'], 'addons_path': pathlib.Path(__file__).resolve().parent, 'assets': { 'test_assetsbundle.bundle4': [ ('after', '/test_assetsbundle/static/src/js/test_jsfile2.js', '/test_assetsbundle/static/src/js/test_jsfile4.js') ] } } view = self.make_asset_view('test_assetsbundle.bundle4') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.bundle4')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.bundle4' */ var a=1;; /* /test_assetsbundle/static/src/js/test_jsfile2.js defined in bundle 'test_assetsbundle.bundle4' */ var b=2;; /* /test_assetsbundle/static/src/js/test_jsfile4.js defined in bundle 'test_assetsbundle.bundle4' */ var d=4;; /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.bundle4' */ var c=3; ''' ) def test_25_js_before_js_in_irasset(self): self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.bundle4', 'path': '/test_assetsbundle/static/src/js/test_jsfile4.js', 'target': '/test_assetsbundle/static/src/js/test_jsfile3.js', 'directive': 'before', }) view = self.make_asset_view('test_assetsbundle.bundle4') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.bundle4')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.bundle4' */ var a=1;; /* /test_assetsbundle/static/src/js/test_jsfile2.js defined in bundle 'test_assetsbundle.bundle4' */ var b=2;; /* /test_assetsbundle/static/src/js/test_jsfile4.js defined in bundle 'test_assetsbundle.bundle4' */ var d=4;; /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.bundle4' */ var c=3; ''' ) def test_26_js_after_js_in_irasset(self): self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.bundle4', 'path': '/test_assetsbundle/static/src/js/test_jsfile4.js', 'target': '/test_assetsbundle/static/src/js/test_jsfile2.js', 'directive': 'after', }) view = self.make_asset_view('test_assetsbundle.bundle4') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.bundle4')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.bundle4' */ var a=1;; /* /test_assetsbundle/static/src/js/test_jsfile2.js defined in bundle 'test_assetsbundle.bundle4' */ var b=2;; /* /test_assetsbundle/static/src/js/test_jsfile4.js defined in bundle 'test_assetsbundle.bundle4' */ var d=4;; /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.bundle4' */ var c=3; ''' ) def test_27_mixing_after_before_js_css_in_irasset(self): self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.bundle4', 'path': '/test_assetsbundle/static/src/js/test_jsfile4.js', 'target': '/test_assetsbundle/static/src/css/test_cssfile1.css', 'directive': 'after', }) self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.bundle4', 'path': '/test_assetsbundle/static/src/css/test_cssfile3.css', 'target': '/test_assetsbundle/static/src/js/test_jsfile2.js', 'directive': 'before', }) view = self.make_asset_view('test_assetsbundle.bundle4', { 't-js': 'true', 't-css': 'true', }) view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.bundle4')], order='create_date DESC', limit=2) attach_css = None attach_js = None for a in attach: if '.css' in a.url: attach_css = a elif '.js' in a.url: attach_js = a js_content = attach_js.raw.decode() self.assertStringEqual( js_content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.bundle4' */ var a=1;; /* /test_assetsbundle/static/src/js/test_jsfile2.js defined in bundle 'test_assetsbundle.bundle4' */ var b=2;; /* /test_assetsbundle/static/src/js/test_jsfile4.js defined in bundle 'test_assetsbundle.bundle4' */ var d=4;; /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.bundle4' */ var c=3; ''' ) css_content = attach_css.raw.decode() self.assertStringEqual( css_content, ''' /* /test_assetsbundle/static/src/css/test_cssfile3.css defined in bundle 'test_assetsbundle.bundle4' */ .rule4{color: green;} /* /test_assetsbundle/static/src/css/test_cssfile1.css defined in bundle 'test_assetsbundle.bundle4' */ .rule1{color: black;}.rule2{color: yellow;}.rule3{color: red;} /* /test_assetsbundle/static/src/css/test_cssfile2.css defined in bundle 'test_assetsbundle.bundle4' */ .rule4{color: blue;} ''' ) def test_28_js_after_js_in_irasset_wrong_path(self): self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.wrong_path', 'path': '/test_assetsbundle/static/src/js/test_jsfile4.js', }) self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.wrong_path', 'path': '/test_assetsbundle/static/src/js/test_jsfile1.js', 'target': '/test_assetsbundle/static/src/js/doesnt_exist.js', 'directive': 'after', }) view = self.make_asset_view('test_assetsbundle.wrong_path') with self.assertRaises(Exception) as cm: view._render() self.assertTrue( "test_assetsbundle/static/src/js/doesnt_exist.js not found" in cm.exception.message ) def test_29_js_after_js_in_irasset_glob(self): self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.manifest4', 'path': '/test_assetsbundle/static/src/*/**', 'target': '/test_assetsbundle/static/src/js/test_jsfile3.js', 'directive': 'after', }) view = self.make_asset_view('test_assetsbundle.manifest4') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest4')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.manifest4' */ var c=3;; /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.manifest4' */ var a=1;; /* /test_assetsbundle/static/src/js/test_jsfile2.js defined in bundle 'test_assetsbundle.manifest4' */ var b=2;; /* /test_assetsbundle/static/src/js/test_jsfile4.js defined in bundle 'test_assetsbundle.manifest4' */ var d=4; ''' ) def test_30_js_before_js_in_irasset_glob(self): self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.manifest4', 'path': '/test_assetsbundle/static/src/js/test_jsfile[124].js', 'target': '/test_assetsbundle/static/src/js/test_jsfile3.js', 'directive': 'before', }) view = self.make_asset_view('test_assetsbundle.manifest4') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.manifest4')], order='create_date DESC', limit=1) content = attach.raw.decode() self.assertStringEqual( content, ''' /* /test_assetsbundle/static/src/js/test_jsfile1.js defined in bundle 'test_assetsbundle.manifest4' */ var a=1;; /* /test_assetsbundle/static/src/js/test_jsfile2.js defined in bundle 'test_assetsbundle.manifest4' */ var b=2;; /* /test_assetsbundle/static/src/js/test_jsfile4.js defined in bundle 'test_assetsbundle.manifest4' */ var d=4;; /* /test_assetsbundle/static/src/js/test_jsfile3.js defined in bundle 'test_assetsbundle.manifest4' */ var c=3; ''' ) @mute_logger('odoo.addons.base.models.ir_asset') def test_31(self): path_to_dummy = '../../tests/dummy.js' me = pathlib.Path(__file__).parent.absolute() file_path = me.joinpath("..", path_to_dummy) # assuming me = test_assetsbundle/tests self.assertTrue(os.path.isfile(file_path)) self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.irassetsec', 'path': '/test_assetsbundle/%s' % path_to_dummy, }) view = self.make_asset_view('test_assetsbundle.irassetsec') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.irassetsec')], order='create_date DESC', limit=1) self.assertFalse(attach.exists()) @mute_logger('odoo.addons.base.models.ir_asset') def test_32(self): path_to_dummy = '../../tests/dummy.xml' me = pathlib.Path(__file__).parent.absolute() file_path = me.joinpath("..", path_to_dummy) # assuming me = test_assetsbundle/tests self.assertTrue(os.path.isfile(file_path)) self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.irassetsec', 'path': '/test_assetsbundle/%s' % path_to_dummy, }) files = self.env['ir.asset']._get_asset_paths('test_assetsbundle.irassetsec', addons=self.installed_modules, xml=False) self.assertFalse(files) def test_33(self): self.manifests['notinstalled_module'] = { 'name': 'notinstalled_module', 'depends': ['test_assetsbundle'], 'addons_path': pathlib.Path(__file__).resolve().parent, } self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.irassetsec', 'path': '/notinstalled_module/somejsfile.js', }) view = self.make_asset_view('test_assetsbundle.irassetsec') with self.assertRaises(QWebException) as cm: view._render() self.assertTrue('Unallowed to fetch files from addon notinstalled_module' in cm.exception.message) def test_33bis_notinstalled_not_in_manifests(self): self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.irassetsec', 'path': '/notinstalled_module/somejsfile.js', }) self.make_asset_view('test_assetsbundle.irassetsec') attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.irassetsec')], order='create_date DESC', limit=1) self.assertFalse(attach.exists()) @mute_logger('odoo.addons.base.models.ir_asset') def test_34(self): self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.irassetsec', 'path': '/test_assetsbundle/__manifest__.py', }) view = self.make_asset_view('test_assetsbundle.irassetsec') view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.irassetsec')], order='create_date DESC', limit=1) self.assertFalse(attach.exists()) @mute_logger('odoo.addons.base.models.ir_asset') def test_35(self): self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.irassetsec', 'path': '/test_assetsbundle/data/ir_asset.xml', }) files = self.env['ir.asset']._get_asset_paths('test_assetsbundle.irassetsec', addons=self.installed_modules, xml=False) self.assertFalse(files) def test_36(self): self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.irassetsec', 'path': '/test_assetsbundle/static/accessible.xml', }) files = self.env['ir.asset']._get_asset_paths('test_assetsbundle.irassetsec', addons=self.installed_modules, xml=False) self.assertEqual(len(files), 1) self.assertTrue('test_assetsbundle/static/accessible.xml' in files[0][0]) def test_37_path_can_be_an_attachment(self): scss_code = base64.b64encode(b""" .my_div { &.subdiv { color: blue; } } """) self.env['ir.attachment'].create({ 'name': 'my custom scss', 'mimetype': 'text/scss', 'type': 'binary', 'url': 'test_assetsbundle/my_style_attach.scss', 'datas': scss_code }) self.env['ir.asset'].create({ 'name': '1', 'bundle': 'test_assetsbundle.irasset_custom_attach', 'path': 'test_assetsbundle/my_style_attach.scss', }) view = self.make_asset_view('test_assetsbundle.irasset_custom_attach', {'t-css': True}) view._render() attach = self.env['ir.attachment'].search([('name', 'ilike', 'test_assetsbundle.irasset_custom_attach')], order='create_date DESC', limit=1) content = attach.raw.decode() # The scss should be compiled self.assertStringEqual( content, """ /* test_assetsbundle/my_style_attach.scss defined in bundle 'test_assetsbundle.irasset_custom_attach' */ .my_div.subdiv{color: blue;} """ )
42.70882
80,378
3,670
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import tagged from odoo.tests.common import TransactionCase from odoo.tools import URL_RE, ODOO_MODULE_RE @tagged('post_install', '-at_install') class TestJsTranspiler(TransactionCase): def test_correct_ODOO_MODULE_RE(self): cases = [ '// @odoo-module', '//@odoo-module', '/* @odoo-module', '/** @odoo-module', '/*@odoo-module', '/**@odoo-module', '// @odoo-module alias=web.test', '/* @odoo-module alias=web.test', '/** @odoo-module alias=web.test', '/** @odoo-module alias=web.test**/', '/* @odoo-module alias=web.test ', '/* @odoo-module alias=web.test default=false', '/* @odoo-module alias=web.test default=false ', '/* @odoo-module alias=web.test default=false**/', ] for case in cases: assert ODOO_MODULE_RE.match(case), "URL_RE is failing... >%s<" % case if "alias" in case: assert ODOO_MODULE_RE.match(case).groupdict().get('alias'), "URL_RE is failing for alias... >%s<" % case assert ODOO_MODULE_RE.match(case).groupdict().get('alias') == "web.test", "URL_RE does not get the right alias for ... >%s<" % case if "default" in case: assert ODOO_MODULE_RE.match(case).groupdict().get('default'), "URL_RE is failing for default... >%s<" % case assert ODOO_MODULE_RE.match(case).groupdict().get('default') == "false", "URL_RE does not get the right default for ... >%s<" % case def test_incorrect_ODOO_MODULE_RE(self): cases = [ '/* @odoo-module alias = web.test ', '/* @odoo-module alias= web.test', '/* @odoo-module alias = web.test default=false' ] for case in cases: assert not ODOO_MODULE_RE.match(case).groupdict().get('alias'), "URL_RE should fail because of too much spaces but didn't... >%s<" % case cases = [ '// @odoo-modulealias=web.test', '/* @odoo-module alias=web.testdefault=false', ] for case in cases: if "alias" in case and "default" in case: assert \ not ODOO_MODULE_RE.match(case).groupdict().get('alias') \ or \ not ODOO_MODULE_RE.match(case).groupdict().get('default'), "URL_RE should fail for alias and default... >%s<" % case elif "alias" in case: assert not ODOO_MODULE_RE.match(case).groupdict().get('alias'), "URL_RE should fail for alias... >%s<" % case def test_correct_URL_RE(self): cases = [ 'web/static/src/js/file.js', '/web/static/src/js/file.js', '/web/other/static/src/js/file.js', '/web/other/static/src/file.js', '/web/other/static/tests/file.js', '/web/other/static/src/another/and/file.js', '/web/other-o/static/src/another/and/file.js', '/web-o/other-o/static/src/another/and/file.js', ] for case in cases: assert URL_RE.fullmatch(case), "URL RE failed... %s" % case def test_incorrect_URL_RE(self): cases = [ 'web/static/js/src/file.js', # src after js 'web/static/js/file.js', # no src or tests folder ] for case in cases: assert not URL_RE.fullmatch(case), "URL RE should have failed... %s" % case
43.690476
3,670
11,381
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import tagged from odoo.tests.common import TransactionCase from odoo.tools import transpile_javascript @tagged('post_install', '-at_install') class TestJsTranspiler(TransactionCase): maxDiff = None def test_01_alias(self): input_content = """/** @odoo-module alias=test_assetsbundle.Alias **/""" result = transpile_javascript("/test_assetsbundle/static/src/alias.js", input_content) expected_result = """odoo.define('@test_assetsbundle/alias', async function (require) { 'use strict'; let __exports = {}; /** @odoo-module alias=test_assetsbundle.Alias **/ return __exports; }); odoo.define(`test_assetsbundle.Alias`, async function(require) { return require('@test_assetsbundle/alias')[Symbol.for("default")]; }); """ self.assertEqual(result, expected_result) def test_02_default(self): input_content = """/** @odoo-module alias=test_assetsbundle.Alias default=False **/""" result = transpile_javascript("/test_assetsbundle/static/src/alias.js", input_content) expected_result = """odoo.define('@test_assetsbundle/alias', async function (require) { 'use strict'; let __exports = {}; /** @odoo-module alias=test_assetsbundle.Alias default=False **/ return __exports; }); odoo.define(`test_assetsbundle.Alias`, async function(require) { return require('@test_assetsbundle/alias'); }); """ self.assertEqual(result, expected_result) input_content = """/** @odoo-module alias=test_assetsbundle.Alias default=0 **/""" result = transpile_javascript("/test_assetsbundle/static/src/alias.js", input_content) expected_result = """odoo.define('@test_assetsbundle/alias', async function (require) { 'use strict'; let __exports = {}; /** @odoo-module alias=test_assetsbundle.Alias default=0 **/ return __exports; }); odoo.define(`test_assetsbundle.Alias`, async function(require) { return require('@test_assetsbundle/alias'); }); """ self.assertEqual(result, expected_result) input_content = """/** @odoo-module alias=test_assetsbundle.Alias default=false **/""" result = transpile_javascript("/test_assetsbundle/static/src/alias.js", input_content) expected_result = """odoo.define('@test_assetsbundle/alias', async function (require) { 'use strict'; let __exports = {}; /** @odoo-module alias=test_assetsbundle.Alias default=false **/ return __exports; }); odoo.define(`test_assetsbundle.Alias`, async function(require) { return require('@test_assetsbundle/alias'); }); """ self.assertEqual(result, expected_result) def test_03_classes(self): input_content = """export default class Nice {} class Vehicule {} export class Car extends Vehicule {} export class Boat extends Vehicule {} export const Ferrari = class Ferrari extends Car {}; """ result = transpile_javascript("/test_assetsbundle/static/src/classes.js", input_content) expected_result = """odoo.define('@test_assetsbundle/classes', async function (require) { 'use strict'; let __exports = {}; const Nice = __exports[Symbol.for("default")] = class Nice {} class Vehicule {} const Car = __exports.Car = class Car extends Vehicule {} const Boat = __exports.Boat = class Boat extends Vehicule {} const Ferrari = __exports.Ferrari = class Ferrari extends Car {}; return __exports; }); """ self.assertEqual(result, expected_result) def test_04_comments(self): input_content = """/** * This is a comment */ /** * This isn't a string */ export class Test { // This is a comment in a class } /* cool comment */ const a = 5; /* another cool comment */ const b = 5; // hello // another one const y = "this is a /* nice string and should be kept */"; const z = "this is a /* nice string and should be kept"; export const x = "this is a // nice string and should be kept"; const w = "this is a */ nice string and should be kept"; // This isn't a string /* comments */ const aaa = "keep!"; /* comments */ """ result = transpile_javascript("/test_assetsbundle/static/src/comments.js", input_content) expected_result = """odoo.define('@test_assetsbundle/comments', async function (require) { 'use strict'; let __exports = {}; /** * This is a comment */ /** * This isn't a string */ const Test = __exports.Test = class Test { // This is a comment in a class } /* cool comment */ const a = 5; /* another cool comment */ const b = 5; // hello // another one const y = "this is a /* nice string and should be kept */"; const z = "this is a /* nice string and should be kept"; const x = __exports.x = "this is a // nice string and should be kept"; const w = "this is a */ nice string and should be kept"; // This isn't a string /* comments */ const aaa = "keep!"; /* comments */ return __exports; }); """ self.assertEqual(result, expected_result) def test_05_functions(self): input_content = """export function sayHello() { console.log("Hello"); } export function sayHelloWorld() { console.log("Hello world"); } export async function sayAsyncHello() { console.log("Hello Async"); } export default function sayHelloDefault() { console.log("Hello Default"); } """ result = transpile_javascript("/test_assetsbundle/static/src/functions.js", input_content) expected_result = """odoo.define('@test_assetsbundle/functions', async function (require) { 'use strict'; let __exports = {}; __exports.sayHello = sayHello; function sayHello() { console.log("Hello"); } __exports.sayHelloWorld = sayHelloWorld; function sayHelloWorld() { console.log("Hello world"); } __exports.sayAsyncHello = sayAsyncHello; async function sayAsyncHello() { console.log("Hello Async"); } __exports[Symbol.for("default")] = sayHelloDefault; function sayHelloDefault() { console.log("Hello Default"); } return __exports; }); """ self.assertEqual(result, expected_result) def test_06_import(self): input_content = """/** * import { Dialog, Notification } from "../src/Dialog"; */ import { Line1 } from "../src/Dialog"; import { Line2, Notification } from "../src/Dialog"; import { Line3, Notification } from "Dialog"; import { Line4, Notification } from "@tests/Dialog"; import { Line5, Notification } from "./Dialog"; import { Line6, Notification } from '../src/Dialog' import Line7 from "../src/Dialog"; import Line8 from '../src/Dialog'; import Line9 from "test.Dialog"; import { Line10, Notification } from 'test.Dialog2'; import * as Line11 from "test.Dialog"; import "test.Dialog"; import Line12 from "@test.Dialog"; //HELLO import {Line13} from "@test.Dialog" //HELLO const test = `import { Line14, Notification } from "../src/Dialog";` import Line15 from "test/Dialog"; import Line16 from "test.Dialog.error"; """ result = transpile_javascript("/test_assetsbundle/static/src/import.js", input_content) expected_result = """odoo.define('@test_assetsbundle/import', async function (require) { 'use strict'; let __exports = {}; /** * import { Dialog, Notification } from "../src/Dialog"; */ const { Line1 } = require("@test_assetsbundle/Dialog"); const { Line2, Notification } = require("@test_assetsbundle/Dialog"); const { Line3, Notification } = require("Dialog"); const { Line4, Notification } = require("@tests/Dialog"); const { Line5, Notification } = require("@test_assetsbundle/Dialog"); const { Line6, Notification } = require("@test_assetsbundle/Dialog") const Line7 = require("@test_assetsbundle/Dialog")[Symbol.for("default")]; const Line8 = require("@test_assetsbundle/Dialog")[Symbol.for("default")]; const Line9 = require("test.Dialog"); const { Line10, Notification } = require('test.Dialog2'); const Line11 = require("test.Dialog"); require("test.Dialog"); const Line12 = require("@test.Dialog")[Symbol.for("default")]; //HELLO const {Line13} = require("@test.Dialog") //HELLO const test = `import { Line14, Notification } from "../src/Dialog";` const Line15 = require("test/Dialog"); const Line16 = require("test.Dialog.error"); return __exports; }); """ self.assertEqual(result, expected_result) def test_07_index(self): input_content = """export const a = 5; import * as b from "@tests/dir"; import c from "@tests/dir/index/"; import d from "@tests";""" result = transpile_javascript("/test_assetsbundle/static/src/index.js", input_content) expected_result = """odoo.define('@test_assetsbundle', async function (require) { 'use strict'; let __exports = {}; const a = __exports.a = 5; const b = require("@tests/dir"); const c = require("@tests/dir")[Symbol.for("default")]; const d = require("@tests")[Symbol.for("default")]; return __exports; }); """ self.assertEqual(result, expected_result) def test_08_list(self): input_content = """export {a, b}; export {a as aa, b, c as cc}; export {a, aReallyVeryLongNameWithSomeExtra} export { a, aReallyVeryLongNameWithSomeExtra, } export { a, aReallyVeryLongNameWithSomeExtra } export {a, aReallyVeryLongNameWithSomeExtra /* a comment must not cause catastrophic backtracking, even if not supported */}; export {c, d} from "@tests/Dialog"; export {e} from "../src/Dialog"; export {c as cc, d, e as ee} from "@tests/Dialog"; export * from "@tests/Dialog"; """ result = transpile_javascript("/test_assetsbundle/static/src/list.js", input_content) expected_result = """odoo.define('@test_assetsbundle/list', async function (require) { 'use strict'; let __exports = {}; Object.assign(__exports, {a, b}); Object.assign(__exports, {aa: a, b, cc: c}); Object.assign(__exports, {a, aReallyVeryLongNameWithSomeExtra}) Object.assign(__exports, { a, aReallyVeryLongNameWithSomeExtra, }) Object.assign(__exports, { a, aReallyVeryLongNameWithSomeExtra }) export {a, aReallyVeryLongNameWithSomeExtra /* a comment must not cause catastrophic backtracking, even if not supported */}; {const {c, d} = require("@tests/Dialog");Object.assign(__exports, {c, d})}; {const {e} = require("@test_assetsbundle/Dialog");Object.assign(__exports, {e})}; {const {c, d, e} = require("@tests/Dialog");Object.assign(__exports, {cc: c, d, ee: e})}; Object.assign(__exports, require("@tests/Dialog")); return __exports; }); """ self.assertEqual(result, expected_result) def test_09_variables(self): input_content = """export const v = 5; const a = 12; const b = 15; export { a, b }; export default 100; export default a; """ result = transpile_javascript("/test_assetsbundle/static/src/variables.js", input_content) expected_result = """odoo.define('@test_assetsbundle/variables', async function (require) { 'use strict'; let __exports = {}; const v = __exports.v = 5; const a = 12; const b = 15; Object.assign(__exports, { a, b }); __exports[Symbol.for("default")] = 100; __exports[Symbol.for("default")] = a; return __exports; }); """ self.assertEqual(result, expected_result)
27.227273
11,381
436
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import SUPERUSER_ID from odoo.http import Controller, request, route class TestAssetsBundleController(Controller): @route('/test_assetsbundle/js', type='http', auth='user') def bundle(self): env = request.env(user=SUPERUSER_ID) return env['ir.ui.view']._render_template('test_assetsbundle.template1')
39.636364
436
789
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Test API', 'version': '1.0', 'category': 'Hidden/Tests', 'description': """A module to test the API.""", 'depends': ['base', 'web', 'web_tour'], 'installable': True, 'auto_install': False, 'data': [ 'security/ir.model.access.csv', 'security/test_new_api_security.xml', 'views/test_new_api_views.xml', 'data/test_new_api_data.xml', ], 'demo': [ ], 'assets': { 'web.assets_tests': [ # inside . 'test_new_api/static/tests/tours/constraint.js', # inside . 'test_new_api/static/tests/tours/x2many.js', ], }, 'license': 'LGPL-3', }
27.206897
789
1,261
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.tests.common import TransactionCase class Many2manyCase(TransactionCase): def setUp(self): super().setUp() self.ship = self.env['test_new_api.ship'].create({'name': 'Colombus'}) # the ship contains one prisoner self.env['test_new_api.prisoner'].create({ 'name': 'Brian', 'ship_ids': self.ship.ids, }) # the ship contains one pirate self.blackbeard = self.env['test_new_api.pirate'].create({ 'name': 'Black Beard', 'ship_ids': self.ship.ids, }) self.redbeard = self.env['test_new_api.pirate'].create({'name': 'Red Beard'}) def test_not_in_relation(self): pirates = self.env['test_new_api.pirate'].search([('ship_ids', 'not in', self.ship.ids)]) self.assertEqual(len(pirates), 1) self.assertEqual(pirates, self.redbeard) def test_not_in_relation_as_query(self): # ship_ids is a Query object ship_ids = self.env['test_new_api.ship']._search([('name', '=', 'Colombus')]) pirates = self.env['test_new_api.pirate'].search([('ship_ids', 'not in', ship_ids)]) self.assertEqual(len(pirates), 1) self.assertEqual(pirates, self.redbeard)
40.677419
1,261
1,984
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.tests from odoo.tools import mute_logger from odoo.addons.base.tests.common import HttpCaseWithUserDemo @odoo.tests.common.tagged('post_install', '-at_install') class TestUi(HttpCaseWithUserDemo): def test_01_admin_widget_x2many(self): # FIXME: breaks if too many children of base.menu_tests # This tour turns out to be quite sensible to the number of items in # the base.menu_tests: it's specifically sequenced to be lower (after) # the default, but doesn't account for the fact that it could # "fall off" into the "o_extra_menu_items" section if the window is # too small or there are too many items preceding it in the tests menu self.start_tour("/web#action=test_new_api.action_discussions", 'widget_x2many', step_delay=100, login="admin", timeout=120) @odoo.tests.tagged('-at_install', 'post_install') class TestUiTranslation(odoo.tests.HttpCase): @mute_logger('odoo.sql_db', 'odoo.http') def test_01_sql_constraints(self): # Raise an SQL constraint and test the message self.env['res.lang']._activate_lang('fr_FR') self.env.ref('base.module_test_new_api')._update_translations(['fr_FR']) constraint = self.env.ref('test_new_api.constraint_test_new_api_category_positive_color') message = constraint.with_context(lang='fr_FR').message self.assertEqual(message, "La couleur doit être une valeur positive !") # TODO: make the test work with French translations. As the transaction # is rollbacked at insert and a new cursor is opened, can not test that # the message is translated (_load_module_terms is also) rollbacked. # Test individually the external id and loading of translation. self.start_tour("/web#action=test_new_api.action_categories", 'sql_constaint', login="admin")
48.365854
1,983
25,128
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.models import MetaModel from odoo.tests import common from odoo.addons.base.models.ir_model import model_xmlid, field_xmlid, selection_xmlid def get_model_name(cls): name = cls._name if not name: [name] = cls._inherit if isinstance(cls._inherit, list) else [cls._inherit] assert isinstance(name, str) return name class TestReflection(common.TransactionCase): """ Test the reflection into 'ir.model', 'ir.model.fields', etc. """ def assertModelXID(self, record): """ Check the XML id of the given 'ir.model' record. """ xid = model_xmlid('test_new_api', record.model) self.assertEqual(record, self.env.ref(xid)) def assertFieldXID(self, record): """ Check the XML id of the given 'ir.model.fields' record. """ xid = field_xmlid('test_new_api', record.model, record.name) self.assertEqual(record, self.env.ref(xid)) def assertSelectionXID(self, record): """ Check the XML id of the given 'ir.model.fields.selection' record. """ xid = selection_xmlid('test_new_api', record.field_id.model, record.field_id.name, record.value) self.assertEqual(record, self.env.ref(xid)) def test_models_fields(self): """ check that all models and fields are reflected as expected. """ # retrieve the models defined in this module, and check them model_names = { get_model_name(cls) for cls in MetaModel.module_to_models['test_new_api'] } ir_models = self.env['ir.model'].search([('model', 'in', list(model_names))]) self.assertEqual(len(ir_models), len(model_names)) for ir_model in ir_models: with self.subTest(model=ir_model.model): model = self.env[ir_model.model] self.assertModelXID(ir_model) self.assertEqual(ir_model.name, model._description or False) self.assertEqual(ir_model.state, 'manual' if model._custom else 'base') self.assertEqual(ir_model.transient, bool(model._transient)) self.assertItemsEqual(ir_model.mapped('field_id.name'), list(model._fields)) for ir_field in ir_model.field_id: with self.subTest(field=ir_field.name): field = model._fields[ir_field.name] self.assertFieldXID(ir_field) self.assertEqual(ir_field.model, field.model_name) self.assertEqual(ir_field.field_description, field.string) self.assertEqual(ir_field.help, field.help or False) self.assertEqual(ir_field.ttype, field.type) self.assertEqual(ir_field.state, 'manual' if field.manual else 'base') self.assertEqual(ir_field.index, bool(field.index)) self.assertEqual(ir_field.store, bool(field.store)) self.assertEqual(ir_field.copied, bool(field.copy)) self.assertEqual(ir_field.related, field.related or False) self.assertEqual(ir_field.readonly, bool(field.readonly)) self.assertEqual(ir_field.required, bool(field.required)) self.assertEqual(ir_field.selectable, bool(field.search or field.store)) self.assertEqual(ir_field.translate, bool(field.translate)) if field.relational: self.assertEqual(ir_field.relation, field.comodel_name) if field.type == 'one2many' and field.store: self.assertEqual(ir_field.relation_field, field.inverse_name) if field.type == 'many2many' and field.store: self.assertEqual(ir_field.relation_table, field.relation) self.assertEqual(ir_field.column1, field.column1) self.assertEqual(ir_field.column2, field.column2) relation = self.env['ir.model.relation'].search([('name', '=', field.relation)]) self.assertTrue(relation) self.assertIn(relation.model.model, [field.model_name, field.comodel_name]) if field.type == 'selection': selection = [(sel.value, sel.name) for sel in ir_field.selection_ids] if isinstance(field.selection, list): self.assertEqual(selection, field.selection) else: self.assertEqual(selection, []) for sel in ir_field.selection_ids: self.assertSelectionXID(sel) field_description = field.get_description(self.env) if field.type in ('many2many', 'one2many'): self.assertFalse(field_description['sortable']) elif field.store and field.column_type: self.assertTrue(field_description['sortable']) class TestSchema(common.TransactionCase): def get_table_data(self, tablename): query = ''' SELECT table_catalog, table_schema, table_name, table_type, user_defined_type_catalog, user_defined_type_schema, user_defined_type_name, is_insertable_into, is_typed FROM information_schema.tables WHERE table_name=%s ''' self.cr.execute(query, [tablename]) return self.cr.dictfetchone() def get_columns_data(self, tablename): query = ''' SELECT table_catalog, table_schema, table_name, column_name, column_default, data_type, is_nullable, is_updatable, character_maximum_length, numeric_precision, numeric_precision_radix, numeric_scale, datetime_precision, udt_catalog, udt_schema, udt_name FROM information_schema.columns WHERE table_name=%s ''' self.cr.execute(query, [tablename]) return {row['column_name']: row for row in self.cr.dictfetchall()} def get_foreign_keys(self, tablename): query = ''' SELECT a.table_name, a.column_name, b.table_name, b.column_name, c.delete_rule FROM information_schema.referential_constraints c, information_schema.key_column_usage a, information_schema.constraint_column_usage b WHERE a.constraint_schema=c.constraint_schema AND a.constraint_name=c.constraint_name AND b.constraint_schema=c.constraint_schema AND b.constraint_name=c.constraint_name AND a.table_name=%s ''' self.cr.execute(query, [tablename]) return self.cr.fetchall() def test_00_table(self): """ check the database schema of a model """ model = self.env['test_new_api.foo'] self.assertEqual(model._table, 'test_new_api_foo') # retrieve schema data about that table table_data = self.get_table_data('test_new_api_foo') self.assertEqual(table_data, { 'is_insertable_into': u'YES', 'is_typed': u'NO', 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_foo', 'table_schema': u'public', 'table_type': u'BASE TABLE', 'user_defined_type_catalog': None, 'user_defined_type_name': None, 'user_defined_type_schema': None, }) # retrieve schema data about the table's columns columns_data = self.get_columns_data('test_new_api_foo') self.assertEqual(set(columns_data), {'id', 'create_date', 'create_uid', 'write_date', 'write_uid', 'name', 'value1', 'value2', 'text'}) # retrieve schema data about the table's foreign keys foreign_keys = self.get_foreign_keys('test_new_api_foo') self.assertItemsEqual(foreign_keys, [ ('test_new_api_foo', 'create_uid', 'res_users', 'id', 'SET NULL'), ('test_new_api_foo', 'write_uid', 'res_users', 'id', 'SET NULL'), ]) def test_10_boolean(self): """ check the database representation of a boolean field """ model = self.env['test_new_api.message'] columns_data = self.get_columns_data(model._table) self.assertEqual(columns_data['important'], { 'character_maximum_length': None, 'column_default': None, 'column_name': u'important', 'data_type': u'boolean', 'datetime_precision': None, 'is_nullable': u'YES', 'is_updatable': u'YES', 'numeric_precision': None, 'numeric_precision_radix': None, 'numeric_scale': None, 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_message', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'bool', 'udt_schema': u'pg_catalog', }) def test_10_integer(self): """ check the database representation of an integer field """ model = self.env['test_new_api.category'] columns_data = self.get_columns_data(model._table) self.assertEqual(columns_data['color'], { 'character_maximum_length': None, 'column_default': None, 'column_name': u'color', 'data_type': u'integer', 'datetime_precision': None, 'is_nullable': u'YES', 'is_updatable': u'YES', 'numeric_precision': 32, 'numeric_precision_radix': 2, 'numeric_scale': 0, 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_category', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'int4', 'udt_schema': u'pg_catalog', }) def test_10_float(self): """ check the database representation of a float field """ model = self.env['test_new_api.mixed'] columns_data = self.get_columns_data(model._table) self.assertEqual(columns_data['number'], { 'character_maximum_length': None, 'column_default': None, 'column_name': u'number', 'data_type': u'numeric', 'datetime_precision': None, 'is_nullable': u'YES', 'is_updatable': u'YES', 'numeric_precision': None, 'numeric_precision_radix': 10, 'numeric_scale': None, 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_mixed', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'numeric', 'udt_schema': u'pg_catalog', }) def test_10_monetary(self): """ check the database representation of a monetary field """ model = self.env['test_new_api.mixed'] columns_data = self.get_columns_data(model._table) self.assertEqual(columns_data['amount'], { 'character_maximum_length': None, 'column_default': None, 'column_name': u'amount', 'data_type': u'numeric', 'datetime_precision': None, 'is_nullable': u'YES', 'is_updatable': u'YES', 'numeric_precision': None, 'numeric_precision_radix': 10, 'numeric_scale': None, 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_mixed', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'numeric', 'udt_schema': u'pg_catalog', }) def test_10_char(self): """ check the database representation of a char field """ model = self.env['res.country'] self.assertFalse(type(model).code.required) self.assertEqual(type(model).code.size, 2) columns_data = self.get_columns_data(model._table) self.assertEqual(columns_data['code'], { 'character_maximum_length': 2, 'column_default': None, 'column_name': u'code', 'data_type': u'character varying', 'datetime_precision': None, 'is_nullable': u'YES', 'is_updatable': u'YES', 'numeric_precision': None, 'numeric_precision_radix': None, 'numeric_scale': None, 'table_catalog': self.cr.dbname, 'table_name': u'res_country', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'varchar', 'udt_schema': u'pg_catalog', }) model = self.env['test_new_api.message'] self.assertFalse(type(model).name.required) columns_data = self.get_columns_data(model._table) self.assertEqual(columns_data['name'], { 'character_maximum_length': None, 'column_default': None, 'column_name': u'name', 'data_type': u'character varying', 'datetime_precision': None, 'is_nullable': u'YES', 'is_updatable': u'YES', 'numeric_precision': None, 'numeric_precision_radix': None, 'numeric_scale': None, 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_message', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'varchar', 'udt_schema': u'pg_catalog', }) model = self.env['test_new_api.category'] self.assertTrue(type(model).name.required) columns_data = self.get_columns_data(model._table) self.assertEqual(columns_data['name'], { 'character_maximum_length': None, 'column_default': None, 'column_name': u'name', 'data_type': u'character varying', 'datetime_precision': None, 'is_nullable': u'NO', 'is_updatable': u'YES', 'numeric_precision': None, 'numeric_precision_radix': None, 'numeric_scale': None, 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_category', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'varchar', 'udt_schema': u'pg_catalog', }) def test_10_text(self): """ check the database representation of a text field """ model = self.env['test_new_api.message'] columns_data = self.get_columns_data(model._table) self.assertEqual(columns_data['body'], { 'character_maximum_length': None, 'column_default': None, 'column_name': u'body', 'data_type': u'text', 'datetime_precision': None, 'is_nullable': u'YES', 'is_updatable': u'YES', 'numeric_precision': None, 'numeric_precision_radix': None, 'numeric_scale': None, 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_message', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'text', 'udt_schema': u'pg_catalog', }) def test_10_html(self): """ check the database representation of an html field """ model = self.env['test_new_api.mixed'] columns_data = self.get_columns_data(model._table) self.assertEqual(columns_data['comment1'], { 'character_maximum_length': None, 'column_default': None, 'column_name': u'comment1', 'data_type': u'text', 'datetime_precision': None, 'is_nullable': u'YES', 'is_updatable': u'YES', 'numeric_precision': None, 'numeric_precision_radix': None, 'numeric_scale': None, 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_mixed', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'text', 'udt_schema': u'pg_catalog', }) def test_10_date(self): """ check the database representation of a date field """ model = self.env['test_new_api.mixed'] columns_data = self.get_columns_data(model._table) self.assertEqual(columns_data['date'], { 'character_maximum_length': None, 'column_default': None, 'column_name': u'date', 'data_type': u'date', 'datetime_precision': 0, 'is_nullable': u'YES', 'is_updatable': u'YES', 'numeric_precision': None, 'numeric_precision_radix': None, 'numeric_scale': None, 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_mixed', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'date', 'udt_schema': u'pg_catalog', }) def test_10_datetime(self): """ check the database representation of a datetime field """ model = self.env['ir.property'] columns_data = self.get_columns_data(model._table) self.assertEqual(columns_data['value_datetime'], { 'character_maximum_length': None, 'column_default': None, 'column_name': u'value_datetime', 'data_type': u'timestamp without time zone', 'datetime_precision': 6, 'is_nullable': u'YES', 'is_updatable': u'YES', 'numeric_precision': None, 'numeric_precision_radix': None, 'numeric_scale': None, 'table_catalog': self.cr.dbname, 'table_name': u'ir_property', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'timestamp', 'udt_schema': u'pg_catalog', }) model = self.env['test_new_api.mixed'] columns_data = self.get_columns_data(model._table) self.assertEqual(columns_data['create_date'], { 'character_maximum_length': None, 'column_default': None, 'column_name': u'create_date', 'data_type': u'timestamp without time zone', 'datetime_precision': 6, 'is_nullable': u'YES', 'is_updatable': u'YES', 'numeric_precision': None, 'numeric_precision_radix': None, 'numeric_scale': None, 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_mixed', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'timestamp', 'udt_schema': u'pg_catalog', }) def test_10_selection(self): """ check the database representation of a selection field """ model = self.env['test_new_api.mixed'] columns_data = self.get_columns_data(model._table) self.assertEqual(columns_data['lang'], { 'character_maximum_length': None, 'column_default': None, 'column_name': u'lang', 'data_type': u'character varying', 'datetime_precision': None, 'is_nullable': u'YES', 'is_updatable': u'YES', 'numeric_precision': None, 'numeric_precision_radix': None, 'numeric_scale': None, 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_mixed', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'varchar', 'udt_schema': u'pg_catalog', }) def test_10_reference(self): """ check the database representation of a reference field """ model = self.env['test_new_api.mixed'] columns_data = self.get_columns_data(model._table) self.assertEqual(columns_data['reference'], { 'character_maximum_length': None, 'column_default': None, 'column_name': u'reference', 'data_type': u'character varying', 'datetime_precision': None, 'is_nullable': u'YES', 'is_updatable': u'YES', 'numeric_precision': None, 'numeric_precision_radix': None, 'numeric_scale': None, 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_mixed', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'varchar', 'udt_schema': u'pg_catalog', }) def test_10_many2one(self): """ check the database representation of a many2one field """ model = self.env['test_new_api.mixed'] columns_data = self.get_columns_data(model._table) self.assertEqual(columns_data['currency_id'], { 'character_maximum_length': None, 'column_default': None, 'column_name': u'currency_id', 'data_type': u'integer', 'datetime_precision': None, 'is_nullable': u'YES', 'is_updatable': u'YES', 'numeric_precision': 32, 'numeric_precision_radix': 2, 'numeric_scale': 0, 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_mixed', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'int4', 'udt_schema': u'pg_catalog', }) foreign_keys = self.get_foreign_keys(model._table) self.assertIn( ('test_new_api_mixed', 'currency_id', 'res_currency', 'id', 'SET NULL'), foreign_keys, ) def test_10_many2many(self): """ check the database representation of a many2many field """ model = self.env['test_new_api.discussion'] field = type(model).categories comodel = self.env[field.comodel_name] self.assertTrue(field.relation) self.assertTrue(field.column1) self.assertTrue(field.column2) columns_data = self.get_columns_data(model._table) self.assertNotIn('categories', columns_data) table_data = self.get_table_data(field.relation) self.assertEqual(table_data, { 'is_insertable_into': u'YES', 'is_typed': u'NO', 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_discussion_category', 'table_schema': u'public', 'table_type': u'BASE TABLE', 'user_defined_type_catalog': None, 'user_defined_type_name': None, 'user_defined_type_schema': None, }) columns_data = self.get_columns_data(field.relation) self.assertEqual(columns_data, { field.column1: { 'character_maximum_length': None, 'column_default': None, 'column_name': u'discussion', 'data_type': u'integer', 'datetime_precision': None, 'is_nullable': u'NO', 'is_updatable': u'YES', 'numeric_precision': 32, 'numeric_precision_radix': 2, 'numeric_scale': 0, 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_discussion_category', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'int4', 'udt_schema': u'pg_catalog', }, field.column2: { 'character_maximum_length': None, 'column_default': None, 'column_name': u'category', 'data_type': u'integer', 'datetime_precision': None, 'is_nullable': u'NO', 'is_updatable': u'YES', 'numeric_precision': 32, 'numeric_precision_radix': 2, 'numeric_scale': 0, 'table_catalog': self.cr.dbname, 'table_name': u'test_new_api_discussion_category', 'table_schema': u'public', 'udt_catalog': self.cr.dbname, 'udt_name': u'int4', 'udt_schema': u'pg_catalog' }, }) foreign_keys = self.get_foreign_keys(field.relation) self.assertItemsEqual(foreign_keys, [ (field.relation, field.column1, model._table, 'id', 'CASCADE'), (field.relation, field.column2, comodel._table, 'id', 'CASCADE'), ])
43.398964
25,128
1,669
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.tests import common class test_domain(common.TransactionCase): def setUp(self): super(test_domain, self).setUp() self.bool = self.env['domain.bool'] def test_00_test_bool_undefined(self): """ Check that undefined/empty values in database is equal to False and different of True """ # Add a new boolean column after that some rows/tuples has been added (with data) # Existing rows/tuples will be undefined/empty self.env['ir.model.fields'].create({ 'name': 'x_bool_new_undefined', 'model_id': self.env.ref('test_new_api.model_domain_bool').id, 'field_description': 'A new boolean column', 'ttype': 'boolean' }) self.env.ref('test_new_api.bool_3').write({'x_bool_new_undefined': True}) self.env.ref('test_new_api.bool_4').write({'x_bool_new_undefined': False}) model = self.bool all_bool = model.search([]) for f in ['bool_true', 'bool_false', 'bool_undefined', 'x_bool_new_undefined']: eq_1 = model.search([(f, '=', False)]) neq_1 = model.search([(f, '!=', True)]) self.assertEqual(eq_1, neq_1, '`= False` (%s) <> `!= True` (%s) ' % (len(eq_1), len(neq_1))) eq_2 = model.search([(f, '=', True)]) neq_2 = model.search([(f, '!=', False)]) self.assertEqual(eq_2, neq_2, '`= True` (%s) <> `!= False` (%s) ' % (len(eq_2), len(neq_2))) self.assertEqual(eq_1+eq_2, all_bool, 'True + False != all') self.assertEqual(neq_1+neq_2, all_bool, 'not True + not False != all')
40.707317
1,669
2,166
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.tests import common class TestFloatExport(common.TransactionCase): def get_converter(self, name): FloatField = self.env['ir.qweb.field.float'] _, precision = self.env['decimal.precision.test']._fields[name].get_digits(self.env) or (None, None) def converter(value, options=None): record = self.env['decimal.precision.test'].new({name: value}) return FloatField.record_to_html(record, name, options or {}) return converter def test_basic_float(self): converter = self.get_converter('float') self.assertEqual( converter(42.0), "42.0") self.assertEqual( converter(42.12345), "42.12345") converter = self.get_converter('float_2') self.assertEqual( converter(42.0), "42.00") self.assertEqual( converter(42.12345), "42.12") converter = self.get_converter('float') # don't use float_4 because the field value 42.12345 is already orm converted to 42.1235 self.assertEqual( converter(42.0, {'precision': 4}), '42.0000') self.assertEqual( converter(42.12345, {'precision': 4}), '42.1235') def test_precision_domain(self): self.env['decimal.precision'].create({ 'name': 'A', 'digits': 2, }) self.env['decimal.precision'].create({ 'name': 'B', 'digits': 6, }) converter = self.get_converter('float') self.assertEqual( converter(42.0, {'decimal_precision': 'A'}), '42.00') self.assertEqual( converter(42.0, {'decimal_precision': 'B'}), '42.000000') converter = self.get_converter('float') # don't use float_4 because the field value 42.12345 is orm converted to 42.1235 self.assertEqual( converter(42.12345, {'decimal_precision': 'A'}), '42.12') self.assertEqual( converter(42.12345, {'decimal_precision': 'B'}), '42.123450')
32.818182
2,166
161,247
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # # test cases for new-style fields # import base64 from collections import OrderedDict from datetime import date, datetime, time import io from PIL import Image import psycopg2 from odoo import models, fields, Command from odoo.addons.base.tests.common import TransactionCaseWithUserDemo from odoo.exceptions import AccessError, MissingError, UserError, ValidationError from odoo.tests import common from odoo.tools import mute_logger, float_repr from odoo.tools.date_utils import add, subtract, start_of, end_of from odoo.tools.image import image_data_uri class TestFields(TransactionCaseWithUserDemo): def setUp(self): # for tests methods that create custom models/fields self.addCleanup(self.registry.reset_changes) self.addCleanup(self.registry.clear_caches) super(TestFields, self).setUp() self.env.ref('test_new_api.discussion_0').write({'participants': [Command.link(self.user_demo.id)]}) # YTI FIX ME: The cache shouldn't be inconsistent (rco is gonna fix it) # self.env.ref('test_new_api.discussion_0').participants -> 1 user # self.env.ref('test_new_api.discussion_0').invalidate_cache() # self.env.ref('test_new_api.discussion_0').with_context(active_test=False).participants -> 2 users self.env.ref('test_new_api.message_0_1').write({'author': self.user_demo.id}) def test_00_basics(self): """ test accessing new fields """ # find a discussion discussion = self.env.ref('test_new_api.discussion_0') # read field as a record attribute or as a record item self.assertIsInstance(discussion.name, str) self.assertIsInstance(discussion['name'], str) self.assertEqual(discussion['name'], discussion.name) # read it with method read() values = discussion.read(['name'])[0] self.assertEqual(values['name'], discussion.name) def test_01_basic_get_assertion(self): """ test item getter """ # field access works on single record record = self.env.ref('test_new_api.message_0_0') self.assertEqual(len(record), 1) ok = record.body # field access fails on multiple records records = self.env['test_new_api.message'].search([]) assert len(records) > 1 with self.assertRaises(ValueError): faulty = records.body def test_01_basic_set_assertion(self): """ test item setter """ # field assignment works on single record record = self.env.ref('test_new_api.message_0_0') self.assertEqual(len(record), 1) record.body = 'OK' # field assignment on multiple records should assign value to all records records = self.env['test_new_api.message'].search([]) records.body = 'Updated' self.assertTrue(all(map(lambda record:record.body=='Updated', records))) # field assigmenent does not cache the wrong value when write overridden record.priority = 4 self.assertEqual(record.priority, 5) def test_05_unknown_fields(self): """ test ORM operations with unknown fields """ cat = self.env['test_new_api.category'].create({'name': 'Foo'}) with self.assertRaisesRegex(ValueError, 'Invalid field'): cat.search([('zzz', '=', 42)]) with self.assertRaisesRegex(ValueError, 'Invalid field'): cat.search([], order='zzz') with self.assertRaisesRegex(ValueError, 'Invalid field'): cat.read(['zzz']) with self.assertRaisesRegex(ValueError, 'Invalid field'): cat.read_group([('zzz', '=', 42)], fields=['color'], groupby=['parent']) with self.assertRaisesRegex(ValueError, 'Invalid field'): cat.read_group([], fields=['zzz'], groupby=['parent']) with self.assertRaisesRegex(ValueError, 'Invalid field'): cat.read_group([], fields=['zzz:sum'], groupby=['parent']) with self.assertRaisesRegex(ValueError, 'Invalid field'): cat.read_group([], fields=['color'], groupby=['zzz']) with self.assertRaisesRegex(ValueError, 'Invalid field'): cat.read_group([], fields=['color'], groupby=['parent'], orderby='zzz') # exception: accept '__count' as field to aggregate cat.read_group([], fields=['__count'], groupby=['parent']) with self.assertRaisesRegex(ValueError, 'Invalid field'): cat.create({'name': 'Foo', 'zzz': 42}) with self.assertRaisesRegex(ValueError, 'Invalid field'): cat.write({'zzz': 42}) with self.assertRaisesRegex(ValueError, 'Invalid field'): cat.new({'name': 'Foo', 'zzz': 42}) def test_10_computed(self): """ check definition of computed fields """ # by default function fields are not stored, readonly, not copied field = self.env['test_new_api.message']._fields['size'] self.assertFalse(field.store) self.assertFalse(field.compute_sudo) self.assertTrue(field.readonly) self.assertFalse(field.copy) field = self.env['test_new_api.message']._fields['name'] self.assertTrue(field.store) self.assertTrue(field.compute_sudo) self.assertTrue(field.readonly) self.assertFalse(field.copy) # stored editable computed fields are copied according to their type field = self.env['test_new_api.compute.onchange']._fields['baz'] self.assertTrue(field.store) self.assertTrue(field.compute_sudo) self.assertFalse(field.readonly) self.assertTrue(field.copy) field = self.env['test_new_api.compute.onchange']._fields['line_ids'] self.assertTrue(field.store) self.assertTrue(field.compute_sudo) self.assertFalse(field.readonly) self.assertFalse(field.copy) # like a regular one2many field field = self.env['test_new_api.compute.onchange']._fields['tag_ids'] self.assertTrue(field.store) self.assertTrue(field.compute_sudo) self.assertFalse(field.readonly) self.assertTrue(field.copy) # like a regular many2many field def test_10_computed_custom(self): """ check definition of custom computed fields """ # Flush demo user before creating a new ir.model.fields to avoid # a deadlock self.user_demo.flush() self.env['ir.model.fields'].create({ 'name': 'x_bool_false_computed', 'model_id': self.env.ref('test_new_api.model_test_new_api_message').id, 'field_description': 'A boolean computed to false', 'compute': "for r in self: r['x_bool_false_computed'] = False", 'store': False, 'ttype': 'boolean' }) field = self.env['test_new_api.message']._fields['x_bool_false_computed'] self.assertFalse(self.registry.field_depends[field]) def test_10_computed_custom_invalid_transitive_depends(self): self.patch(type(self.env["ir.model.fields"]), "_check_depends", lambda self: True) self.env["ir.model.fields"].create( { "name": "x_computed_custom_valid_depends", "model_id": self.env.ref("test_new_api.model_test_new_api_foo").id, "state": "manual", "field_description": "A compute with a valid depends", "compute": "for r in self: r['x_computed_custom_valid_depends'] = False", "depends": "value1", "store": False, "ttype": "boolean", } ) self.env["ir.model.fields"].create( { "name": "x_computed_custom_valid_transitive_depends", "model_id": self.env.ref("test_new_api.model_test_new_api_foo").id, "state": "manual", "field_description": "A compute with a valid transitive depends", "compute": "for r in self: r['x_computed_custom_valid_transitive_depends'] = False", "depends": "x_computed_custom_valid_depends", "store": False, "ttype": "boolean", } ) self.env["ir.model.fields"].create( { "name": "x_computed_custom_invalid_depends", "model_id": self.env.ref("test_new_api.model_test_new_api_foo").id, "state": "manual", "field_description": "A compute with an invalid depends", "compute": "for r in self: r['x_computed_custom_invalid_depends'] = False", "depends": "bar", "store": False, "ttype": "boolean", } ) self.env["ir.model.fields"].create( { "name": "x_computed_custom_invalid_transitive_depends", "model_id": self.env.ref("test_new_api.model_test_new_api_foo").id, "state": "manual", "field_description": "A compute with an invalid transitive depends", "compute": "for r in self: r['x_computed_custom_invalid_transitive_depends'] = False", "depends": "x_computed_custom_invalid_depends", "store": False, "ttype": "boolean", } ) fields = self.env["test_new_api.foo"]._fields triggers = self.env.registry.field_triggers value1 = fields["value1"] valid_depends = fields["x_computed_custom_valid_depends"] valid_transitive_depends = fields["x_computed_custom_valid_transitive_depends"] invalid_depends = fields["x_computed_custom_invalid_depends"] invalid_transitive_depends = fields["x_computed_custom_invalid_transitive_depends"] # `x_computed_custom_valid_depends` in the triggers of the field `value1` self.assertTrue(valid_depends in triggers[value1][None]) # `x_computed_custom_valid_transitive_depends` in the triggers `x_computed_custom_valid_depends` and `value1` self.assertTrue(valid_transitive_depends in triggers[valid_depends][None]) self.assertTrue(valid_transitive_depends in triggers[value1][None]) # `x_computed_custom_invalid_depends` not in any triggers, as it was invalid and was skipped self.assertEqual( sum(invalid_depends in field_triggers.get(None, []) for field_triggers in triggers.values()), 0 ) # `x_computed_custom_invalid_transitive_depends` in the triggers of `x_computed_custom_invalid_depends` only self.assertTrue(invalid_transitive_depends in triggers[invalid_depends][None]) self.assertEqual( sum(invalid_transitive_depends in field_triggers.get(None, []) for field_triggers in triggers.values()), 1 ) @mute_logger('odoo.fields') def test_10_computed_stored_x_name(self): # create a custom model with two fields self.env["ir.model"].create({ "name": "x_test_10_compute_store_x_name", "model": "x_test_10_compute_store_x_name", "field_id": [ (0, 0, {'name': 'x_name', 'ttype': 'char'}), (0, 0, {'name': 'x_stuff_id', 'ttype': 'many2one', 'relation': 'ir.model'}), ], }) # set 'x_stuff_id' refer to a model not loaded yet self.cr.execute(""" UPDATE ir_model_fields SET relation = 'not.loaded' WHERE model = 'x_test_10_compute_store_x_name' AND name = 'x_stuff_id' """) # set 'x_name' be computed and depend on 'x_stuff_id' self.cr.execute(""" UPDATE ir_model_fields SET compute = 'pass', depends = 'x_stuff_id.x_custom_1' WHERE model = 'x_test_10_compute_store_x_name' AND name = 'x_name' """) # setting up models should not crash self.registry.setup_models(self.cr) def test_10_display_name(self): """ test definition of automatic field 'display_name' """ field = type(self.env['test_new_api.discussion']).display_name self.assertTrue(field.automatic) self.assertTrue(field.compute) self.assertEqual(self.registry.field_depends[field], ('name',)) def test_10_non_stored(self): """ test non-stored fields """ # a field declared with store=False should not have a column field = self.env['test_new_api.category']._fields['dummy'] self.assertFalse(field.store) self.assertFalse(field.compute) self.assertFalse(field.inverse) # find messages for message in self.env['test_new_api.message'].search([]): # check definition of field self.assertEqual(message.size, len(message.body or '')) # check recomputation after record is modified size = message.size message.write({'body': (message.body or '') + "!!!"}) self.assertEqual(message.size, size + 3) # create a message, assign body, and check size in several environments message1 = self.env['test_new_api.message'].create({}) message2 = message1.with_user(self.user_demo) self.assertEqual(message1.size, 0) self.assertEqual(message2.size, 0) message1.write({'body': "XXX"}) self.assertEqual(message1.size, 3) self.assertEqual(message2.size, 3) # special case: computed field without dependency must be computed record = self.env['test_new_api.mixed'].create({}) self.assertTrue(record.now) def test_11_stored(self): """ test stored fields """ def check_stored(disc): """ Check the stored computed field on disc.messages """ for msg in disc.messages: self.assertEqual(msg.name, "[%s] %s" % (disc.name, msg.author.name)) # find the demo discussion, and check messages discussion1 = self.env.ref('test_new_api.discussion_0') self.assertTrue(discussion1.messages) check_stored(discussion1) # modify discussion name, and check again messages discussion1.name = 'Talking about stuff...' check_stored(discussion1) # switch message from discussion, and check again # See YTI FIXME discussion1.invalidate_cache() discussion2 = discussion1.copy({'name': 'Another discussion'}) message2 = discussion1.messages[0] message2.discussion = discussion2 check_stored(discussion2) # create a new discussion with messages, and check their name user_root = self.env.ref('base.user_root') user_demo = self.user_demo discussion3 = self.env['test_new_api.discussion'].create({ 'name': 'Stuff', 'participants': [Command.link(user_root.id), Command.link(user_demo.id)], 'messages': [ Command.create({'author': user_root.id, 'body': 'one'}), Command.create({'author': user_demo.id, 'body': 'two'}), Command.create({'author': user_root.id, 'body': 'three'}), ], }) check_stored(discussion3) # modify the discussion messages: edit the 2nd one, remove the last one # (keep modifications in that order, as they reproduce a former bug!) discussion3.write({ 'messages': [ Command.link(discussion3.messages[0].id), Command.update(discussion3.messages[1].id, {'author': user_root.id}), Command.delete(discussion3.messages[2].id), ], }) check_stored(discussion3) def test_11_stored_protected(self): """ test protection against recomputation """ model = self.env['test_new_api.compute.readonly'] field = model._fields['bar'] record = model.create({'foo': 'unprotected #1'}) self.assertEqual(record.bar, 'unprotected #1') record.write({'foo': 'unprotected #2'}) self.assertEqual(record.bar, 'unprotected #2') # by protecting 'bar', we prevent it from being recomputed with self.env.protecting([field], record): record.write({'foo': 'protected'}) self.assertEqual(record.bar, 'unprotected #2') # also works when nested with self.env.protecting([field], record): record.write({'foo': 'protected'}) self.assertEqual(record.bar, 'unprotected #2') record.write({'foo': 'protected'}) self.assertEqual(record.bar, 'unprotected #2') record.write({'foo': 'unprotected #3'}) self.assertEqual(record.bar, 'unprotected #3') # also works with duplicated fields with self.env.protecting([field, field], record): record.write({'foo': 'protected'}) self.assertEqual(record.bar, 'unprotected #3') record.write({'foo': 'unprotected #4'}) self.assertEqual(record.bar, 'unprotected #4') # we protect 'bar' on a different record with self.env.protecting([field], record): record2 = model.create({'foo': 'unprotected'}) self.assertEqual(record2.bar, 'unprotected') def test_11_computed_access(self): """ test computed fields with access right errors """ User = self.env['res.users'] user1 = User.create({'name': 'Aaaah', 'login': 'a'}) user2 = User.create({'name': 'Boooh', 'login': 'b'}) user3 = User.create({'name': 'Crrrr', 'login': 'c'}) # add a rule to not give access to user2 self.env['ir.rule'].create({ 'model_id': self.env['ir.model'].search([('model', '=', 'res.users')]).id, 'domain_force': "[('id', '!=', %d)]" % user2.id, }) # DLE P72: Since we decided that we do not raise security access errors for data to which we had the occassion # to put the value in the cache, we need to invalidate the cache for user1, user2 and user3 in order # to test the below access error. Otherwise the above create calls set in the cache the information needed # to compute `company_type` ('is_company'), and doesn't need to trigger a read. # We need to force the read in order to test the security access User.invalidate_cache() # group users as a recordset, and read them as user demo users = (user1 + user2 + user3).with_user(self.user_demo) user1, user2, user3 = users # regression test: a bug invalidated the field's value from cache user1.company_type with self.assertRaises(AccessError): user2.company_type user3.company_type def test_12_recursive(self): """ test recursively dependent fields """ Category = self.env['test_new_api.category'] abel = Category.create({'name': 'Abel'}) beth = Category.create({'name': 'Bethany'}) cath = Category.create({'name': 'Catherine'}) dean = Category.create({'name': 'Dean'}) ewan = Category.create({'name': 'Ewan'}) finn = Category.create({'name': 'Finnley'}) gabe = Category.create({'name': 'Gabriel'}) cath.parent = finn.parent = gabe abel.parent = beth.parent = cath dean.parent = ewan.parent = finn self.assertEqual(abel.display_name, "Gabriel / Catherine / Abel") self.assertEqual(beth.display_name, "Gabriel / Catherine / Bethany") self.assertEqual(cath.display_name, "Gabriel / Catherine") self.assertEqual(dean.display_name, "Gabriel / Finnley / Dean") self.assertEqual(ewan.display_name, "Gabriel / Finnley / Ewan") self.assertEqual(finn.display_name, "Gabriel / Finnley") self.assertEqual(gabe.display_name, "Gabriel") ewan.parent = cath self.assertEqual(ewan.display_name, "Gabriel / Catherine / Ewan") cath.parent = finn self.assertEqual(ewan.display_name, "Gabriel / Finnley / Catherine / Ewan") def test_12_recursive_recompute(self): """ test recomputation on recursively dependent field """ a = self.env['test_new_api.recursive'].create({'name': 'A'}) b = self.env['test_new_api.recursive'].create({'name': 'B', 'parent': a.id}) c = self.env['test_new_api.recursive'].create({'name': 'C', 'parent': b.id}) d = self.env['test_new_api.recursive'].create({'name': 'D', 'parent': c.id}) self.assertEqual(a.full_name, 'A') self.assertEqual(b.full_name, 'A / B') self.assertEqual(c.full_name, 'A / B / C') self.assertEqual(d.full_name, 'A / B / C / D') self.assertEqual(a.display_name, 'A') self.assertEqual(b.display_name, 'A / B') self.assertEqual(c.display_name, 'A / B / C') self.assertEqual(d.display_name, 'A / B / C / D') a.name = 'A1' self.assertEqual(a.full_name, 'A1') self.assertEqual(b.full_name, 'A1 / B') self.assertEqual(c.full_name, 'A1 / B / C') self.assertEqual(d.full_name, 'A1 / B / C / D') self.assertEqual(a.display_name, 'A1') self.assertEqual(b.display_name, 'A1 / B') self.assertEqual(c.display_name, 'A1 / B / C') self.assertEqual(d.display_name, 'A1 / B / C / D') b.parent = False self.assertEqual(a.full_name, 'A1') self.assertEqual(b.full_name, 'B') self.assertEqual(c.full_name, 'B / C') self.assertEqual(d.full_name, 'B / C / D') self.assertEqual(a.display_name, 'A1') self.assertEqual(b.display_name, 'B') self.assertEqual(c.display_name, 'B / C') self.assertEqual(d.display_name, 'B / C / D') # rename several records to trigger several recomputations at once (d + c + b).write({'name': 'X'}) self.assertEqual(a.full_name, 'A1') self.assertEqual(b.full_name, 'X') self.assertEqual(c.full_name, 'X / X') self.assertEqual(d.full_name, 'X / X / X') self.assertEqual(a.display_name, 'A1') self.assertEqual(b.display_name, 'X') self.assertEqual(c.display_name, 'X / X') self.assertEqual(d.display_name, 'X / X / X') # delete b; both c and d are deleted in cascade; c should also be marked # to recompute, but recomputation should not fail... b.unlink() self.assertEqual((a + b + c + d).exists(), a) def test_12_recursive_tree(self): foo = self.env['test_new_api.recursive.tree'].create({'name': 'foo'}) self.assertEqual(foo.display_name, 'foo()') bar = foo.create({'name': 'bar', 'parent_id': foo.id}) self.assertEqual(foo.display_name, 'foo(bar())') baz = foo.create({'name': 'baz', 'parent_id': bar.id}) self.assertEqual(foo.display_name, 'foo(bar(baz()))') def test_12_cascade(self): """ test computed field depending on computed field """ message = self.env.ref('test_new_api.message_0_0') message.invalidate_cache() double_size = message.double_size self.assertEqual(double_size, message.size) record = self.env['test_new_api.cascade'].create({'foo': "Hi"}) self.assertEqual(record.baz, "<[Hi]>") record.foo = "Ho" self.assertEqual(record.baz, "<[Ho]>") def test_12_dynamic_depends(self): Model = self.registry['test_new_api.compute.dynamic.depends'] self.assertEqual(self.registry.field_depends[Model.full_name], ()) # the dependencies of full_name are stored in a config parameter self.env['ir.config_parameter'].set_param('test_new_api.full_name', 'name1,name2') # this must re-evaluate the field's dependencies self.env['base'].flush() self.registry.setup_models(self.cr) self.assertEqual(self.registry.field_depends[Model.full_name], ('name1', 'name2')) def test_13_inverse(self): """ test inverse computation of fields """ Category = self.env['test_new_api.category'] abel = Category.create({'name': 'Abel'}) beth = Category.create({'name': 'Bethany'}) cath = Category.create({'name': 'Catherine'}) dean = Category.create({'name': 'Dean'}) ewan = Category.create({'name': 'Ewan'}) finn = Category.create({'name': 'Finnley'}) gabe = Category.create({'name': 'Gabriel'}) self.assertEqual(ewan.display_name, "Ewan") ewan.display_name = "Abel / Bethany / Catherine / Erwan" self.assertEqual(beth.parent, abel) self.assertEqual(cath.parent, beth) self.assertEqual(ewan.parent, cath) self.assertEqual(ewan.name, "Erwan") # check create/write with several records vals = {'name': 'None', 'display_name': 'Foo'} foo1, foo2 = Category.create([vals, vals]) self.assertEqual(foo1.name, 'Foo') self.assertEqual(foo2.name, 'Foo') (foo1 + foo2).write({'display_name': 'Bar'}) self.assertEqual(foo1.name, 'Bar') self.assertEqual(foo2.name, 'Bar') # create/write on 'foo' should only invoke the compute method log = [] model = self.env['test_new_api.compute.inverse'].with_context(log=log) record = model.create({'foo': 'Hi'}) self.assertEqual(record.foo, 'Hi') self.assertEqual(record.bar, 'Hi') self.assertCountEqual(log, ['compute']) log.clear() record.write({'foo': 'Ho'}) self.assertEqual(record.foo, 'Ho') self.assertEqual(record.bar, 'Ho') self.assertCountEqual(log, ['compute']) # create/write on 'bar' should only invoke the inverse method log.clear() record = model.create({'bar': 'Hi'}) self.assertEqual(record.foo, 'Hi') self.assertEqual(record.bar, 'Hi') self.assertCountEqual(log, ['inverse']) log.clear() record.write({'bar': 'Ho'}) self.assertEqual(record.foo, 'Ho') self.assertEqual(record.bar, 'Ho') self.assertCountEqual(log, ['inverse']) # Test compatibility multiple compute/inverse fields log = [] model = self.env['test_new_api.multi_compute_inverse'].with_context(log=log) record = model.create({ 'bar1': '1', 'bar2': '2', 'bar3': '3', }) self.assertEqual(record.foo, '1/2/3') self.assertEqual(record.bar1, '1') self.assertEqual(record.bar2, '2') self.assertEqual(record.bar3, '3') self.assertCountEqual(log, ['inverse1', 'inverse23']) log.clear() record.write({'bar2': '4', 'bar3': '5'}) self.assertEqual(record.foo, '1/4/5') self.assertEqual(record.bar1, '1') self.assertEqual(record.bar2, '4') self.assertEqual(record.bar3, '5') self.assertCountEqual(log, ['inverse23']) log.clear() record.write({'bar1': '6', 'bar2': '7'}) self.assertEqual(record.foo, '6/7/5') self.assertEqual(record.bar1, '6') self.assertEqual(record.bar2, '7') self.assertEqual(record.bar3, '5') self.assertCountEqual(log, ['inverse1', 'inverse23']) log.clear() record.write({'foo': 'A/B/C'}) self.assertEqual(record.foo, 'A/B/C') self.assertEqual(record.bar1, 'A') self.assertEqual(record.bar2, 'B') self.assertEqual(record.bar3, 'C') self.assertCountEqual(log, ['compute']) # corner case: write on a field that is marked to compute log.clear() # writing on 'foo' marks 'bar1', 'bar2', 'bar3' to compute record.write({'foo': '1/2/3'}) self.assertCountEqual(log, []) # writing on 'bar3' must force the computation before updating record.write({'bar3': 'X'}) self.assertCountEqual(log, ['compute', 'inverse23']) self.assertEqual(record.foo, '1/2/X') self.assertEqual(record.bar1, '1') self.assertEqual(record.bar2, '2') self.assertEqual(record.bar3, 'X') self.assertCountEqual(log, ['compute', 'inverse23']) log.clear() # writing on 'foo' marks 'bar1', 'bar2', 'bar3' to compute record.write({'foo': 'A/B/C'}) self.assertCountEqual(log, []) # writing on 'bar1', 'bar2', 'bar3' discards the computation record.write({'bar1': 'X', 'bar2': 'Y', 'bar3': 'Z'}) self.assertCountEqual(log, ['inverse1', 'inverse23']) self.assertEqual(record.foo, 'X/Y/Z') self.assertEqual(record.bar1, 'X') self.assertEqual(record.bar2, 'Y') self.assertEqual(record.bar3, 'Z') self.assertCountEqual(log, ['inverse1', 'inverse23']) def test_13_inverse_access(self): """ test access rights on inverse fields """ foo = self.env['test_new_api.category'].create({'name': 'Foo'}) user = self.env['res.users'].create({'name': 'Foo', 'login': 'foo'}) self.assertFalse(user.has_group('base.group_system')) # add group on non-stored inverse field self.patch(type(foo).display_name, 'groups', 'base.group_system') with self.assertRaises(AccessError): foo.with_user(user).display_name = 'Forbidden' def test_13_inverse_with_unlink(self): """ test x2many delete command combined with an inverse field """ country1 = self.env['res.country'].create({'name': 'test country'}) country2 = self.env['res.country'].create({'name': 'other country'}) company = self.env['res.company'].create({ 'name': 'test company', 'child_ids': [ (0, 0, {'name': 'Child Company 1'}), (0, 0, {'name': 'Child Company 2'}), ] }) child_company = company.child_ids[0] # check first that the field has an inverse and is not stored field = type(company).country_id self.assertFalse(field.store) self.assertTrue(field.inverse) company.write({'country_id': country1.id}) self.assertEqual(company.country_id, country1) company.write({ 'country_id': country2.id, 'child_ids': [(2, child_company.id)], }) self.assertEqual(company.country_id, country2) def test_14_search(self): """ test search on computed fields """ discussion = self.env.ref('test_new_api.discussion_0') # determine message sizes sizes = set(message.size for message in discussion.messages) # search for messages based on their size for size in sizes: messages0 = self.env['test_new_api.message'].search( [('discussion', '=', discussion.id), ('size', '<=', size)]) messages1 = self.env['test_new_api.message'].browse() for message in discussion.messages: if message.size <= size: messages1 += message self.assertEqual(messages0, messages1) def test_15_constraint(self): """ test new-style Python constraints """ discussion = self.env.ref('test_new_api.discussion_0') discussion.flush() # remove oneself from discussion participants: we can no longer create # messages in discussion discussion.participants -= self.env.user with self.assertRaises(ValidationError): self.env['test_new_api.message'].create({'discussion': discussion.id, 'body': 'Whatever'}) # make sure that assertRaises() does not leave fields to recompute self.assertFalse(self.env.fields_to_compute()) # put back oneself into discussion participants: now we can create # messages in discussion discussion.participants += self.env.user self.env['test_new_api.message'].create({'discussion': discussion.id, 'body': 'Whatever'}) # check constraint on recomputed field self.assertTrue(discussion.messages) with self.assertRaises(ValidationError): discussion.name = "X" discussion.flush() def test_15_constraint_inverse(self): """ test constraint method on normal field and field with inverse """ log = [] model = self.env['test_new_api.compute.inverse'].with_context(log=log, log_constraint=True) # create/write with normal field only log.clear() record = model.create({'baz': 'Hi'}) self.assertCountEqual(log, ['constraint']) log.clear() record.write({'baz': 'Ho'}) self.assertCountEqual(log, ['constraint']) # create/write with inverse field only log.clear() record = model.create({'bar': 'Hi'}) self.assertCountEqual(log, ['inverse', 'constraint']) log.clear() record.write({'bar': 'Ho'}) self.assertCountEqual(log, ['inverse', 'constraint']) # create/write with both fields only log.clear() record = model.create({'bar': 'Hi', 'baz': 'Hi'}) self.assertCountEqual(log, ['inverse', 'constraint']) log.clear() record.write({'bar': 'Ho', 'baz': 'Ho'}) self.assertCountEqual(log, ['inverse', 'constraint']) def test_16_compute_unassigned(self): model = self.env['test_new_api.compute.unassigned'] # real record record = model.create({}) with self.assertRaises(ValueError): record.bar self.assertEqual(record.bare, False) self.assertEqual(record.bars, False) self.assertEqual(record.bares, False) # new record record = model.new() with self.assertRaises(ValueError): record.bar self.assertEqual(record.bare, False) self.assertEqual(record.bars, False) self.assertEqual(record.bares, False) def test_16_compute_unassigned_access_error(self): # create two records records = self.env['test_new_api.compute.unassigned'].create([{}, {}]) records.flush() # alter access rights: regular users cannot read 'records' access = self.env.ref('test_new_api.access_test_new_api_compute_unassigned') access.perm_read = False access.flush() # switch to environment with user demo records = records.with_user(self.user_demo) records.env.cache.invalidate() # check that records are not accessible with self.assertRaises(AccessError): records[0].bars with self.assertRaises(AccessError): records[1].bars # Modify the records and flush() changes with the current environment: # this should not trigger an access error, whatever the order in which # records are considered. It may fail in the following scenario: # - mark field 'bars' to compute on records # - access records[0].bars # - recompute bars on records (both) -> assign records[0] only # - return records[0].bars from cache # - access records[1].bars # - recompute nothing (done already) # - records[1].bars is not in cache # - fetch records[1].bars -> access error records[0].foo = "assign" records[1].foo = "x" records.flush() # try the other way around, too records.env.cache.invalidate() records[0].foo = "x" records[1].foo = "assign" records.flush() def test_20_float(self): """ test rounding of float fields """ record = self.env['test_new_api.mixed'].create({}) query = "SELECT 1 FROM test_new_api_mixed WHERE id=%s AND number=%s" # 2.49609375 (exact float) must be rounded to 2.5 record.write({'number': 2.49609375}) record.flush() self.cr.execute(query, [record.id, '2.5']) self.assertTrue(self.cr.rowcount) self.assertEqual(record.number, 2.5) # 1.1 (1.1000000000000000888178420 in float) must be 1.1 in database record.write({'number': 1.1}) record.flush() self.cr.execute(query, [record.id, '1.1']) self.assertTrue(self.cr.rowcount) self.assertEqual(record.number, 1.1) def test_21_float_digits(self): """ test field description """ precision = self.env.ref('test_new_api.decimal_new_api_number') description = self.env['test_new_api.mixed'].fields_get()['number2'] self.assertEqual(description['digits'], (16, precision.digits)) def check_monetary(self, record, amount, currency, msg=None): # determine the possible roundings of amount if currency: ramount = currency.round(amount) samount = float(float_repr(ramount, currency.decimal_places)) else: ramount = samount = amount # check the currency on record self.assertEqual(record.currency_id, currency) # check the value on the record self.assertIn(record.amount, [ramount, samount], msg) # check the value in the database record.flush() self.cr.execute('SELECT amount FROM test_new_api_mixed WHERE id=%s', [record.id]) value = self.cr.fetchone()[0] self.assertEqual(value, samount, msg) def test_20_monetary(self): """ test monetary fields """ model = self.env['test_new_api.mixed'] currency = self.env['res.currency'].with_context(active_test=False) amount = 14.70126 for rounding in [0.01, 0.0001, 1.0, 0]: # first retrieve a currency corresponding to rounding if rounding: currency = currency.search([('rounding', '=', rounding)], limit=1) self.assertTrue(currency, "No currency found for rounding %s" % rounding) else: # rounding=0 corresponds to currency=False currency = currency.browse() # case 1: create with amount and currency record = model.create({'amount': amount, 'currency_id': currency.id}) self.check_monetary(record, amount, currency, 'create(amount, currency)') # case 2: assign amount record.amount = 0 record.amount = amount self.check_monetary(record, amount, currency, 'assign(amount)') # case 3: write with amount and currency record.write({'amount': 0, 'currency_id': False}) record.write({'amount': amount, 'currency_id': currency.id}) self.check_monetary(record, amount, currency, 'write(amount, currency)') # case 4: write with amount only record.write({'amount': 0}) record.write({'amount': amount}) self.check_monetary(record, amount, currency, 'write(amount)') # case 5: write with amount on several records records = record + model.create({'currency_id': currency.id}) records.write({'amount': 0}) records.write({'amount': amount}) for record in records: self.check_monetary(record, amount, currency, 'multi write(amount)') def test_20_monetary_opw_2223134(self): """ test monetary fields with cache override """ model = self.env['test_new_api.monetary_order'] currency = self.env.ref('base.USD') def check(value): self.assertEqual(record.total, value) record.flush() self.cr.execute('SELECT total FROM test_new_api_monetary_order WHERE id=%s', [record.id]) [total] = self.cr.fetchone() self.assertEqual(total, value) # create, and compute amount record = model.create({ 'currency_id': currency.id, 'line_ids': [Command.create({'subtotal': 1.0})], }) check(1.0) # delete and add a line: the deletion of the line clears the cache, then # the recomputation of 'total' must prefetch record.currency_id without # screwing up the new value in cache record.write({ 'line_ids': [Command.delete(record.line_ids.id), Command.create({'subtotal': 1.0})], }) check(1.0) def test_20_monetary_related(self): """ test value rounding with related currency """ currency = self.env.ref('base.USD') monetary_base = self.env['test_new_api.monetary_base'].create({ 'base_currency_id': currency.id }) monetary_related = self.env['test_new_api.monetary_related'].create({ 'monetary_id': monetary_base.id, 'total': 1/3, }) self.env.cr.execute( "SELECT total FROM test_new_api_monetary_related WHERE id=%s", monetary_related.ids, ) [total] = self.env.cr.fetchone() self.assertEqual(total, .33) def test_20_like(self): """ test filtered_domain() on char fields. """ record = self.env['test_new_api.multi.tag'].create({'name': 'Foo'}) self.assertTrue(record.filtered_domain([('name', 'like', 'F')])) self.assertTrue(record.filtered_domain([('name', 'ilike', 'f')])) record.name = 'Bar' self.assertFalse(record.filtered_domain([('name', 'like', 'F')])) self.assertFalse(record.filtered_domain([('name', 'ilike', 'f')])) record.name = False self.assertFalse(record.filtered_domain([('name', 'like', 'F')])) self.assertFalse(record.filtered_domain([('name', 'ilike', 'f')])) def test_21_date(self): """ test date fields """ record = self.env['test_new_api.mixed'].create({}) # one may assign False or None record.date = None self.assertFalse(record.date) # one may assign date but not datetime objects record.date = date(2012, 5, 1) self.assertEqual(record.date, date(2012, 5, 1)) # DLE P41: We now support to assign datetime to date. Not sure this is the good practice though. # with self.assertRaises(TypeError): # record.date = datetime(2012, 5, 1, 10, 45, 0) # one may assign dates and datetime in the default format, and it must be checked record.date = '2012-05-01' self.assertEqual(record.date, date(2012, 5, 1)) record.date = "2012-05-01 10:45:00" self.assertEqual(record.date, date(2012, 5, 1)) with self.assertRaises(ValueError): record.date = '12-5-1' # check filtered_domain self.assertTrue(record.filtered_domain([('date', '<', '2012-05-02')])) self.assertTrue(record.filtered_domain([('date', '<', date(2012, 5, 2))])) self.assertTrue(record.filtered_domain([('date', '<', datetime(2012, 5, 2, 12, 0, 0))])) self.assertTrue(record.filtered_domain([('date', '!=', False)])) self.assertFalse(record.filtered_domain([('date', '=', False)])) record.date = None self.assertFalse(record.filtered_domain([('date', '<', '2012-05-02')])) self.assertFalse(record.filtered_domain([('date', '<', date(2012, 5, 2))])) self.assertFalse(record.filtered_domain([('date', '<', datetime(2012, 5, 2, 12, 0, 0))])) self.assertFalse(record.filtered_domain([('date', '!=', False)])) self.assertTrue(record.filtered_domain([('date', '=', False)])) def test_21_datetime(self): """ test datetime fields """ for i in range(0, 10): self.assertEqual(fields.Datetime.now().microsecond, 0) record = self.env['test_new_api.mixed'].create({}) # assign falsy value record.moment = None self.assertFalse(record.moment) # assign string record.moment = '2012-05-01' self.assertEqual(record.moment, datetime(2012, 5, 1)) record.moment = '2012-05-01 06:00:00' self.assertEqual(record.moment, datetime(2012, 5, 1, 6)) with self.assertRaises(ValueError): record.moment = '12-5-1' # assign date or datetime record.moment = date(2012, 5, 1) self.assertEqual(record.moment, datetime(2012, 5, 1)) record.moment = datetime(2012, 5, 1, 6) self.assertEqual(record.moment, datetime(2012, 5, 1, 6)) # check filtered_domain self.assertTrue(record.filtered_domain([('moment', '<', '2012-05-02')])) self.assertTrue(record.filtered_domain([('moment', '<', date(2012, 5, 2))])) self.assertTrue(record.filtered_domain([('moment', '<', datetime(2012, 5, 1, 12, 0, 0))])) self.assertTrue(record.filtered_domain([('moment', '!=', False)])) self.assertFalse(record.filtered_domain([('moment', '=', False)])) record.moment = None self.assertFalse(record.filtered_domain([('moment', '<', '2012-05-02')])) self.assertFalse(record.filtered_domain([('moment', '<', date(2012, 5, 2))])) self.assertFalse(record.filtered_domain([('moment', '<', datetime(2012, 5, 2, 12, 0, 0))])) self.assertFalse(record.filtered_domain([('moment', '!=', False)])) self.assertTrue(record.filtered_domain([('moment', '=', False)])) def test_21_date_datetime_helpers(self): """ test date/datetime fields helpers """ _date = fields.Date.from_string("2077-10-23") _datetime = fields.Datetime.from_string("2077-10-23 09:42:00") # addition self.assertEqual(add(_date, days=5), date(2077, 10, 28)) self.assertEqual(add(_datetime, seconds=10), datetime(2077, 10, 23, 9, 42, 10)) # subtraction self.assertEqual(subtract(_date, months=1), date(2077, 9, 23)) self.assertEqual(subtract(_datetime, hours=2), datetime(2077, 10, 23, 7, 42, 0)) # start_of # year self.assertEqual(start_of(_date, 'year'), date(2077, 1, 1)) self.assertEqual(start_of(_datetime, 'year'), datetime(2077, 1, 1)) # quarter q1 = date(2077, 1, 1) q2 = date(2077, 4, 1) q3 = date(2077, 7, 1) q4 = date(2077, 10, 1) self.assertEqual(start_of(_date.replace(month=3), 'quarter'), q1) self.assertEqual(start_of(_date.replace(month=5), 'quarter'), q2) self.assertEqual(start_of(_date.replace(month=7), 'quarter'), q3) self.assertEqual(start_of(_date, 'quarter'), q4) self.assertEqual(start_of(_datetime, 'quarter'), datetime.combine(q4, time.min)) # month self.assertEqual(start_of(_date, 'month'), date(2077, 10, 1)) self.assertEqual(start_of(_datetime, 'month'), datetime(2077, 10, 1)) # week self.assertEqual(start_of(_date, 'week'), date(2077, 10, 18)) self.assertEqual(start_of(_datetime, 'week'), datetime(2077, 10, 18)) # day self.assertEqual(start_of(_date, 'day'), _date) self.assertEqual(start_of(_datetime, 'day'), _datetime.replace(hour=0, minute=0, second=0)) # hour with self.assertRaises(ValueError): start_of(_date, 'hour') self.assertEqual(start_of(_datetime, 'hour'), _datetime.replace(minute=0, second=0)) # invalid with self.assertRaises(ValueError): start_of(_datetime, 'poop') # end_of # year self.assertEqual(end_of(_date, 'year'), _date.replace(month=12, day=31)) self.assertEqual(end_of(_datetime, 'year'), datetime.combine(_date.replace(month=12, day=31), time.max)) # quarter q1 = date(2077, 3, 31) q2 = date(2077, 6, 30) q3 = date(2077, 9, 30) q4 = date(2077, 12, 31) self.assertEqual(end_of(_date.replace(month=2), 'quarter'), q1) self.assertEqual(end_of(_date.replace(month=4), 'quarter'), q2) self.assertEqual(end_of(_date.replace(month=9), 'quarter'), q3) self.assertEqual(end_of(_date, 'quarter'), q4) self.assertEqual(end_of(_datetime, 'quarter'), datetime.combine(q4, time.max)) # month self.assertEqual(end_of(_date, 'month'), _date.replace(day=31)) self.assertEqual(end_of(_datetime, 'month'), datetime.combine(date(2077, 10, 31), time.max)) # week self.assertEqual(end_of(_date, 'week'), date(2077, 10, 24)) self.assertEqual(end_of(_datetime, 'week'), datetime.combine(datetime(2077, 10, 24), time.max)) # day self.assertEqual(end_of(_date, 'day'), _date) self.assertEqual(end_of(_datetime, 'day'), datetime.combine(_datetime, time.max)) # hour with self.assertRaises(ValueError): end_of(_date, 'hour') self.assertEqual(end_of(_datetime, 'hour'), datetime.combine(_datetime, time.max).replace(hour=_datetime.hour)) # invalid with self.assertRaises(ValueError): end_of(_datetime, 'crap') def test_22_selection(self): """ test selection fields """ record = self.env['test_new_api.mixed'].create({}) # one may assign False or None record.lang = None self.assertFalse(record.lang) # one may assign a value, and it must be checked for language in self.env['res.lang'].search([]): record.lang = language.code with self.assertRaises(ValueError): record.lang = 'zz_ZZ' def test_23_relation(self): """ test relation fields """ demo = self.user_demo message = self.env.ref('test_new_api.message_0_0') # check environment of record and related records self.assertEqual(message.env, self.env) self.assertEqual(message.discussion.env, self.env) demo_env = self.env(user=demo) self.assertNotEqual(demo_env, self.env) # check environment of record and related records self.assertEqual(message.env, self.env) self.assertEqual(message.discussion.env, self.env) # "migrate" message into demo_env, and check again demo_message = message.with_user(demo) self.assertEqual(demo_message.env, demo_env) self.assertEqual(demo_message.discussion.env, demo_env) # See YTI FIXME message.discussion.invalidate_cache() # assign record's parent to a record in demo_env message.discussion = message.discussion.copy({'name': 'Copy'}) # both message and its parent field must be in self.env self.assertEqual(message.env, self.env) self.assertEqual(message.discussion.env, self.env) def test_24_reference(self): """ test reference fields. """ record = self.env['test_new_api.mixed'].create({}) # one may assign False or None record.reference = None self.assertFalse(record.reference) # one may assign a user or a partner... record.reference = self.env.user self.assertEqual(record.reference, self.env.user) record.reference = self.env.user.partner_id self.assertEqual(record.reference, self.env.user.partner_id) # ... but no record from a model that starts with 'ir.' with self.assertRaises(ValueError): record.reference = self.env['ir.model'].search([], limit=1) def test_25_related(self): """ test related fields. """ message = self.env.ref('test_new_api.message_0_0') discussion = message.discussion # by default related fields are not stored field = message._fields['discussion_name'] self.assertFalse(field.store) self.assertFalse(field.readonly) # check value of related field self.assertEqual(message.discussion_name, discussion.name) # change discussion name, and check result discussion.name = 'Foo' self.assertEqual(message.discussion_name, 'Foo') # change discussion name via related field, and check result message.discussion_name = 'Bar' self.assertEqual(discussion.name, 'Bar') self.assertEqual(message.discussion_name, 'Bar') # change discussion name via related field on several records discussion1 = discussion.create({'name': 'X1'}) discussion2 = discussion.create({'name': 'X2'}) discussion1.participants = discussion2.participants = self.env.user message1 = message.create({'discussion': discussion1.id}) message2 = message.create({'discussion': discussion2.id}) self.assertEqual(message1.discussion_name, 'X1') self.assertEqual(message2.discussion_name, 'X2') (message1 + message2).write({'discussion_name': 'X3'}) self.assertEqual(discussion1.name, 'X3') self.assertEqual(discussion2.name, 'X3') # search on related field, and check result search_on_related = self.env['test_new_api.message'].search([('discussion_name', '=', 'Bar')]) search_on_regular = self.env['test_new_api.message'].search([('discussion.name', '=', 'Bar')]) self.assertEqual(search_on_related, search_on_regular) # check that field attributes are copied message_field = message.fields_get(['discussion_name'])['discussion_name'] discussion_field = discussion.fields_get(['name'])['name'] self.assertEqual(message_field['help'], discussion_field['help']) def test_25_related_attributes(self): """ test the attributes of related fields """ text = self.registry['test_new_api.foo'].text self.assertFalse(text.trim, "The target field is defined with trim=False") # trim=True is the default on the field's class self.assertTrue(type(text).trim, "By default, a Char field has trim=True") # the parameter 'trim' is not set in text1's definition, so the field # retrieves its value from text.trim text1 = self.registry['test_new_api.bar'].text1 self.assertFalse(text1.trim, "The related field retrieves trim=False from target") # text2 is defined with trim=True, so it should get that value text2 = self.registry['test_new_api.bar'].text2 self.assertTrue(text2.trim, "The related field was defined with trim=True") def test_25_related_single(self): """ test related fields with a single field in the path. """ record = self.env['test_new_api.related'].create({'name': 'A'}) self.assertEqual(record.related_name, record.name) self.assertEqual(record.related_related_name, record.name) # check searching on related fields records0 = record.search([('name', '=', 'A')]) self.assertIn(record, records0) records1 = record.search([('related_name', '=', 'A')]) self.assertEqual(records1, records0) records2 = record.search([('related_related_name', '=', 'A')]) self.assertEqual(records2, records0) # check writing on related fields record.write({'related_name': 'B'}) self.assertEqual(record.name, 'B') record.write({'related_related_name': 'C'}) self.assertEqual(record.name, 'C') def test_25_related_multi(self): """ test write() on several related fields based on a common computed field. """ foo = self.env['test_new_api.foo'].create({'name': 'A', 'value1': 1, 'value2': 2}) oof = self.env['test_new_api.foo'].create({'name': 'B', 'value1': 1, 'value2': 2}) bar = self.env['test_new_api.bar'].create({'name': 'A'}) self.assertEqual(bar.foo, foo) self.assertEqual(bar.value1, 1) self.assertEqual(bar.value2, 2) foo.invalidate_cache() bar.write({'value1': 3, 'value2': 4}) self.assertEqual(foo.value1, 3) self.assertEqual(foo.value2, 4) # modify 'name', and search on 'foo': this should flush 'name' bar.name = 'B' self.assertEqual(bar.foo, oof) self.assertIn(bar, bar.search([('foo', 'in', oof.ids)])) def test_25_one2many_inverse_related(self): left = self.env['test_new_api.trigger.left'].create({}) right = self.env['test_new_api.trigger.right'].create({}) self.assertFalse(left.right_id) self.assertFalse(right.left_ids) self.assertFalse(right.left_size) # create middle: this should trigger left.right_id by traversing # middle.left_id, and right.left_size by traversing left.right_id # after its computation! middle = self.env['test_new_api.trigger.middle'].create({ 'left_id': left.id, 'right_id': right.id, }) self.assertEqual(left.right_id, right) self.assertEqual(right.left_ids, left) self.assertEqual(right.left_size, 1) # delete middle: this should trigger left.right_id by traversing # middle.left_id, and right.left_size by traversing left.right_id # before its computation! middle.unlink() self.assertFalse(left.right_id) self.assertFalse(right.left_ids) self.assertFalse(right.left_size) def test_26_inherited(self): """ test inherited fields. """ # a bunch of fields are inherited from res_partner for user in self.env['res.users'].search([]): partner = user.partner_id for field in ('is_company', 'name', 'email', 'country_id'): self.assertEqual(getattr(user, field), getattr(partner, field)) self.assertEqual(user[field], partner[field]) def test_27_company_dependent(self): """ test company-dependent fields. """ # consider three companies company0 = self.env.ref('base.main_company') company1 = self.env['res.company'].create({'name': 'A'}) company2 = self.env['res.company'].create({'name': 'B'}) # create one user per company user0 = self.env['res.users'].create({ 'name': 'Foo', 'login': 'foo', 'company_id': company0.id, 'company_ids': [Command.set([company0.id, company1.id, company2.id])]}) user1 = self.env['res.users'].create({ 'name': 'Bar', 'login': 'bar', 'company_id': company1.id, 'company_ids': [Command.set([company0.id, company1.id, company2.id])]}) user2 = self.env['res.users'].create({ 'name': 'Baz', 'login': 'baz', 'company_id': company2.id, 'company_ids': [Command.set([company0.id, company1.id, company2.id])]}) # create values for many2one field tag0 = self.env['test_new_api.multi.tag'].create({'name': 'Qux'}) tag1 = self.env['test_new_api.multi.tag'].create({'name': 'Quux'}) tag2 = self.env['test_new_api.multi.tag'].create({'name': 'Quuz'}) # create default values for the company-dependent fields self.env['ir.property']._set_default('foo', 'test_new_api.company', 'default') self.env['ir.property']._set_default('foo', 'test_new_api.company', 'default1', company1) self.env['ir.property']._set_default('tag_id', 'test_new_api.company', tag0) # assumption: users don't have access to 'ir.property' accesses = self.env['ir.model.access'].search([('model_id.model', '=', 'ir.property')]) accesses.write(dict.fromkeys(['perm_read', 'perm_write', 'perm_create', 'perm_unlink'], False)) # create/modify a record, and check the value for each user record = self.env['test_new_api.company'].create({ 'foo': 'main', 'date': '1932-11-09', 'moment': '1932-11-09 00:00:00', 'tag_id': tag1.id, }) self.assertEqual(record.with_user(user0).foo, 'main') self.assertEqual(record.with_user(user1).foo, 'default1') self.assertEqual(record.with_user(user2).foo, 'default') self.assertEqual(str(record.with_user(user0).date), '1932-11-09') self.assertEqual(record.with_user(user1).date, False) self.assertEqual(record.with_user(user2).date, False) self.assertEqual(str(record.with_user(user0).moment), '1932-11-09 00:00:00') self.assertEqual(record.with_user(user1).moment, False) self.assertEqual(record.with_user(user2).moment, False) self.assertEqual(record.with_user(user0).tag_id, tag1) self.assertEqual(record.with_user(user1).tag_id, tag0) self.assertEqual(record.with_user(user2).tag_id, tag0) record.with_user(user1).write({ 'foo': 'alpha', 'date': '1932-12-10', 'moment': '1932-12-10 23:59:59', 'tag_id': tag2.id, }) self.assertEqual(record.with_user(user0).foo, 'main') self.assertEqual(record.with_user(user1).foo, 'alpha') self.assertEqual(record.with_user(user2).foo, 'default') self.assertEqual(str(record.with_user(user0).date), '1932-11-09') self.assertEqual(str(record.with_user(user1).date), '1932-12-10') self.assertEqual(record.with_user(user2).date, False) self.assertEqual(str(record.with_user(user0).moment), '1932-11-09 00:00:00') self.assertEqual(str(record.with_user(user1).moment), '1932-12-10 23:59:59') self.assertEqual(record.with_user(user2).moment, False) self.assertEqual(record.with_user(user0).tag_id, tag1) self.assertEqual(record.with_user(user1).tag_id, tag2) self.assertEqual(record.with_user(user2).tag_id, tag0) # regression: duplicated records caused values to be browse(browse(id)) recs = record.create({}) + record + record recs.invalidate_cache() for rec in recs.with_user(user0): self.assertIsInstance(rec.tag_id.id, int) # unlink value of a many2one (tag2), and check again tag2.unlink() self.assertEqual(record.with_user(user0).tag_id, tag1) self.assertEqual(record.with_user(user1).tag_id, tag0.browse()) self.assertEqual(record.with_user(user2).tag_id, tag0) record.with_user(user1).foo = False self.assertEqual(record.with_user(user0).foo, 'main') self.assertEqual(record.with_user(user1).foo, False) self.assertEqual(record.with_user(user2).foo, 'default') record.with_user(user0).with_company(company1).foo = 'beta' record.invalidate_cache() self.assertEqual(record.with_user(user0).foo, 'main') self.assertEqual(record.with_user(user1).foo, 'beta') self.assertEqual(record.with_user(user2).foo, 'default') # add group on company-dependent field self.assertFalse(user0.has_group('base.group_system')) self.patch(type(record).foo, 'groups', 'base.group_system') with self.assertRaises(AccessError): record.with_user(user0).foo = 'forbidden' record.flush() user0.write({'groups_id': [Command.link(self.env.ref('base.group_system').id)]}) record.with_user(user0).foo = 'yes we can' # add ir.rule to prevent access on record self.assertTrue(user0.has_group('base.group_user')) rule = self.env['ir.rule'].create({ 'model_id': self.env['ir.model']._get_id(record._name), 'groups': [self.env.ref('base.group_user').id], 'domain_force': str([('id', '!=', record.id)]), }) with self.assertRaises(AccessError): record.with_user(user0).foo = 'forbidden' record.flush() # create company record and attribute company_record = self.env['test_new_api.company'].create({'foo': 'ABC'}) attribute_record = self.env['test_new_api.company.attr'].create({ 'company': company_record.id, 'quantity': 1, }) self.assertEqual(attribute_record.bar, 'ABC') # change quantity, 'bar' should recompute to 'ABCABC' attribute_record.quantity = 2 self.assertEqual(attribute_record.bar, 'ABCABC') # change company field 'foo', 'bar' should recompute to 'DEFDEF' company_record.foo = 'DEF' self.assertEqual(attribute_record.company.foo, 'DEF') self.assertEqual(attribute_record.bar, 'DEFDEF') # a low priviledge user should be able to search on company_dependent fields company_record.env.user.groups_id -= self.env.ref('base.group_system') self.assertFalse(company_record.env.user.has_group('base.group_system')) company_records = self.env['test_new_api.company'].search([('foo', '=', 'DEF')]) self.assertEqual(len(company_records), 1) def test_28_company_dependent_search(self): """ Test the search on company-dependent fields in all corner cases. This assumes that filtered_domain() correctly filters records when its domain refers to company-dependent fields. """ Property = self.env['ir.property'] Model = self.env['test_new_api.company'] # create 4 records for all cases: two with explicit truthy values, one # with an explicit falsy value, and one without an explicit value records = Model.create([{}] * 4) # For each field, we assign values to the records, and test a number of # searches. The search cases are given by comparison operators, and for # each operator, we test a number of possible operands. Every search() # returns a subset of the records, and we compare it to an equivalent # search performed by filtered_domain(). def test_field(field_name, truthy_values, operations): # set ir.properties to all records except the last one Property._set_multi( field_name, Model._name, {rec.id: val for rec, val in zip(records, truthy_values + [False])}, # Using this sentinel for 'default_value' forces the method to # create 'ir.property' records for the value False. Without it, # no property would be created because False is the default # value. default_value=object(), ) # test without default value test_cases(field_name, operations) # set default value to False Property._set_default(field_name, Model._name, False) Property.flush() Property.invalidate_cache() test_cases(field_name, operations, False) # set default value to truthy_values[0] Property._set_default(field_name, Model._name, truthy_values[0]) Property.flush() Property.invalidate_cache() test_cases(field_name, operations, truthy_values[0]) def test_cases(field_name, operations, default=None): for operator, values in operations.items(): for value in values: domain = [(field_name, operator, value)] with self.subTest(domain=domain, default=default): search_result = Model.search([('id', 'in', records.ids)] + domain) filter_result = records.filtered_domain(domain) self.assertEqual( search_result, filter_result, f"Got values {[r[field_name] for r in search_result]} " f"instead of {[r[field_name] for r in filter_result]}", ) # boolean fields test_field('truth', [True, True], { '=': (True, False), '!=': (True, False), }) # integer fields test_field('count', [10, -2], { '=': (10, -2, 0, False), '!=': (10, -2, 0, False), '<': (10, -2, 0), '>=': (10, -2, 0), '<=': (10, -2, 0), '>': (10, -2, 0), }) # float fields test_field('phi', [1.61803, -1], { '=': (1.61803, -1, 0, False), '!=': (1.61803, -1, 0, False), '<': (1.61803, -1, 0), '>=': (1.61803, -1, 0), '<=': (1.61803, -1, 0), '>': (1.61803, -1, 0), }) # char fields test_field('foo', ['qwer', 'azer'], { 'like': ('qwer', 'azer'), 'ilike': ('qwer', 'azer'), 'not like': ('qwer', 'azer'), 'not ilike': ('qwer', 'azer'), '=': ('qwer', 'azer', False), '!=': ('qwer', 'azer', False), 'not in': (['qwer', 'azer'], ['qwer', False], [False], []), 'in': (['qwer', 'azer'], ['qwer', False], [False], []), }) # date fields date1, date2 = date(2021, 11, 22), date(2021, 11, 23) test_field('date', [date1, date2], { '=': (date1, date2, False), '!=': (date1, date2, False), '<': (date1, date2), '>=': (date1, date2), '<=': (date1, date2), '>': (date1, date2), }) # datetime fields moment1, moment2 = datetime(2021, 11, 22), datetime(2021, 11, 23) test_field('moment', [moment1, moment2], { '=': (moment1, moment2, False), '!=': (moment1, moment2, False), '<': (moment1, moment2), '>=': (moment1, moment2), '<=': (moment1, moment2), '>': (moment1, moment2), }) # many2one fields tag1, tag2 = self.env['test_new_api.multi.tag'].create([{'name': 'one'}, {'name': 'two'}]) test_field('tag_id', [tag1.id, tag2.id], { 'like': (tag1.name, tag2.name), 'ilike': (tag1.name, tag2.name), 'not like': (tag1.name, tag2.name), 'not ilike': (tag1.name, tag2.name), '=': (tag1.id, tag2.id, False), '!=': (tag1.id, tag2.id, False), 'in': ([tag1.id, tag2.id], [tag2.id, False], [False], []), 'not in': ([tag1.id, tag2.id], [tag2.id, False], [False], []), }) def test_30_read(self): """ test computed fields as returned by read(). """ discussion = self.env.ref('test_new_api.discussion_0') for message in discussion.messages: display_name = message.display_name size = message.size data = message.read(['display_name', 'size'])[0] self.assertEqual(data['display_name'], display_name) self.assertEqual(data['size'], size) def test_31_prefetch(self): """ test prefetch of records handle AccessError """ Category = self.env['test_new_api.category'] cat1 = Category.create({'name': 'NOACCESS'}) cat2 = Category.create({'name': 'ACCESS', 'parent': cat1.id}) cats = cat1 + cat2 self.env.clear() cat1, cat2 = cats self.assertEqual(cat2.name, 'ACCESS') # both categories should be ready for prefetching self.assertItemsEqual(cat2._prefetch_ids, cats.ids) # but due to our (lame) overwrite of `read`, it should not forbid us to read records we have access to self.assertFalse(cat2.discussions) self.assertEqual(cat2.parent, cat1) with self.assertRaises(AccessError): cat1.name def test_32_prefetch_missing_error(self): """ Test that prefetching non-column fields works in the presence of deleted records. """ Discussion = self.env['test_new_api.discussion'] # add an ir.rule that forces reading field 'name' self.env['ir.rule'].create({ 'model_id': self.env['ir.model']._get(Discussion._name).id, 'groups': [self.env.ref('base.group_user').id], 'domain_force': "[('name', '!=', 'Super Secret discution')]", }) records = Discussion.with_user(self.user_demo).create([ {'name': 'EXISTING'}, {'name': 'MISSING'}, ]) # unpack to keep the prefetch on each recordset existing, deleted = records self.assertEqual(existing._prefetch_ids, records._ids) # this invalidates the caches but the prefetching remains the same deleted.unlink() # this should not trigger a MissingError existing.categories # invalidate 'categories' for the assertQueryCount existing.invalidate_cache(['categories']) with self.assertQueryCount(4): # <categories>.__get__(existing) # -> records._fetch_field(['categories']) # -> records._read(['categories']) # -> records.check_access_rule('read') # -> records._filter_access_rules_python('read') # -> records.filtered_domain(...) # -> <name>.__get__(existing) # -> records._fetch_field(['name']) # -> records._read(['name', ...]) # -> ONE QUERY to read ['name', ...] of records # -> ONE QUERY for deleted.exists() / code: forbidden = missing.exists() # -> ONE QUERY for records.exists() / code: self = self.exists() # -> ONE QUERY to read the many2many of existing existing.categories # this one must trigger a MissingError with self.assertRaises(MissingError): deleted.categories # special case: should not fail Discussion.browse([None]).read(['categories']) def test_40_real_vs_new(self): """ test field access on new records vs real records. """ Model = self.env['test_new_api.category'] real_record = Model.create({'name': 'Foo'}) self.env.cache.invalidate() new_origin = Model.new({'name': 'Bar'}, origin=real_record) new_record = Model.new({'name': 'Baz'}) # non-computed non-stored field: default value real_record = real_record.with_context(default_dummy='WTF') new_origin = new_origin.with_context(default_dummy='WTF') new_record = new_record.with_context(default_dummy='WTF') self.assertEqual(real_record.dummy, 'WTF') self.assertEqual(new_origin.dummy, 'WTF') self.assertEqual(new_record.dummy, 'WTF') # non-computed stored field: origin or default if no origin real_record = real_record.with_context(default_color=42) new_origin = new_origin.with_context(default_color=42) new_record = new_record.with_context(default_color=42) self.assertEqual(real_record.color, 0) self.assertEqual(new_origin.color, 0) self.assertEqual(new_record.color, 42) # computed non-stored field: always computed self.assertEqual(real_record.display_name, 'Foo') self.assertEqual(new_origin.display_name, 'Bar') self.assertEqual(new_record.display_name, 'Baz') # computed stored field: origin or computed if no origin Model = self.env['test_new_api.recursive'] real_record = Model.create({'name': 'Foo'}) new_origin = Model.new({'name': 'Bar'}, origin=real_record) new_record = Model.new({'name': 'Baz'}) self.assertEqual(real_record.display_name, 'Foo') self.assertEqual(new_origin.display_name, 'Bar') self.assertEqual(new_record.display_name, 'Baz') # computed stored field with recomputation: always computed real_record.name = 'Fool' new_origin.name = 'Barr' new_record.name = 'Bazz' self.assertEqual(real_record.display_name, 'Fool') self.assertEqual(new_origin.display_name, 'Barr') self.assertEqual(new_record.display_name, 'Bazz') def test_40_new_defaults(self): """ Test new records with defaults. """ user = self.env.user discussion = self.env.ref('test_new_api.discussion_0') # create a new message; fields have their default value if not given new_msg = self.env['test_new_api.message'].new({'body': "XXX"}) self.assertFalse(new_msg.id) self.assertEqual(new_msg.body, "XXX") self.assertEqual(new_msg.author, user) # assign some fields; should have no side effect new_msg.discussion = discussion new_msg.body = "YYY" self.assertEqual(new_msg.discussion, discussion) self.assertEqual(new_msg.body, "YYY") self.assertNotIn(new_msg, discussion.messages) # check computed values of fields self.assertEqual(new_msg.name, "[%s] %s" % (discussion.name, user.name)) self.assertEqual(new_msg.size, 3) # extra tests for x2many fields with default cat1 = self.env['test_new_api.category'].create({'name': "Cat1"}) cat2 = self.env['test_new_api.category'].create({'name': "Cat2"}) discussion = discussion.with_context(default_categories=[Command.link(cat1.id)]) # no value gives the default value new_disc = discussion.new({'name': "Foo"}) self.assertEqual(new_disc.categories._origin, cat1) # value overrides default value new_disc = discussion.new({'name': "Foo", 'categories': [Command.link(cat2.id)]}) self.assertEqual(new_disc.categories._origin, cat2) def test_40_new_fields(self): """ Test new records with relational fields. """ # create a new discussion with all kinds of relational fields msg0 = self.env['test_new_api.message'].create({'body': "XXX"}) msg1 = self.env['test_new_api.message'].create({'body': "WWW"}) cat0 = self.env['test_new_api.category'].create({'name': 'AAA'}) cat1 = self.env['test_new_api.category'].create({'name': 'DDD'}) new_disc = self.env['test_new_api.discussion'].new({ 'name': "Stuff", 'moderator': self.env.uid, 'messages': [ Command.link(msg0.id), Command.link(msg1.id), Command.update(msg1.id, {'body': "YYY"}), Command.create({'body': "ZZZ"}) ], 'categories': [ Command.link(cat0.id), Command.link(cat1.id), Command.update(cat1.id, {'name': "BBB"}), Command.create({'name': "CCC"}) ], }) self.assertFalse(new_disc.id) # many2one field values are actual records self.assertEqual(new_disc.moderator.id, self.env.uid) # x2many fields values are new records new_msg0, new_msg1, new_msg2 = new_disc.messages self.assertFalse(new_msg0.id) self.assertFalse(new_msg1.id) self.assertFalse(new_msg2.id) new_cat0, new_cat1, new_cat2 = new_disc.categories self.assertFalse(new_cat0.id) self.assertFalse(new_cat1.id) self.assertFalse(new_cat2.id) # the x2many has its inverse field set self.assertEqual(new_msg0.discussion, new_disc) self.assertEqual(new_msg1.discussion, new_disc) self.assertEqual(new_msg2.discussion, new_disc) self.assertFalse(msg0.discussion) self.assertFalse(msg1.discussion) self.assertEqual(new_cat0.discussions, new_disc) # add other discussions self.assertEqual(new_cat1.discussions, new_disc) self.assertEqual(new_cat2.discussions, new_disc) self.assertNotIn(new_disc, cat0.discussions) self.assertNotIn(new_disc, cat1.discussions) # new lines are connected to their origin self.assertEqual(new_msg0._origin, msg0) self.assertEqual(new_msg1._origin, msg1) self.assertFalse(new_msg2._origin) self.assertEqual(new_cat0._origin, cat0) self.assertEqual(new_cat1._origin, cat1) self.assertFalse(new_cat2._origin) # the field values are either specific, or the same as the origin self.assertEqual(new_msg0.body, "XXX") self.assertEqual(new_msg1.body, "YYY") self.assertEqual(new_msg2.body, "ZZZ") self.assertEqual(msg0.body, "XXX") self.assertEqual(msg1.body, "WWW") self.assertEqual(new_cat0.name, "AAA") self.assertEqual(new_cat1.name, "BBB") self.assertEqual(new_cat2.name, "CCC") self.assertEqual(cat0.name, "AAA") self.assertEqual(cat1.name, "DDD") # special case for many2one fields that define _inherits new_email = self.env['test_new_api.emailmessage'].new({'body': "XXX"}) self.assertFalse(new_email.id) self.assertTrue(new_email.message) self.assertFalse(new_email.message.id) self.assertEqual(new_email.body, "XXX") new_email = self.env['test_new_api.emailmessage'].new({'message': msg0.id}) self.assertFalse(new_email.id) self.assertFalse(new_email._origin) self.assertFalse(new_email.message.id) self.assertEqual(new_email.message._origin, msg0) self.assertEqual(new_email.body, "XXX") # check that this does not generate an infinite recursion new_disc._convert_to_write(new_disc._cache) def test_40_new_inherited_fields(self): """ Test the behavior of new records with inherited fields. """ email = self.env['test_new_api.emailmessage'].new({'body': 'XXX'}) self.assertEqual(email.body, 'XXX') self.assertEqual(email.message.body, 'XXX') email.body = 'YYY' self.assertEqual(email.body, 'YYY') self.assertEqual(email.message.body, 'YYY') email.message.body = 'ZZZ' self.assertEqual(email.body, 'ZZZ') self.assertEqual(email.message.body, 'ZZZ') def test_40_new_ref_origin(self): """ Test the behavior of new records with ref/origin. """ Discussion = self.env['test_new_api.discussion'] new = Discussion.new # new records with identical/different refs xs = new() + new(ref='a') + new(ref='b') + new(ref='b') self.assertEqual([x == y for x in xs for y in xs], [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, ]) for x in xs: self.assertFalse(x._origin) # new records with identical/different origins a, b = Discussion.create([{'name': "A"}, {'name': "B"}]) xs = new() + new(origin=a) + new(origin=b) + new(origin=b) self.assertEqual([x == y for x in xs for y in xs], [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, ]) self.assertFalse(xs[0]._origin) self.assertEqual(xs[1]._origin, a) self.assertEqual(xs[2]._origin, b) self.assertEqual(xs[3]._origin, b) self.assertEqual(xs._origin, a + b + b) self.assertEqual(xs._origin._origin, a + b + b) # new records with refs and origins x1 = new(ref='a') x2 = new(origin=b) self.assertNotEqual(x1, x2) # new discussion based on existing discussion disc = self.env.ref('test_new_api.discussion_0') new_disc = disc.new(origin=disc) self.assertFalse(new_disc.id) self.assertEqual(new_disc._origin, disc) self.assertEqual(new_disc.name, disc.name) # many2one field self.assertEqual(new_disc.moderator, disc.moderator) # one2many field self.assertTrue(new_disc.messages) self.assertNotEqual(new_disc.messages, disc.messages) self.assertEqual(new_disc.messages._origin, disc.messages) # many2many field self.assertTrue(new_disc.participants) self.assertNotEqual(new_disc.participants, disc.participants) self.assertEqual(new_disc.participants._origin, disc.participants) # provide many2one field as a dict of values; the value is a new record # with the given 'id' as origin (if given, of course) new_msg = disc.messages.new({ 'discussion': {'name': disc.name}, }) self.assertTrue(new_msg.discussion) self.assertFalse(new_msg.discussion.id) self.assertFalse(new_msg.discussion._origin) new_msg = disc.messages.new({ 'discussion': {'name': disc.name, 'id': disc.id}, }) self.assertTrue(new_msg.discussion) self.assertFalse(new_msg.discussion.id) self.assertEqual(new_msg.discussion._origin, disc) # check convert_to_write tag = self.env['test_new_api.multi.tag'].create({'name': 'Foo'}) rec = self.env['test_new_api.multi'].create({ 'lines': [(0, 0, {'tags': [(6, 0, tag.ids)]})], }) new = rec.new(origin=rec) self.assertEqual(new.lines.tags._origin, rec.lines.tags) vals = new._convert_to_write(new._cache) self.assertEqual(vals['lines'], [(6, 0, rec.lines.ids)]) def test_41_new_compute(self): """ Check recomputation of fields on new records. """ move = self.env['test_new_api.move'].create({ 'line_ids': [Command.create({'quantity': 1}), Command.create({'quantity': 1})], }) move.flush() line = move.line_ids[0] new_move = move.new(origin=move) new_line = line.new(origin=line) # move_id is fetched from origin self.assertEqual(new_line.move_id, move) self.assertEqual(new_move.quantity, 2) self.assertEqual(move.quantity, 2) # modifying new_line must trigger recomputation on new_move, even if # new_line.move_id is not new_move! new_line.quantity = 2 self.assertEqual(new_line.move_id, move) self.assertEqual(new_move.quantity, 3) self.assertEqual(move.quantity, 2) def test_41_new_one2many(self): """ Check command on one2many field on new record. """ move = self.env['test_new_api.move'].create({}) line = self.env['test_new_api.move_line'].create({'move_id': move.id, 'quantity': 1}) move.flush() new_move = move.new(origin=move) new_line = line.new(origin=line) self.assertEqual(new_move.line_ids, new_line) # drop line, and create a new one new_move.line_ids = [Command.delete(new_line.id), Command.create({'quantity': 2})] self.assertEqual(len(new_move.line_ids), 1) self.assertFalse(new_move.line_ids.id) self.assertEqual(new_move.line_ids.quantity, 2) # assign line to new move without origin new_move = move.new() new_move.line_ids = line self.assertFalse(new_move.line_ids.id) self.assertEqual(new_move.line_ids._origin, line) self.assertEqual(new_move.line_ids.move_id, new_move) @mute_logger('odoo.addons.base.models.ir_model') def test_41_new_related(self): """ test the behavior of related fields starting on new records. """ # make discussions unreadable for demo user access = self.env.ref('test_new_api.access_discussion') access.write({'perm_read': False}) # create an environment for demo user env = self.env(user=self.user_demo) self.assertEqual(env.user.login, "demo") # create a new message as demo user discussion = self.env.ref('test_new_api.discussion_0') message = env['test_new_api.message'].new({'discussion': discussion}) self.assertEqual(message.discussion, discussion) # read the related field discussion_name self.assertEqual(message.discussion.env, env) self.assertEqual(message.discussion_name, discussion.name) # DLE P75: message.discussion.name is put in the cache as sudo thanks to the computation of message.discussion_name # As we decided that now if we had the chance to access the value at some point in the code, and that it was stored in the cache # it's not a big deal to no longer raise the accesserror, as we had the chance to get the value at some point # with self.assertRaises(AccessError): # message.discussion.name @mute_logger('odoo.addons.base.models.ir_model') def test_42_new_related(self): """ test the behavior of related fields traversing new records. """ # make discussions unreadable for demo user access = self.env.ref('test_new_api.access_discussion') access.write({'perm_read': False}) # create an environment for demo user env = self.env(user=self.user_demo) self.assertEqual(env.user.login, "demo") # create a new discussion and a new message as demo user discussion = env['test_new_api.discussion'].new({'name': 'Stuff'}) message = env['test_new_api.message'].new({'discussion': discussion}) self.assertEqual(message.discussion, discussion) # read the related field discussion_name self.assertNotEqual(message.sudo().env, message.env) self.assertEqual(message.discussion_name, discussion.name) def test_43_new_related(self): """ test the behavior of one2many related fields """ partner = self.env['res.partner'].create({ 'name': 'Foo', 'child_ids': [Command.create({'name': 'Bar'})], }) multi = self.env['test_new_api.multi'].new() multi.partner = partner self.assertEqual(multi.partners.mapped('name'), ['Bar']) def test_50_defaults(self): """ test default values. """ fields = ['discussion', 'body', 'author', 'size'] defaults = self.env['test_new_api.message'].default_get(fields) self.assertEqual(defaults, {'author': self.env.uid}) defaults = self.env['test_new_api.mixed'].default_get(['number']) self.assertEqual(defaults, {'number': 3.14}) def test_50_search_many2one(self): """ test search through a path of computed fields""" messages = self.env['test_new_api.message'].search( [('author_partner.name', '=', 'Marc Demo')]) self.assertEqual(messages, self.env.ref('test_new_api.message_0_1')) def test_60_one2many_domain(self): """ test the cache consistency of a one2many field with a domain """ discussion = self.env.ref('test_new_api.discussion_0') message = discussion.messages[0] self.assertNotIn(message, discussion.important_messages) message.important = True self.assertIn(message, discussion.important_messages) # writing on very_important_messages should call its domain method self.assertIn(message, discussion.very_important_messages) discussion.write({'very_important_messages': [Command.clear()]}) self.assertFalse(discussion.very_important_messages) self.assertFalse(message.exists()) def test_60_many2many_domain(self): """ test the cache consistency of a many2many field with a domain """ tag = self.env['test_new_api.multi.tag'].create({'name': 'bar'}) record = self.env['test_new_api.multi'].create({'tags': tag.ids}) record.flush() record.invalidate_cache() self.assertEqual(type(record).tags.domain, [('name', 'ilike', 'a')]) # the tag is in the many2many self.assertIn(tag, record.tags) # modify the tag; it should not longer be in the many2many tag.name = 'foo' self.assertNotIn(tag, record.tags) # modify again the tag; it should be back in the many2many tag.name = 'baz' self.assertIn(tag, record.tags) def test_70_x2many_write(self): discussion = self.env.ref('test_new_api.discussion_0') # See YTI FIXME discussion.invalidate_cache() Message = self.env['test_new_api.message'] # There must be 3 messages, 0 important self.assertEqual(len(discussion.messages), 3) self.assertEqual(len(discussion.important_messages), 0) self.assertEqual(len(discussion.very_important_messages), 0) discussion.important_messages = [Command.create({ 'body': 'What is the answer?', 'important': True, })] # There must be 4 messages, 1 important self.assertEqual(len(discussion.messages), 4) self.assertEqual(len(discussion.important_messages), 1) self.assertEqual(len(discussion.very_important_messages), 1) discussion.very_important_messages |= Message.new({ 'body': '42', 'important': True, }) # There must be 5 messages, 2 important self.assertEqual(len(discussion.messages), 5) self.assertEqual(len(discussion.important_messages), 2) self.assertEqual(len(discussion.very_important_messages), 2) def test_70_relational_inverse(self): """ Check the consistency of relational fields with inverse(s). """ discussion = self.env.ref('test_new_api.discussion_0') demo_discussion = discussion.with_user(self.user_demo) # check that the demo user sees the same messages self.assertEqual(demo_discussion.messages, discussion.messages) # See YTI FIXME discussion.invalidate_cache() demo_discussion.invalidate_cache() # add a message as user demo messages = demo_discussion.messages message = messages.create({'discussion': discussion.id}) self.assertEqual(demo_discussion.messages, messages + message) self.assertEqual(demo_discussion.messages, discussion.messages) # add a message as superuser messages = discussion.messages message = messages.create({'discussion': discussion.id}) self.assertEqual(discussion.messages, messages + message) self.assertEqual(demo_discussion.messages, discussion.messages) def test_71_relational_inverse(self): """ Check the consistency of relational fields with inverse(s). """ move1 = self.env['test_new_api.move'].create({}) move2 = self.env['test_new_api.move'].create({}) line = self.env['test_new_api.move_line'].create({'move_id': move1.id}) line.flush() self.env.cache.invalidate() line.with_context(prefetch_fields=False).move_id # Setting 'move_id' updates the one2many field that is based on it, # which has a domain. Here we check that evaluating the domain does not # accidentally override 'move_id' (by prefetch). line.move_id = move2 self.assertEqual(line.move_id, move2) def test_72_relational_inverse(self): """ Check the consistency of relational fields with inverse(s). """ move1 = self.env['test_new_api.move'].create({}) move2 = self.env['test_new_api.move'].create({}) # makes sure that line.move_id is flushed before search line = self.env['test_new_api.move_line'].create({'move_id': move1.id}) moves = self.env['test_new_api.move'].search([('line_ids', 'in', line.id)]) self.assertEqual(moves, move1) # makes sure that line.move_id is flushed before search line.move_id = move2 moves = self.env['test_new_api.move'].search([('line_ids', 'in', line.id)]) self.assertEqual(moves, move2) def test_73_relational_inverse(self): """ Check the consistency of relational fields with inverse(s). """ discussion1, discussion2 = self.env['test_new_api.discussion'].create([ {'name': "discussion1"}, {'name': "discussion2"}, ]) category1, category2 = self.env['test_new_api.category'].create([ {'name': "category1"}, {'name': "category2"}, ]) # assumption: category12 and category21 are in different order, but are # in the same order when put in a set() category12 = category1 + category2 category21 = category2 + category1 self.assertNotEqual(category12.ids, category21.ids) self.assertEqual(list(set(category12.ids)), list(set(category21.ids))) # make sure discussion1.categories is in cache; the write() below should # update the cache of discussion1.categories by appending category12.ids discussion1.categories category12.write({'discussions': [Command.link(discussion1.id)]}) self.assertEqual(discussion1.categories.ids, category12.ids) # make sure discussion2.categories is in cache; the write() below should # update the cache of discussion2.categories by appending category21.ids discussion2.categories category21.write({'discussions': [Command.link(discussion2.id)]}) self.assertEqual(discussion2.categories.ids, category21.ids) def test_80_copy(self): Translations = self.env['ir.translation'] discussion = self.env.ref('test_new_api.discussion_0') message = self.env.ref('test_new_api.message_0_0') message1 = self.env.ref('test_new_api.message_0_1') email = self.env.ref('test_new_api.emailmessage_0_0') self.assertEqual(email.message, message) self.env['res.lang']._activate_lang('fr_FR') def count(msg): # return the number of translations of msg.label return Translations.search_count([ ('name', '=', 'test_new_api.message,label'), ('res_id', '=', msg.id), ]) # set a translation for message.label email.with_context(lang='fr_FR').label = "bonjour" self.assertEqual(count(message), 1) self.assertEqual(count(message1), 0) # setting the parent record should not copy its translations email.copy({'message': message1.id}) self.assertEqual(count(message), 1) self.assertEqual(count(message1), 0) # setting a one2many should not copy translations on the lines discussion.copy({'messages': [Command.set(message1.ids)]}) self.assertEqual(count(message), 1) self.assertEqual(count(message1), 0) def test_85_binary_guess_zip(self): from odoo.addons.base.tests.test_mimetypes import ZIP # Regular ZIP files can be uploaded by non-admin users self.env['test_new_api.binary_svg'].with_user( self.env.ref('base.user_demo'), ).create({ 'name': 'Test without attachment', 'image_wo_attachment': base64.b64decode(ZIP), }) def test_86_text_base64_guess_svg(self): from odoo.addons.base.tests.test_mimetypes import SVG with self.assertRaises(UserError) as e: self.env['test_new_api.binary_svg'].with_user( self.env.ref('base.user_demo'), ).create({ 'name': 'Test without attachment', 'image_wo_attachment': SVG.decode("utf-8"), }) self.assertEqual(e.exception.args[0], 'Only admins can upload SVG files.') def test_90_binary_svg(self): from odoo.addons.base.tests.test_mimetypes import SVG # This should work without problems self.env['test_new_api.binary_svg'].create({ 'name': 'Test without attachment', 'image_wo_attachment': SVG, }) # And this gives error with self.assertRaises(UserError): self.env['test_new_api.binary_svg'].with_user( self.user_demo, ).create({ 'name': 'Test without attachment', 'image_wo_attachment': SVG, }) def test_91_binary_svg_attachment(self): from odoo.addons.base.tests.test_mimetypes import SVG # This doesn't neuter SVG with admin record = self.env['test_new_api.binary_svg'].create({ 'name': 'Test without attachment', 'image_attachment': SVG, }) attachment = self.env['ir.attachment'].search([ ('res_model', '=', record._name), ('res_field', '=', 'image_attachment'), ('res_id', '=', record.id), ]) self.assertEqual(attachment.mimetype, 'image/svg+xml') # ...but this should be neutered with demo user record = self.env['test_new_api.binary_svg'].with_user( self.user_demo, ).create({ 'name': 'Test without attachment', 'image_attachment': SVG, }) attachment = self.env['ir.attachment'].search([ ('res_model', '=', record._name), ('res_field', '=', 'image_attachment'), ('res_id', '=', record.id), ]) self.assertEqual(attachment.mimetype, 'text/plain') def test_92_binary_self_avatar_svg(self): from odoo.addons.base.tests.test_mimetypes import SVG demo_user = self.user_demo # User demo changes his own avatar demo_user.with_user(demo_user).image_1920 = SVG # The SVG file should have been neutered attachment = self.env['ir.attachment'].search([ ('res_model', '=', demo_user.partner_id._name), ('res_field', '=', 'image_1920'), ('res_id', '=', demo_user.partner_id.id), ]) self.assertEqual(attachment.mimetype, 'text/plain') def test_93_monetary_related(self): """ Check the currency field on related monetary fields. """ # check base field model = self.env['test_new_api.monetary_base'] field = model._fields['amount'] self.assertEqual(field.get_currency_field(model), 'base_currency_id') # related fields must use the field 'currency_id' or 'x_currency_id' model = self.env['test_new_api.monetary_related'] field = model._fields['amount'] self.assertEqual(field.related, 'monetary_id.amount') self.assertEqual(field.get_currency_field(model), 'currency_id') model = self.env['test_new_api.monetary_custom'] field = model._fields['x_amount'] self.assertEqual(field.related, 'monetary_id.amount') self.assertEqual(field.get_currency_field(model), 'x_currency_id') # inherited field must use the same field as its parent field model = self.env['test_new_api.monetary_inherits'] field = model._fields['amount'] self.assertEqual(field.related, 'monetary_id.amount') self.assertEqual(field.get_currency_field(model), 'base_currency_id') def test_94_image(self): f = io.BytesIO() Image.new('RGB', (4000, 2000), '#4169E1').save(f, 'PNG') f.seek(0) image_w = base64.b64encode(f.read()) f = io.BytesIO() Image.new('RGB', (2000, 4000), '#4169E1').save(f, 'PNG') f.seek(0) image_h = base64.b64encode(f.read()) record = self.env['test_new_api.model_image'].create({ 'name': 'image', 'image': image_w, 'image_128': image_w, }) # test create (no resize) self.assertEqual(record.image, image_w) # test create (resize, width limited) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_128))).size, (128, 64)) # test create related store (resize, width limited) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_512))).size, (512, 256)) # test create related no store (resize, width limited) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_256))).size, (256, 128)) record.write({ 'image': image_h, 'image_128': image_h, }) # test write (no resize) self.assertEqual(record.image, image_h) # test write (resize, height limited) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_128))).size, (64, 128)) # test write related store (resize, height limited) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_512))).size, (256, 512)) # test write related no store (resize, height limited) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_256))).size, (128, 256)) record = self.env['test_new_api.model_image'].create({ 'name': 'image', 'image': image_h, 'image_128': image_h, }) # test create (no resize) self.assertEqual(record.image, image_h) # test create (resize, height limited) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_128))).size, (64, 128)) # test create related store (resize, height limited) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_512))).size, (256, 512)) # test create related no store (resize, height limited) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_256))).size, (128, 256)) record.write({ 'image': image_w, 'image_128': image_w, }) # test write (no resize) self.assertEqual(record.image, image_w) # test write (resize, width limited) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_128))).size, (128, 64)) # test write related store (resize, width limited) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_512))).size, (512, 256)) # test write related store (resize, width limited) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_256))).size, (256, 128)) # test create inverse store record = self.env['test_new_api.model_image'].create({ 'name': 'image', 'image_512': image_w, }) record.invalidate_cache(fnames=['image_512'], ids=record.ids) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_512))).size, (512, 256)) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image))).size, (4000, 2000)) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_256))).size, (256, 128)) # test write inverse store record.write({ 'image_512': image_h, }) record.invalidate_cache(fnames=['image_512'], ids=record.ids) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_512))).size, (256, 512)) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image))).size, (2000, 4000)) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_256))).size, (128, 256)) # test create inverse no store record = self.env['test_new_api.model_image'].with_context(image_no_postprocess=True).create({ 'name': 'image', 'image_256': image_w, }) record.invalidate_cache(fnames=['image_256'], ids=record.ids) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_512))).size, (512, 256)) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image))).size, (4000, 2000)) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_256))).size, (256, 128)) # test write inverse no store record.write({ 'image_256': image_h, }) record.invalidate_cache(fnames=['image_256'], ids=record.ids) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_512))).size, (256, 512)) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image))).size, (2000, 4000)) self.assertEqual(Image.open(io.BytesIO(base64.b64decode(record.image_256))).size, (128, 256)) # test bin_size record_bin_size = record.with_context(bin_size=True) self.assertEqual(record_bin_size.image, b'31.54 Kb') self.assertEqual(record_bin_size.image_512, b'1.02 Kb') self.assertEqual(record_bin_size.image_256, b'424.00 bytes') # ensure image_data_uri works (value must be bytes and not string) self.assertEqual(record.image_256[:8], b'iVBORw0K') self.assertEqual(image_data_uri(record.image_256)[:30], 'data:image/png;base64,iVBORw0K') # ensure invalid image raises with self.assertRaises(UserError), self.cr.savepoint(): record.write({ 'image': 'invalid image', }) # assignment of invalid image on new record does nothing, the value is # taken from origin instead (use-case: onchange) new_record = record.new(origin=record) new_record.image = '31.54 Kb' self.assertEqual(record.image, image_h) self.assertEqual(new_record.image, image_h) # assignment to new record with origin should not do any query with self.assertQueryCount(0): new_record.image = image_w def test_95_binary_bin_size(self): binary_value = base64.b64encode(b'content') binary_size = b'7.00 bytes' def assertBinaryValue(record, value): for field in ('binary', 'binary_related_store', 'binary_related_no_store'): self.assertEqual(record[field], value) # created, flushed, and first read without context record = self.env['test_new_api.model_binary'].create({'binary': binary_value}) record.flush() record.invalidate_cache() record_no_bin_size = record.with_context(bin_size=False) record_bin_size = record.with_context(bin_size=True) assertBinaryValue(record, binary_value) assertBinaryValue(record_no_bin_size, binary_value) assertBinaryValue(record_bin_size, binary_size) # created, flushed, and first read with bin_size=False record_no_bin_size = self.env['test_new_api.model_binary'].with_context(bin_size=False).create({'binary': binary_value}) record_no_bin_size.flush() record_no_bin_size.invalidate_cache() record = self.env['test_new_api.model_binary'].browse(record.id) record_bin_size = record.with_context(bin_size=True) assertBinaryValue(record_no_bin_size, binary_value) assertBinaryValue(record, binary_value) assertBinaryValue(record_bin_size, binary_size) # created, flushed, and first read with bin_size=True record_bin_size = self.env['test_new_api.model_binary'].with_context(bin_size=True).create({'binary': binary_value}) record_bin_size.flush() record_bin_size.invalidate_cache() record = self.env['test_new_api.model_binary'].browse(record.id) record_no_bin_size = record.with_context(bin_size=False) assertBinaryValue(record_bin_size, binary_size) assertBinaryValue(record_no_bin_size, binary_value) assertBinaryValue(record, binary_value) # created without context and flushed with bin_size record = self.env['test_new_api.model_binary'].create({'binary': binary_value}) record_no_bin_size = record.with_context(bin_size=False) record_bin_size = record.with_context(bin_size=True) record_bin_size.flush() record_bin_size.invalidate_cache() assertBinaryValue(record, binary_value) assertBinaryValue(record_no_bin_size, binary_value) assertBinaryValue(record_bin_size, binary_size) # check computed binary field with arbitrary Python value record = self.env['test_new_api.model_binary'].create({}) record.flush() record.invalidate_cache() record_no_bin_size = record.with_context(bin_size=False) record_bin_size = record.with_context(bin_size=True) expected_value = [(record.id, False)] self.assertEqual(record.binary_computed, expected_value) self.assertEqual(record_no_bin_size.binary_computed, expected_value) self.assertEqual(record_bin_size.binary_computed, expected_value) def test_96_order_m2o(self): belgium, congo = self.env['test_new_api.country'].create([ {'name': "Duchy of Brabant"}, {'name': "Congo"}, ]) cities = self.env['test_new_api.city'].create([ {'name': "Brussels", 'country_id': belgium.id}, {'name': "Kinshasa", 'country_id': congo.id}, ]) # cities are sorted by country_id, name self.assertEqual(cities.sorted().mapped('name'), ["Kinshasa", "Brussels"]) # change order of countries, and check sorted() belgium.name = "Belgium" self.assertEqual(cities.sorted().mapped('name'), ["Brussels", "Kinshasa"]) def test_97_ir_rule_m2m_field(self): """Ensures m2m fields can't be read if the left records can't be read. Also makes sure reading m2m doesn't take more queries than necessary.""" tag = self.env['test_new_api.multi.tag'].create({}) record = self.env['test_new_api.multi.line'].create({ 'name': 'image', 'tags': [Command.link(tag.id)], }) # only one query as admin: reading pivot table with self.assertQueryCount(1): record.read(['tags']) user = self.env['res.users'].create({'name': "user", 'login': "user"}) record_user = record.with_user(user) # prep the following query count by caching access check related data record_user.read(['tags']) # only one query as user: reading pivot table with self.assertQueryCount(1): record_user.read(['tags']) # create a passing ir.rule self.env['ir.rule'].create({ 'model_id': self.env['ir.model']._get(record._name).id, 'domain_force': "[('id', '=', %d)]" % record.id, }) # prep the following query count by caching access check related data record_user.read(['tags']) # still only 1 query: reading pivot table # access rules are checked in python in this case with self.assertQueryCount(1): record_user.read(['tags']) # create a blocking ir.rule self.env['ir.rule'].create({ 'model_id': self.env['ir.model']._get(record._name).id, 'domain_force': "[('id', '!=', %d)]" % record.id, }) # ensure ir.rule is applied even when reading m2m with self.assertRaises(AccessError): record_user.read(['tags']) def test_98_unlink_recompute(self): move = self.env['test_new_api.move'].create({ 'line_ids': [(0, 0, {'quantity': 42})], }) line = move.line_ids self.assertEqual(move.quantity, 42) # create an ir.rule for lines that uses move.quantity self.env['ir.rule'].create({ 'model_id': self.env['ir.model']._get(line._name).id, 'domain_force': "[('move_id.quantity', '>=', 0)]", }) # unlink the line, and check the recomputation of move.quantity user = self.env.ref('base.user_demo') line.with_user(user).unlink() self.assertEqual(move.quantity, 0) class TestX2many(common.TransactionCase): def test_definition_many2many(self): """ Test the definition of inherited many2many fields. """ field = self.env['test_new_api.multi.line']._fields['tags'] self.assertEqual(field.relation, 'test_new_api_multi_line_test_new_api_multi_tag_rel') self.assertEqual(field.column1, 'test_new_api_multi_line_id') self.assertEqual(field.column2, 'test_new_api_multi_tag_id') field = self.env['test_new_api.multi.line2']._fields['tags'] self.assertEqual(field.relation, 'test_new_api_multi_line2_test_new_api_multi_tag_rel') self.assertEqual(field.column1, 'test_new_api_multi_line2_id') self.assertEqual(field.column2, 'test_new_api_multi_tag_id') def test_10_ondelete_many2many(self): """Test A can't be deleted when used on the relation.""" record_a = self.env['test_new_api.model_a'].create({'name': 'a'}) record_b = self.env['test_new_api.model_b'].create({'name': 'b'}) record_a.write({ 'a_restricted_b_ids': [Command.set(record_b.ids)], }) with self.assertRaises(psycopg2.IntegrityError): with mute_logger('odoo.sql_db'), self.cr.savepoint(): record_a.unlink() # Test B is still cascade. record_b.unlink() self.assertFalse(record_b.exists()) def test_11_ondelete_many2many(self): """Test B can't be deleted when used on the relation.""" record_a = self.env['test_new_api.model_a'].create({'name': 'a'}) record_b = self.env['test_new_api.model_b'].create({'name': 'b'}) record_a.write({ 'b_restricted_b_ids': [Command.set(record_b.ids)], }) with self.assertRaises(psycopg2.IntegrityError): with mute_logger('odoo.sql_db'), self.cr.savepoint(): record_b.unlink() # Test A is still cascade. record_a.unlink() self.assertFalse(record_a.exists()) def test_12_active_test_one2many(self): Model = self.env['test_new_api.model_active_field'] parent = Model.create({}) self.assertFalse(parent.children_ids) # create with implicit active_test=True in context child1, child2 = Model.create([ {'parent_id': parent.id, 'active': True}, {'parent_id': parent.id, 'active': False}, ]) act_children = child1 all_children = child1 + child2 self.assertEqual(parent.children_ids, act_children) self.assertEqual(parent.with_context(active_test=True).children_ids, act_children) self.assertEqual(parent.with_context(active_test=False).children_ids, all_children) # create with active_test=False in context child3, child4 = Model.with_context(active_test=False).create([ {'parent_id': parent.id, 'active': True}, {'parent_id': parent.id, 'active': False}, ]) act_children = child1 + child3 all_children = child1 + child2 + child3 + child4 self.assertEqual(parent.children_ids, act_children) self.assertEqual(parent.with_context(active_test=True).children_ids, act_children) self.assertEqual(parent.with_context(active_test=False).children_ids, all_children) # replace active children parent.write({'children_ids': [Command.set([child1.id])]}) act_children = child1 all_children = child1 + child2 + child4 self.assertEqual(parent.children_ids, act_children) self.assertEqual(parent.with_context(active_test=True).children_ids, act_children) self.assertEqual(parent.with_context(active_test=False).children_ids, all_children) # replace all children parent.with_context(active_test=False).write({'children_ids': [Command.set([child1.id])]}) act_children = child1 all_children = child1 self.assertEqual(parent.children_ids, act_children) self.assertEqual(parent.with_context(active_test=True).children_ids, act_children) self.assertEqual(parent.with_context(active_test=False).children_ids, all_children) # check recomputation of inactive records parent.write({'children_ids': [Command.set(child4.ids)]}) self.assertTrue(child4.parent_active) parent.active = False self.assertFalse(child4.parent_active) def test_12_active_test_one2many_with_context(self): Model = self.env['test_new_api.model_active_field'] parent = Model.create({}) all_children = Model.create([ {'parent_id': parent.id, 'active': True}, {'parent_id': parent.id, 'active': False}, ]) act_children = all_children[0] self.assertEqual(parent.children_ids, act_children) self.assertEqual(parent.with_context(active_test=True).children_ids, act_children) self.assertEqual(parent.with_context(active_test=False).children_ids, all_children) self.assertEqual(parent.all_children_ids, all_children) self.assertEqual(parent.with_context(active_test=True).all_children_ids, all_children) self.assertEqual(parent.with_context(active_test=False).all_children_ids, all_children) self.assertEqual(parent.active_children_ids, act_children) self.assertEqual(parent.with_context(active_test=True).active_children_ids, act_children) self.assertEqual(parent.with_context(active_test=False).active_children_ids, act_children) # check read() self.env.cache.invalidate() self.assertEqual(parent.children_ids, act_children) self.assertEqual(parent.all_children_ids, all_children) self.assertEqual(parent.active_children_ids, act_children) self.env.cache.invalidate() self.assertEqual(parent.with_context(active_test=False).children_ids, all_children) self.assertEqual(parent.with_context(active_test=False).all_children_ids, all_children) self.assertEqual(parent.with_context(active_test=False).active_children_ids, act_children) def test_12_active_test_one2many_search(self): Model = self.env['test_new_api.model_active_field'] parent = Model.create({}) all_children = Model.create([ {'name': 'A', 'parent_id': parent.id, 'active': True}, {'name': 'B', 'parent_id': parent.id, 'active': False}, ]) # a one2many field without context does not match its inactive children self.assertIn(parent, Model.search([('children_ids.name', '=', 'A')])) self.assertNotIn(parent, Model.search([('children_ids.name', '=', 'B')])) # a one2many field with active_test=False matches its inactive children self.assertIn(parent, Model.search([('all_children_ids.name', '=', 'A')])) self.assertIn(parent, Model.search([('all_children_ids.name', '=', 'B')])) def test_search_many2many(self): """ Tests search on many2many fields. """ tags = self.env['test_new_api.multi.tag'] tagA = tags.create({}) tagB = tags.create({}) tagC = tags.create({}) recs = self.env['test_new_api.multi.line'] recW = recs.create({}) recX = recs.create({'tags': [Command.link(tagA.id)]}) recY = recs.create({'tags': [Command.link(tagB.id)]}) recZ = recs.create({'tags': [Command.link(tagA.id), Command.link(tagB.id)]}) recs = recW + recX + recY + recZ # test 'in' result = recs.search([('tags', 'in', (tagA + tagB).ids)]) self.assertEqual(result, recX + recY + recZ) result = recs.search([('tags', 'in', tagA.ids)]) self.assertEqual(result, recX + recZ) result = recs.search([('tags', 'in', tagB.ids)]) self.assertEqual(result, recY + recZ) result = recs.search([('tags', 'in', tagC.ids)]) self.assertEqual(result, recs.browse()) result = recs.search([('tags', 'in', [])]) self.assertEqual(result, recs.browse()) # test 'not in' result = recs.search([('id', 'in', recs.ids), ('tags', 'not in', (tagA + tagB).ids)]) self.assertEqual(result, recs - recX - recY - recZ) result = recs.search([('id', 'in', recs.ids), ('tags', 'not in', tagA.ids)]) self.assertEqual(result, recs - recX - recZ) result = recs.search([('id', 'in', recs.ids), ('tags', 'not in', tagB.ids)]) self.assertEqual(result, recs - recY - recZ) result = recs.search([('id', 'in', recs.ids), ('tags', 'not in', tagC.ids)]) self.assertEqual(result, recs) result = recs.search([('id', 'in', recs.ids), ('tags', 'not in', [])]) self.assertEqual(result, recs) # special case: compare with False result = recs.search([('id', 'in', recs.ids), ('tags', '=', False)]) self.assertEqual(result, recW) result = recs.search([('id', 'in', recs.ids), ('tags', '!=', False)]) self.assertEqual(result, recs - recW) def test_search_one2many(self): """ Tests search on one2many fields. """ recs = self.env['test_new_api.multi'] recX = recs.create({'lines': [Command.create({}), Command.create({})]}) recY = recs.create({'lines': [Command.create({})]}) recZ = recs.create({}) recs = recX + recY + recZ line1, line2, line3 = recs.lines line4 = recs.create({'lines': [Command.create({})]}).lines line0 = line4.create({}) # test 'in' result = recs.search([('id', 'in', recs.ids), ('lines', 'in', (line1 + line2 + line3 + line4).ids)]) self.assertEqual(result, recX + recY) result = recs.search([('id', 'in', recs.ids), ('lines', 'in', (line1 + line3 + line4).ids)]) self.assertEqual(result, recX + recY) result = recs.search([('id', 'in', recs.ids), ('lines', 'in', (line1 + line4).ids)]) self.assertEqual(result, recX) result = recs.search([('id', 'in', recs.ids), ('lines', 'in', line4.ids)]) self.assertEqual(result, recs.browse()) result = recs.search([('id', 'in', recs.ids), ('lines', 'in', [])]) self.assertEqual(result, recs.browse()) # test 'not in' result = recs.search([('id', 'in', recs.ids), ('lines', 'not in', (line1 + line2 + line3).ids)]) self.assertEqual(result, recs - recX - recY) result = recs.search([('id', 'in', recs.ids), ('lines', 'not in', (line1 + line3).ids)]) self.assertEqual(result, recs - recX - recY) result = recs.search([('id', 'in', recs.ids), ('lines', 'not in', line1.ids)]) self.assertEqual(result, recs - recX) result = recs.search([('id', 'in', recs.ids), ('lines', 'not in', (line1 + line4).ids)]) self.assertEqual(result, recs - recX) result = recs.search([('id', 'in', recs.ids), ('lines', 'not in', line4.ids)]) self.assertEqual(result, recs) result = recs.search([('id', 'in', recs.ids), ('lines', 'not in', [])]) self.assertEqual(result, recs) # test 'not in' where the lines contain NULL values result = recs.search([('id', 'in', recs.ids), ('lines', 'not in', (line1 + line0).ids)]) self.assertEqual(result, recs - recX) result = recs.search([('id', 'in', recs.ids), ('lines', 'not in', line0.ids)]) self.assertEqual(result, recs) # special case: compare with False result = recs.search([('id', 'in', recs.ids), ('lines', '=', False)]) self.assertEqual(result, recZ) result = recs.search([('id', 'in', recs.ids), ('lines', '!=', False)]) self.assertEqual(result, recs - recZ) def test_create_batch_m2m(self): lines = self.env['test_new_api.multi.line'].create([{ 'tags': [Command.create({'name': str(j)}) for j in range(3)], } for i in range(3)]) self.assertEqual(len(lines), 3) for line in lines: self.assertEqual(len(line.tags), 3) def test_custom_m2m(self): model_id = self.env['ir.model']._get_id('res.partner') field = self.env['ir.model.fields'].create({ 'name': 'x_foo', 'field_description': 'Foo', 'model_id': model_id, 'ttype': 'many2many', 'relation': 'res.country', 'store': False, }) self.assertTrue(field.unlink()) def test_custom_m2m_related(self): # this checks the ondelete of a related many2many field model_id = self.env['ir.model']._get_id('res.partner') field = self.env['ir.model.fields'].create({ 'name': 'x_foo', 'field_description': 'Foo', 'model_id': model_id, 'ttype': 'many2many', 'relation': 'res.partner.category', 'related': 'category_id', 'readonly': True, 'store': True, }) self.assertTrue(field.unlink()) class TestHtmlField(common.TransactionCase): def setUp(self): super(TestHtmlField, self).setUp() self.model = self.env['test_new_api.mixed'] def test_00_sanitize(self): self.assertEqual(self.model._fields['comment1'].sanitize, False) self.assertEqual(self.model._fields['comment2'].sanitize_attributes, True) self.assertEqual(self.model._fields['comment2'].strip_classes, False) self.assertEqual(self.model._fields['comment3'].sanitize_attributes, True) self.assertEqual(self.model._fields['comment3'].strip_classes, True) some_ugly_html = """<p>Oops this should maybe be sanitized % if object.some_field and not object.oriented: <table> % if object.other_field: <tr style="margin: 0px; border: 10px solid black;"> ${object.mako_thing} <td> </tr> <tr class="custom_class"> This is some html. </tr> % endif <tr> %if object.dummy_field: <p>Youpie</p> %endif""" record = self.model.create({ 'comment1': some_ugly_html, 'comment2': some_ugly_html, 'comment3': some_ugly_html, 'comment4': some_ugly_html, }) self.assertEqual(record.comment1, some_ugly_html, 'Error in HTML field: content was sanitized but field has sanitize=False') self.assertIn('<tr class="', record.comment2) # sanitize should have closed tags left open in the original html self.assertIn('</table>', record.comment3, 'Error in HTML field: content does not seem to have been sanitized despise sanitize=True') self.assertIn('</td>', record.comment3, 'Error in HTML field: content does not seem to have been sanitized despise sanitize=True') self.assertIn('<tr style="', record.comment3, 'Style attr should not have been stripped') # sanitize does not keep classes if asked to self.assertNotIn('<tr class="', record.comment3) self.assertNotIn('<tr style="', record.comment4, 'Style attr should have been stripped') class TestMagicFields(common.TransactionCase): def test_write_date(self): record = self.env['test_new_api.discussion'].create({'name': 'Booba'}) self.assertEqual(record.create_uid, self.env.user) self.assertEqual(record.write_uid, self.env.user) def test_mro_mixin(self): # Mixin # | # | # | # ExtendedDisplay 'test_new_api.mixin' Display 'base' # | | | | # +----------------------+-+--------------+---------+ # | # 'test_new_api.display' # # The field 'display_name' is defined as store=True on the class Display # above. The field 'display_name' on the model 'test_new_api.mixin' is # expected to be automatic and non-stored. But the field 'display_name' # on the model 'test_new_api.display' should not be automatic: it must # correspond to the definition given in class Display, even if the MRO # of the model shows the automatic field on the mixin model before the # actual definition. registry = self.env.registry models = registry.models # check setup of models in alphanumeric order self.patch(registry, 'models', OrderedDict(sorted(models.items()))) registry.setup_models(self.cr) field = registry['test_new_api.display'].display_name self.assertFalse(field.automatic) self.assertTrue(field.store) # check setup of models in reverse alphanumeric order self.patch(registry, 'models', OrderedDict(sorted(models.items(), reverse=True))) registry.setup_models(self.cr) field = registry['test_new_api.display'].display_name self.assertFalse(field.automatic) self.assertTrue(field.store) class TestParentStore(common.TransactionCase): def setUp(self): super(TestParentStore, self).setUp() # make a tree of categories: # 0 # /|\ # 1 2 3 # /|\ # 4 5 6 # /|\ # 7 8 9 Cat = self.env['test_new_api.category'] cat0 = Cat.create({'name': '0'}) cat1 = Cat.create({'name': '1', 'parent': cat0.id}) cat2 = Cat.create({'name': '2', 'parent': cat0.id}) cat3 = Cat.create({'name': '3', 'parent': cat0.id}) cat4 = Cat.create({'name': '4', 'parent': cat3.id}) cat5 = Cat.create({'name': '5', 'parent': cat3.id}) cat6 = Cat.create({'name': '6', 'parent': cat3.id}) cat7 = Cat.create({'name': '7', 'parent': cat6.id}) cat8 = Cat.create({'name': '8', 'parent': cat6.id}) cat9 = Cat.create({'name': '9', 'parent': cat6.id}) self._cats = Cat.concat(cat0, cat1, cat2, cat3, cat4, cat5, cat6, cat7, cat8, cat9) def cats(self, *indexes): """ Return the given categories. """ ids = self._cats.ids return self._cats.browse([ids[index] for index in indexes]) def assertChildOf(self, category, children): self.assertEqual(category.search([('id', 'child_of', category.ids)]), children) def assertParentOf(self, category, parents): self.assertEqual(category.search([('id', 'parent_of', category.ids)]), parents) def test_base(self): """ Check the initial tree structure. """ self.assertChildOf(self.cats(0), self.cats(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) self.assertChildOf(self.cats(1), self.cats(1)) self.assertChildOf(self.cats(2), self.cats(2)) self.assertChildOf(self.cats(3), self.cats(3, 4, 5, 6, 7, 8, 9)) self.assertChildOf(self.cats(4), self.cats(4)) self.assertChildOf(self.cats(5), self.cats(5)) self.assertChildOf(self.cats(6), self.cats(6, 7, 8, 9)) self.assertChildOf(self.cats(7), self.cats(7)) self.assertChildOf(self.cats(8), self.cats(8)) self.assertChildOf(self.cats(9), self.cats(9)) self.assertParentOf(self.cats(0), self.cats(0)) self.assertParentOf(self.cats(1), self.cats(0, 1)) self.assertParentOf(self.cats(2), self.cats(0, 2)) self.assertParentOf(self.cats(3), self.cats(0, 3)) self.assertParentOf(self.cats(4), self.cats(0, 3, 4)) self.assertParentOf(self.cats(5), self.cats(0, 3, 5)) self.assertParentOf(self.cats(6), self.cats(0, 3, 6)) self.assertParentOf(self.cats(7), self.cats(0, 3, 6, 7)) self.assertParentOf(self.cats(8), self.cats(0, 3, 6, 8)) self.assertParentOf(self.cats(9), self.cats(0, 3, 6, 9)) def test_base_compute(self): """ Check the tree structure after computation from scratch. """ self.cats()._parent_store_compute() self.assertChildOf(self.cats(0), self.cats(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) self.assertChildOf(self.cats(1), self.cats(1)) self.assertChildOf(self.cats(2), self.cats(2)) self.assertChildOf(self.cats(3), self.cats(3, 4, 5, 6, 7, 8, 9)) self.assertChildOf(self.cats(4), self.cats(4)) self.assertChildOf(self.cats(5), self.cats(5)) self.assertChildOf(self.cats(6), self.cats(6, 7, 8, 9)) self.assertChildOf(self.cats(7), self.cats(7)) self.assertChildOf(self.cats(8), self.cats(8)) self.assertChildOf(self.cats(9), self.cats(9)) self.assertParentOf(self.cats(0), self.cats(0)) self.assertParentOf(self.cats(1), self.cats(0, 1)) self.assertParentOf(self.cats(2), self.cats(0, 2)) self.assertParentOf(self.cats(3), self.cats(0, 3)) self.assertParentOf(self.cats(4), self.cats(0, 3, 4)) self.assertParentOf(self.cats(5), self.cats(0, 3, 5)) self.assertParentOf(self.cats(6), self.cats(0, 3, 6)) self.assertParentOf(self.cats(7), self.cats(0, 3, 6, 7)) self.assertParentOf(self.cats(8), self.cats(0, 3, 6, 8)) self.assertParentOf(self.cats(9), self.cats(0, 3, 6, 9)) def test_delete(self): """ Delete a node. """ self.cats(6).unlink() self.assertChildOf(self.cats(0), self.cats(0, 1, 2, 3, 4, 5)) self.assertChildOf(self.cats(3), self.cats(3, 4, 5)) self.assertChildOf(self.cats(5), self.cats(5)) self.assertParentOf(self.cats(0), self.cats(0)) self.assertParentOf(self.cats(3), self.cats(0, 3)) self.assertParentOf(self.cats(5), self.cats(0, 3, 5)) def test_move_1_0(self): """ Move a node to a root position. """ self.cats(6).write({'parent': False}) self.assertChildOf(self.cats(0), self.cats(0, 1, 2, 3, 4, 5)) self.assertChildOf(self.cats(3), self.cats(3, 4, 5)) self.assertChildOf(self.cats(6), self.cats(6, 7, 8, 9)) self.assertParentOf(self.cats(9), self.cats(6, 9)) def test_move_1_1(self): """ Move a node into an empty subtree. """ self.cats(6).write({'parent': self.cats(1).id}) self.assertChildOf(self.cats(0), self.cats(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) self.assertChildOf(self.cats(1), self.cats(1, 6, 7, 8, 9)) self.assertChildOf(self.cats(3), self.cats(3, 4, 5)) self.assertChildOf(self.cats(6), self.cats(6, 7, 8, 9)) self.assertParentOf(self.cats(9), self.cats(0, 1, 6, 9)) def test_move_1_N(self): """ Move a node into a non-empty subtree. """ self.cats(6).write({'parent': self.cats(0).id}) self.assertChildOf(self.cats(0), self.cats(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) self.assertChildOf(self.cats(3), self.cats(3, 4, 5)) self.assertChildOf(self.cats(6), self.cats(6, 7, 8, 9)) self.assertParentOf(self.cats(9), self.cats(0, 6, 9)) def test_move_N_0(self): """ Move multiple nodes to root position. """ self.cats(5, 6).write({'parent': False}) self.assertChildOf(self.cats(0), self.cats(0, 1, 2, 3, 4)) self.assertChildOf(self.cats(3), self.cats(3, 4)) self.assertChildOf(self.cats(5), self.cats(5)) self.assertChildOf(self.cats(6), self.cats(6, 7, 8, 9)) self.assertParentOf(self.cats(5), self.cats(5)) self.assertParentOf(self.cats(9), self.cats(6, 9)) def test_move_N_1(self): """ Move multiple nodes to an empty subtree. """ self.cats(5, 6).write({'parent': self.cats(1).id}) self.assertChildOf(self.cats(0), self.cats(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) self.assertChildOf(self.cats(1), self.cats(1, 5, 6, 7, 8, 9)) self.assertChildOf(self.cats(3), self.cats(3, 4)) self.assertChildOf(self.cats(5), self.cats(5)) self.assertChildOf(self.cats(6), self.cats(6, 7, 8, 9)) self.assertParentOf(self.cats(5), self.cats(0, 1, 5)) self.assertParentOf(self.cats(9), self.cats(0, 1, 6, 9)) def test_move_N_N(self): """ Move multiple nodes to a non- empty subtree. """ self.cats(5, 6).write({'parent': self.cats(0).id}) self.assertChildOf(self.cats(0), self.cats(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) self.assertChildOf(self.cats(3), self.cats(3, 4)) self.assertChildOf(self.cats(5), self.cats(5)) self.assertChildOf(self.cats(6), self.cats(6, 7, 8, 9)) self.assertParentOf(self.cats(5), self.cats(0, 5)) self.assertParentOf(self.cats(9), self.cats(0, 6, 9)) def test_move_1_cycle(self): """ Move a node to create a cycle. """ with self.assertRaises(UserError): self.cats(3).write({'parent': self.cats(9).id}) def test_move_N_cycle(self): """ Move multiple nodes to create a cycle. """ with self.assertRaises(UserError): self.cats(1, 3).write({'parent': self.cats(9).id}) def test_compute_depend_parent_path(self): self.assertEqual(self.cats(7).depth, 3) self.assertEqual(self.cats(8).depth, 3) self.assertEqual(self.cats(9).depth, 3) # change parent of node to have 2 parents self.cats(7).parent = self.cats(2) self.assertEqual(self.cats(7).depth, 2) # change parent of node to root self.cats(7).parent = False self.assertEqual(self.cats(7).depth, 0) # change grand-parent of nodes self.cats(6).parent = self.cats(0) self.assertEqual(self.cats(8).depth, 2) self.assertEqual(self.cats(9).depth, 2) class TestRequiredMany2one(common.TransactionCase): def test_explicit_ondelete(self): field = self.env['test_new_api.req_m2o']._fields['foo'] self.assertEqual(field.ondelete, 'cascade') def test_implicit_ondelete(self): field = self.env['test_new_api.req_m2o']._fields['bar'] self.assertEqual(field.ondelete, 'restrict') def test_explicit_set_null(self): Model = self.env['test_new_api.req_m2o'] field = Model._fields['foo'] # clean up registry after this test self.addCleanup(self.registry.reset_changes) self.patch(field, 'ondelete', 'set null') with self.assertRaises(ValueError): field.setup_nonrelated(Model) class TestRequiredMany2oneTransient(common.TransactionCase): def test_explicit_ondelete(self): field = self.env['test_new_api.req_m2o_transient']._fields['foo'] self.assertEqual(field.ondelete, 'restrict') def test_implicit_ondelete(self): field = self.env['test_new_api.req_m2o_transient']._fields['bar'] self.assertEqual(field.ondelete, 'cascade') def test_explicit_set_null(self): Model = self.env['test_new_api.req_m2o_transient'] field = Model._fields['foo'] # clean up registry after this test self.addCleanup(self.registry.reset_changes) self.patch(field, 'ondelete', 'set null') with self.assertRaises(ValueError): field.setup_nonrelated(Model) @common.tagged('m2oref') class TestMany2oneReference(common.TransactionCase): def test_delete_m2o_reference_records(self): m = self.env['test_new_api.model_many2one_reference'] self.env.cr.execute("SELECT max(id) FROM test_new_api_model_many2one_reference") ids = self.env.cr.fetchone() # fake record to emulate the unlink of a non-existant record foo = m.browse(1 if not ids[0] else (ids[0] + 1)) self.assertTrue(foo.unlink()) @common.tagged('selection_abstract') class TestSelectionDeleteUpdate(common.TransactionCase): MODEL_ABSTRACT = 'test_new_api.state_mixin' def setUp(self): super().setUp() # enable unlinking ir.model.fields.selection self.patch(self.registry, 'ready', False) def test_unlink_asbtract(self): self.env['ir.model.fields.selection'].search([ ('field_id.model', '=', self.MODEL_ABSTRACT), ('field_id.name', '=', 'state'), ('value', '=', 'confirmed'), ], limit=1).unlink() @common.tagged('selection_ondelete_base') class TestSelectionOndelete(common.TransactionCase): MODEL_BASE = 'test_new_api.model_selection_base' MODEL_REQUIRED = 'test_new_api.model_selection_required' MODEL_NONSTORED = 'test_new_api.model_selection_non_stored' MODEL_WRITE_OVERRIDE = 'test_new_api.model_selection_required_for_write_override' def setUp(self): super().setUp() # enable unlinking ir.model.fields.selection self.patch(self.registry, 'ready', False) def _unlink_option(self, model, option): self.env['ir.model.fields.selection'].search([ ('field_id.model', '=', model), ('field_id.name', '=', 'my_selection'), ('value', '=', option), ], limit=1).unlink() def test_ondelete_default(self): # create some records, one of which having the extended selection option rec1 = self.env[self.MODEL_REQUIRED].create({'my_selection': 'foo'}) rec2 = self.env[self.MODEL_REQUIRED].create({'my_selection': 'bar'}) rec3 = self.env[self.MODEL_REQUIRED].create({'my_selection': 'baz'}) # test that all values are correct before the removal of the value self.assertEqual(rec1.my_selection, 'foo') self.assertEqual(rec2.my_selection, 'bar') self.assertEqual(rec3.my_selection, 'baz') # unlink the extended option (simulates a module uninstall) self._unlink_option(self.MODEL_REQUIRED, 'baz') # verify that the ondelete policy has succesfully been applied self.assertEqual(rec1.my_selection, 'foo') self.assertEqual(rec2.my_selection, 'bar') self.assertEqual(rec3.my_selection, 'foo') # reset to default def test_ondelete_base_null_explicit(self): rec1 = self.env[self.MODEL_BASE].create({'my_selection': 'foo'}) rec2 = self.env[self.MODEL_BASE].create({'my_selection': 'bar'}) rec3 = self.env[self.MODEL_BASE].create({'my_selection': 'quux'}) self.assertEqual(rec1.my_selection, 'foo') self.assertEqual(rec2.my_selection, 'bar') self.assertEqual(rec3.my_selection, 'quux') self._unlink_option(self.MODEL_BASE, 'quux') self.assertEqual(rec1.my_selection, 'foo') self.assertEqual(rec2.my_selection, 'bar') self.assertFalse(rec3.my_selection) def test_ondelete_base_null_implicit(self): rec1 = self.env[self.MODEL_BASE].create({'my_selection': 'foo'}) rec2 = self.env[self.MODEL_BASE].create({'my_selection': 'bar'}) rec3 = self.env[self.MODEL_BASE].create({'my_selection': 'ham'}) self.assertEqual(rec1.my_selection, 'foo') self.assertEqual(rec2.my_selection, 'bar') self.assertEqual(rec3.my_selection, 'ham') self._unlink_option(self.MODEL_BASE, 'ham') self.assertEqual(rec1.my_selection, 'foo') self.assertEqual(rec2.my_selection, 'bar') self.assertFalse(rec3.my_selection) def test_ondelete_cascade(self): rec1 = self.env[self.MODEL_REQUIRED].create({'my_selection': 'foo'}) rec2 = self.env[self.MODEL_REQUIRED].create({'my_selection': 'bar'}) rec3 = self.env[self.MODEL_REQUIRED].create({'my_selection': 'eggs'}) self.assertEqual(rec1.my_selection, 'foo') self.assertEqual(rec2.my_selection, 'bar') self.assertEqual(rec3.my_selection, 'eggs') self._unlink_option(self.MODEL_REQUIRED, 'eggs') self.assertEqual(rec1.my_selection, 'foo') self.assertEqual(rec2.my_selection, 'bar') self.assertFalse(rec3.exists()) def test_ondelete_literal(self): rec1 = self.env[self.MODEL_REQUIRED].create({'my_selection': 'foo'}) rec2 = self.env[self.MODEL_REQUIRED].create({'my_selection': 'bar'}) rec3 = self.env[self.MODEL_REQUIRED].create({'my_selection': 'bacon'}) self.assertEqual(rec1.my_selection, 'foo') self.assertEqual(rec2.my_selection, 'bar') self.assertEqual(rec3.my_selection, 'bacon') self._unlink_option(self.MODEL_REQUIRED, 'bacon') self.assertEqual(rec1.my_selection, 'foo') self.assertEqual(rec2.my_selection, 'bar') self.assertEqual(rec3.my_selection, 'bar') def test_ondelete_multiple_explicit(self): rec1 = self.env[self.MODEL_REQUIRED].create({'my_selection': 'foo'}) rec2 = self.env[self.MODEL_REQUIRED].create({'my_selection': 'eevee'}) rec3 = self.env[self.MODEL_REQUIRED].create({'my_selection': 'pikachu'}) self.assertEqual(rec1.my_selection, 'foo') self.assertEqual(rec2.my_selection, 'eevee') self.assertEqual(rec3.my_selection, 'pikachu') self._unlink_option(self.MODEL_REQUIRED, 'eevee') self._unlink_option(self.MODEL_REQUIRED, 'pikachu') self.assertEqual(rec1.my_selection, 'foo') self.assertEqual(rec2.my_selection, 'bar') self.assertEqual(rec3.my_selection, 'foo') def test_ondelete_callback(self): rec = self.env[self.MODEL_REQUIRED].create({'my_selection': 'knickers'}) self.assertEqual(rec.my_selection, 'knickers') self._unlink_option(self.MODEL_REQUIRED, 'knickers') self.assertEqual(rec.my_selection, 'foo') self.assertFalse(rec.active) def test_non_stored_selection(self): rec = self.env[self.MODEL_NONSTORED].create({}) rec.my_selection = 'foo' self.assertEqual(rec.my_selection, 'foo') self._unlink_option(self.MODEL_NONSTORED, 'foo') self.assertFalse(rec.my_selection) def test_required_base_selection_field(self): # test that no ondelete action is executed on a required selection field that is not # extended, only required fields that extend it with selection_add should # have ondelete actions defined rec = self.env[self.MODEL_REQUIRED].create({'my_selection': 'foo'}) self.assertEqual(rec.my_selection, 'foo') self._unlink_option(self.MODEL_REQUIRED, 'foo') self.assertEqual(rec.my_selection, 'foo') @mute_logger('odoo.addons.base.models.ir_model') def test_write_override_selection(self): # test that on override to write that raises an error does not prevent the ondelete # policy from executing and cleaning up what needs to be cleaned up rec = self.env[self.MODEL_WRITE_OVERRIDE].create({'my_selection': 'divinity'}) self.assertEqual(rec.my_selection, 'divinity') self._unlink_option(self.MODEL_WRITE_OVERRIDE, 'divinity') self.assertEqual(rec.my_selection, 'foo') @common.tagged('selection_ondelete_advanced') class TestSelectionOndeleteAdvanced(common.TransactionCase): MODEL_BASE = 'test_new_api.model_selection_base' MODEL_REQUIRED = 'test_new_api.model_selection_required' def setUp(self): super().setUp() # necessary cleanup for resetting changes in the registry for model_name in (self.MODEL_BASE, self.MODEL_REQUIRED): Model = self.registry[model_name] self.addCleanup(setattr, Model, '_BaseModel__base_classes', Model._BaseModel__base_classes) def test_ondelete_unexisting_policy(self): class Foo(models.Model): _module = None _inherit = self.MODEL_REQUIRED my_selection = fields.Selection(selection_add=[ ('random', "Random stuff"), ], ondelete={'random': 'poop'}) Foo._build_model(self.registry, self.env.cr) with self.assertRaises(ValueError): self.registry.setup_models(self.env.cr) def test_ondelete_default_no_default(self): class Foo(models.Model): _module = None _inherit = self.MODEL_BASE my_selection = fields.Selection(selection_add=[ ('corona', "Corona beers suck"), ], ondelete={'corona': 'set default'}) Foo._build_model(self.registry, self.env.cr) with self.assertRaises(AssertionError): self.registry.setup_models(self.env.cr) def test_ondelete_value_no_valid(self): class Foo(models.Model): _module = None _inherit = self.MODEL_BASE my_selection = fields.Selection(selection_add=[ ('westvleteren', "Westvleteren beers is overrated"), ], ondelete={'westvleteren': 'set foooo'}) Foo._build_model(self.registry, self.env.cr) with self.assertRaises(AssertionError): self.registry.setup_models(self.env.cr) def test_ondelete_required_null_explicit(self): class Foo(models.Model): _module = None _inherit = self.MODEL_REQUIRED my_selection = fields.Selection(selection_add=[ ('brap', "Brap"), ], ondelete={'brap': 'set null'}) Foo._build_model(self.registry, self.env.cr) with self.assertRaises(ValueError): self.registry.setup_models(self.env.cr) def test_ondelete_required_null_implicit(self): class Foo(models.Model): _module = None _inherit = self.MODEL_REQUIRED my_selection = fields.Selection(selection_add=[ ('boing', "Boyoyoyoing"), ]) Foo._build_model(self.registry, self.env.cr) with self.assertRaises(ValueError): self.registry.setup_models(self.env.cr) class TestFieldParametersValidation(common.TransactionCase): def test_invalid_parameter(self): class Foo(models.Model): _module = None _name = _description = 'test_new_api.field_parameter_validation' name = fields.Char(invalid_parameter=42) Foo._build_model(self.registry, self.env.cr) self.addCleanup(self.registry.__delitem__, Foo._name) with self.assertLogs('odoo.fields', level='WARNING') as cm: self.registry.setup_models(self.env.cr) self.assertTrue(cm.output[0].startswith( "WARNING:odoo.fields:Field test_new_api.field_parameter_validation.name: " "unknown parameter 'invalid_parameter'" )) def insert(model, *fnames): """ Return the expected query string to INSERT the given columns. """ columns = sorted(fnames + ('create_uid', 'create_date', 'write_uid', 'write_date')) return 'INSERT INTO "{}" ("id", {}) VALUES (nextval(%s), {}) RETURNING id'.format( model._table, ", ".join('"{}"'.format(column) for column in columns), ", ".join('%s' for column in columns), ) def update(model, *fnames): """ Return the expected query string to UPDATE the given columns. """ columns = sorted(fnames + ('write_uid', 'write_date')) return 'UPDATE "{}" SET {} WHERE id IN %s'.format( model._table, ", ".join('"{}" = %s'.format(column) for column in columns), ) class TestComputeQueries(common.TransactionCase): """ Test the queries made by create() with computed fields. """ def test_compute_readonly(self): model = self.env['test_new_api.compute.readonly'] model.create({}) # no value, no default with self.assertQueries([insert(model, 'foo'), update(model, 'bar')]): record = model.create({'foo': 'Foo'}) self.assertEqual(record.bar, 'Foo') # some value, no default with self.assertQueries([insert(model, 'foo', 'bar'), update(model, 'bar')]): record = model.create({'foo': 'Foo', 'bar': 'Bar'}) self.assertEqual(record.bar, 'Foo') model = model.with_context(default_bar='Def') # no value, some default with self.assertQueries([insert(model, 'foo', 'bar'), update(model, 'bar')]): record = model.create({'foo': 'Foo'}) self.assertEqual(record.bar, 'Foo') # some value, some default with self.assertQueries([insert(model, 'foo', 'bar'), update(model, 'bar')]): record = model.create({'foo': 'Foo', 'bar': 'Bar'}) self.assertEqual(record.bar, 'Foo') def test_compute_readwrite(self): model = self.env['test_new_api.compute.readwrite'] model.create({}) # no value, no default with self.assertQueries([insert(model, 'foo'), update(model, 'bar')]): record = model.create({'foo': 'Foo'}) self.assertEqual(record.bar, 'Foo') # some value, no default with self.assertQueries([insert(model, 'foo', 'bar')]): record = model.create({'foo': 'Foo', 'bar': 'Bar'}) self.assertEqual(record.bar, 'Bar') model = model.with_context(default_bar='Def') # no value, some default with self.assertQueries([insert(model, 'foo', 'bar')]): record = model.create({'foo': 'Foo'}) self.assertEqual(record.bar, 'Def') # some value, some default with self.assertQueries([insert(model, 'foo', 'bar')]): record = model.create({'foo': 'Foo', 'bar': 'Bar'}) self.assertEqual(record.bar, 'Bar') def test_compute_inverse(self): model = self.env['test_new_api.compute.inverse'] model.create({}) # no value, no default with self.assertQueries([insert(model, 'foo'), update(model, 'bar')]): record = model.create({'foo': 'Foo'}) self.assertEqual(record.foo, 'Foo') self.assertEqual(record.bar, 'Foo') # some value, no default with self.assertQueries([insert(model, 'foo', 'bar'), update(model, 'foo')]): record = model.create({'foo': 'Foo', 'bar': 'Bar'}) self.assertEqual(record.foo, 'Bar') self.assertEqual(record.bar, 'Bar') model = model.with_context(default_bar='Def') # no value, some default with self.assertQueries([insert(model, 'foo', 'bar'), update(model, 'foo')]): record = model.create({'foo': 'Foo'}) self.assertEqual(record.foo, 'Def') self.assertEqual(record.bar, 'Def') # some value, some default with self.assertQueries([insert(model, 'foo', 'bar'), update(model, 'foo')]): record = model.create({'foo': 'Foo', 'bar': 'Bar'}) self.assertEqual(record.foo, 'Bar') self.assertEqual(record.bar, 'Bar') class test_shared_cache(TransactionCaseWithUserDemo): def test_shared_cache_computed_field(self): # Test case: Check that the shared cache is not used if a compute_sudo stored field # is computed IF there is an ir.rule defined on this specific model. # Real life example: # A user can only see its own timesheets on a task, but the field "Planned Hours", # which is stored-compute_sudo, should take all the timesheet lines into account # However, when adding a new line and then recomputing the value, no existing line # from another user is binded on self, then the value is erased and saved on the # database. task = self.env['test_new_api.model_shared_cache_compute_parent'].create({ 'name': 'Shared Task'}) self.env['test_new_api.model_shared_cache_compute_line'].create({ 'user_id': self.env.ref('base.user_admin').id, 'parent_id': task.id, 'amount': 1, }) self.assertEqual(task.total_amount, 1) self.env['base'].flush() task.invalidate_cache() # Start fresh, as it would be the case on 2 different sessions. task = task.with_user(self.user_demo) with common.Form(task) as task_form: # Use demo has no access to the already existing line self.assertEqual(len(task_form.line_ids), 0) # But see the real total_amount self.assertEqual(task_form.total_amount, 1) # Now let's add a new line (and retrigger the compute method) with task_form.line_ids.new() as line: line.amount = 2 # The new value for total_amount, should be 3, not 2. self.assertEqual(task_form.total_amount, 2) @common.tagged('unlink_constraints') class TestUnlinkConstraints(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() MODEL = cls.env['test_new_api.model_constrained_unlinks'] cls.deletable_bar = MODEL.create({'bar': 5}) cls.undeletable_bar = MODEL.create({'bar': 6}) cls.deletable_foo = MODEL.create({'foo': 'formaggio'}) cls.undeletable_foo = MODEL.create({'foo': 'prosciutto'}) from odoo.addons.base.models.ir_model import MODULE_UNINSTALL_FLAG uninstall = {MODULE_UNINSTALL_FLAG: True} cls.undeletable_bar_uninstall = cls.undeletable_bar.with_context(**uninstall) cls.undeletable_foo_uninstall = cls.undeletable_foo.with_context(**uninstall) def test_unlink_constraint_manual_bar(self): self.assertTrue(self.deletable_bar.unlink()) with self.assertRaises(ValueError, msg="Nooooooooo bar can't be greater than five!!"): self.undeletable_bar.unlink() def test_unlink_constraint_uninstall_bar(self): self.assertTrue(self.deletable_bar.unlink()) # should succeed since it's at_uninstall=False self.assertTrue(self.undeletable_bar_uninstall.unlink()) def test_unlink_constraint_manual_foo(self): self.assertTrue(self.deletable_foo.unlink()) with self.assertRaises(ValueError, msg="You didn't say if you wanted it crudo or cotto..."): self.undeletable_foo.unlink() def test_unlink_constraint_uninstall_foo(self): self.assertTrue(self.deletable_foo) # should fail since it's at_uninstall=True with self.assertRaises(ValueError, msg="You didn't say if you wanted it crudo or cotto..."): self.undeletable_foo_uninstall.unlink() @common.tagged('wrong_related_path') class TestWrongRelatedError(common.TransactionCase): def test_wrong_related_path(self): class Foo(models.Model): _module = None _name = _description = 'test_new_api.wrong_related_path' foo_id = fields.Many2one('test_new_api.foo') foo_non_existing = fields.Char(related='foo_id.non_existing_field') Foo._build_model(self.registry, self.env.cr) self.addCleanup(self.registry.__delitem__, Foo._name) errMsg = ( "Field non_existing_field referenced in related field definition " "test_new_api.wrong_related_path.foo_non_existing does not exist." ) with self.assertRaisesRegex(KeyError, errMsg): self.registry.setup_models(self.env.cr)
43.439386
161,247
37,013
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from unittest.mock import patch from odoo.addons.base.tests.common import SavepointCaseWithUserDemo from odoo.tests import common, Form from odoo import Command def strip_prefix(prefix, names): size = len(prefix) return [name[size:] for name in names if name.startswith(prefix)] class TestOnChange(SavepointCaseWithUserDemo): def setUp(self): super(TestOnChange, self).setUp() self.Discussion = self.env['test_new_api.discussion'] self.Message = self.env['test_new_api.message'] self.EmailMessage = self.env['test_new_api.emailmessage'] def test_default_get(self): """ checking values returned by default_get() """ fields = ['name', 'categories', 'participants', 'messages'] values = self.Discussion.default_get(fields) self.assertEqual(values, {}) def test_get_field(self): """ checking that accessing an unknown attribute does nothing special """ with self.assertRaises(AttributeError): self.Discussion.not_really_a_method() def test_onchange(self): """ test the effect of onchange() """ discussion = self.env.ref('test_new_api.discussion_0') BODY = "What a beautiful day!" USER = self.env.user field_onchange = self.Message._onchange_spec() self.assertEqual(field_onchange.get('author'), '1') self.assertEqual(field_onchange.get('body'), '1') self.assertEqual(field_onchange.get('discussion'), '1') # changing 'discussion' should recompute 'name' values = { 'discussion': discussion.id, 'name': "[%s] %s" % ('', USER.name), 'body': False, 'author': USER.id, 'size': 0, } self.env.cache.invalidate() result = self.Message.onchange(values, 'discussion', field_onchange) self.assertIn('name', result['value']) self.assertEqual(result['value']['name'], "[%s] %s" % (discussion.name, USER.name)) # changing 'body' should recompute 'size' values = { 'discussion': discussion.id, 'name': "[%s] %s" % (discussion.name, USER.name), 'body': BODY, 'author': USER.id, 'size': 0, } self.env.cache.invalidate() result = self.Message.onchange(values, 'body', field_onchange) self.assertIn('size', result['value']) self.assertEqual(result['value']['size'], len(BODY)) # changing 'body' should not recompute 'name', even if 'discussion' and # 'name' are not consistent with each other values = { 'discussion': discussion.id, 'name': False, 'body': BODY, 'author': USER.id, 'size': 0, } self.env.cache.invalidate() result = self.Message.onchange(values, 'body', field_onchange) self.assertNotIn('name', result['value']) def test_onchange_many2one(self): Category = self.env['test_new_api.category'] field_onchange = Category._onchange_spec() self.assertEqual(field_onchange.get('parent'), '1') root = Category.create(dict(name='root')) values = { 'name': 'test', 'parent': root.id, 'root_categ': False, } self.env.cache.invalidate() result = Category.onchange(values, 'parent', field_onchange).get('value', {}) self.assertIn('root_categ', result) self.assertEqual(result['root_categ'], root.name_get()[0]) values.update(result) values['parent'] = False self.env.cache.invalidate() result = Category.onchange(values, 'parent', field_onchange).get('value', {}) self.assertIn('root_categ', result) self.assertIs(result['root_categ'], False) def test_onchange_one2many(self): """ test the effect of onchange() on one2many fields """ USER = self.env.user # create an independent message message1 = self.Message.create({'body': "ABC"}) message2 = self.Message.create({'body': "ABC"}) self.assertEqual(message1.name, "[%s] %s" % ('', USER.name)) field_onchange = self.Discussion._onchange_spec() self.assertEqual(field_onchange.get('name'), '1') self.assertEqual(field_onchange.get('messages'), '1') self.assertItemsEqual( strip_prefix('messages.', field_onchange), ['author', 'body', 'name', 'size', 'important'], ) # modify discussion name values = { 'name': "Foo", 'categories': [], 'moderator': False, 'participants': [], 'messages': [ Command.link(message1.id), Command.link(message2.id), Command.update(message2.id, {'body': "XYZ"}), Command.create({ 'name': "[%s] %s" % ('', USER.name), 'body': "ABC", 'author': USER.id, 'size': 3, 'important': False, }), ], } self.env.cache.invalidate() result = self.Discussion.onchange(values, 'name', field_onchange) self.assertIn('messages', result['value']) self.assertEqual(result['value']['messages'], [ Command.clear(), Command.update(message1.id, { 'name': "[%s] %s" % ("Foo", USER.name), 'body': "ABC", 'author': USER.name_get()[0], 'size': 3, 'important': False, }), Command.update(message2.id, { 'name': "[%s] %s" % ("Foo", USER.name), 'body': "XYZ", # this must be sent back 'author': USER.name_get()[0], 'size': 3, 'important': False, }), Command.create({ 'name': "[%s] %s" % ("Foo", USER.name), 'body': "ABC", 'author': USER.name_get()[0], 'size': 3, 'important': False, }), ]) # ensure onchange changing one2many without subfield works one_level_fields = {k: v for k, v in field_onchange.items() if k.count('.') < 1} values = dict(values, name='{generate_dummy_message}') result = self.Discussion.with_context(generate_dummy_message=True).onchange(values, 'name', one_level_fields) self.assertEqual(result['value']['messages'], [ Command.clear(), Command.link(message1.id), Command.link(message2.id), Command.create({}), Command.create({}), ]) def test_onchange_one2many_reference(self): """ test the effect of onchange() on one2many fields with line references """ BODY = "What a beautiful day!" USER = self.env.user REFERENCE = "virtualid42" field_onchange = self.Discussion._onchange_spec() self.assertEqual(field_onchange.get('name'), '1') self.assertEqual(field_onchange.get('messages'), '1') self.assertItemsEqual( strip_prefix('messages.', field_onchange), ['author', 'body', 'name', 'size', 'important'], ) # modify discussion name, and check that the reference of the new line # is returned values = { 'name': "Foo", 'categories': [], 'moderator': False, 'participants': [], 'messages': [ (0, REFERENCE, { 'name': "[%s] %s" % ('', USER.name), 'body': BODY, 'author': USER.id, 'size': len(BODY), 'important': False, }), ], } self.env.cache.invalidate() result = self.Discussion.onchange(values, 'name', field_onchange) self.assertIn('messages', result['value']) self.assertItemsEqual(result['value']['messages'], [ (5, 0, 0), (0, REFERENCE, { 'name': "[%s] %s" % ("Foo", USER.name), 'body': BODY, 'author': USER.name_get()[0], 'size': len(BODY), 'important': False, }), ]) def test_onchange_one2many_multi(self): """ test the effect of multiple onchange methods on one2many fields """ partner1 = self.env['res.partner'].create({'name': 'A partner'}) multi = self.env['test_new_api.multi'].create({'partner': partner1.id}) line1 = multi.lines.create({'multi': multi.id}) field_onchange = multi._onchange_spec() self.assertEqual(field_onchange, { 'name': '1', 'partner': '1', 'lines': None, 'lines.name': None, 'lines.partner': None, 'lines.tags': None, 'lines.tags.name': None, }) values = multi._convert_to_write({key: multi[key] for key in ('name', 'partner', 'lines')}) self.assertEqual(values, { 'name': partner1.name, 'partner': partner1.id, 'lines': [Command.set([line1.id])], }) # modify 'partner' # -> set 'partner' on all lines # -> recompute 'name' # -> set 'name' on all lines partner2 = self.env['res.partner'].create({'name': 'A second partner'}) values = { 'name': partner1.name, 'partner': partner2.id, # this one just changed 'lines': [Command.set([line1.id]), Command.create({'name': False, 'partner': False, 'tags': [Command.clear()]})], } self.env.cache.invalidate() result = multi.onchange(values, 'partner', field_onchange) self.assertEqual(result['value'], { 'name': partner2.name, 'lines': [ Command.clear(), Command.update(line1.id, { 'name': partner2.name, 'partner': (partner2.id, partner2.name), 'tags': [Command.clear()], }), Command.create({ 'name': partner2.name, 'partner': (partner2.id, partner2.name), 'tags': [Command.clear()], }), ], }) # do it again, but this time with a new tag on the second line values = { 'name': partner1.name, 'partner': partner2.id, # this one just changed 'lines': [Command.set([line1.id]), Command.create({'name': False, 'partner': False, 'tags': [Command.clear(), Command.create({'name': 'Tag'})]})], } self.env.cache.invalidate() result = multi.onchange(values, 'partner', field_onchange) expected_value = { 'name': partner2.name, 'lines': [ Command.clear(), Command.update(line1.id, { 'name': partner2.name, 'partner': (partner2.id, partner2.name), 'tags': [Command.clear()], }), Command.create({ 'name': partner2.name, 'partner': (partner2.id, partner2.name), 'tags': [Command.clear(), Command.create({'name': 'Tag'})], }), ], } self.assertEqual(result['value'], expected_value) # ensure ID is not returned when asked and a many2many record is set to be created self.env.cache.invalidate() result = multi.onchange(values, 'partner', dict(field_onchange, **{'lines.tags.id': None})) self.assertEqual(result['value'], expected_value) # ensure inverse of one2many field is not returned self.env.cache.invalidate() result = multi.onchange(values, 'partner', dict(field_onchange, **{'lines.multi': None})) self.assertEqual(result['value'], expected_value) def test_onchange_specific(self): """ test the effect of field-specific onchange method """ discussion = self.env.ref('test_new_api.discussion_0') demo = self.user_demo field_onchange = self.Discussion._onchange_spec() self.assertEqual(field_onchange.get('moderator'), '1') self.assertItemsEqual( strip_prefix('participants.', field_onchange), ['display_name'], ) # first remove demo user from participants discussion.participants -= demo self.assertNotIn(demo, discussion.participants) # check that demo_user is added to participants when set as moderator values = { 'name': discussion.name, 'moderator': demo.id, 'categories': [Command.link(cat.id) for cat in discussion.categories], 'messages': [Command.link(msg.id) for msg in discussion.messages], 'participants': [Command.link(usr.id) for usr in discussion.participants], } self.env.cache.invalidate() result = discussion.onchange(values, 'moderator', field_onchange) self.assertIn('participants', result['value']) self.assertItemsEqual( result['value']['participants'], [Command.clear()] + [Command.link(user.id) for user in discussion.participants + demo], ) def test_onchange_default(self): """ test the effect of a conditional user-default on a field """ Foo = self.env['test_new_api.foo'] field_onchange = Foo._onchange_spec() self.assertTrue(Foo._fields['value1'].change_default) self.assertEqual(field_onchange.get('value1'), '1') # create a user-defined default based on 'value1' self.env['ir.default'].set('test_new_api.foo', 'value2', 666, condition='value1=42') # setting 'value1' to 42 should trigger the change of 'value2' self.env.cache.invalidate() values = {'name': 'X', 'value1': 42, 'value2': False} result = Foo.onchange(values, 'value1', field_onchange) self.assertEqual(result['value'], {'value2': 666}) # setting 'value1' to 24 should not trigger the change of 'value2' self.env.cache.invalidate() values = {'name': 'X', 'value1': 24, 'value2': False} result = Foo.onchange(values, 'value1', field_onchange) self.assertEqual(result['value'], {}) def test_onchange_one2many_first(self): partner = self.env['res.partner'].create({ 'name': 'X', 'country_id': self.env.ref('base.be').id, }) with common.Form(self.env['test_new_api.multi']) as form: form.partner = partner self.assertEqual(form.partner, partner) self.assertEqual(form.name, partner.name) with form.lines.new() as line: # the first onchange() must have computed partner self.assertEqual(line.partner, partner) def test_onchange_one2many_value(self): """ test the value of the one2many field inside the onchange """ discussion = self.env.ref('test_new_api.discussion_0') demo = self.user_demo field_onchange = self.Discussion._onchange_spec() self.assertEqual(field_onchange.get('messages'), '1') self.assertEqual(len(discussion.messages), 3) messages = [Command.link(msg.id) for msg in discussion.messages] messages[0] = (1, messages[0][1], {'body': 'test onchange'}) lines = ["%s:%s" % (m.name, m.body) for m in discussion.messages] lines[0] = "%s:%s" % (discussion.messages[0].name, 'test onchange') values = { 'name': discussion.name, 'moderator': demo.id, 'categories': [Command.link(cat.id) for cat in discussion.categories], 'messages': messages, 'participants': [Command.link(usr.id) for usr in discussion.participants], 'message_concat': False, } result = discussion.onchange(values, 'messages', field_onchange) self.assertIn('message_concat', result['value']) self.assertEqual(result['value']['message_concat'], "\n".join(lines)) def test_onchange_one2many_with_domain_on_related_field(self): """ test the value of the one2many field when defined with a domain on a related field""" discussion = self.env.ref('test_new_api.discussion_0') demo = self.user_demo # mimic UI behaviour, so we get subfields # (we need at least subfield: 'important_emails.important') view_info = self.Discussion.fields_view_get( view_id=self.env.ref('test_new_api.discussion_form').id, view_type='form') field_onchange = self.Discussion._onchange_spec(view_info=view_info) self.assertEqual(field_onchange.get('messages'), '1') BODY = "What a beautiful day!" USER = self.env.user # create standalone email email = self.EmailMessage.create({ 'discussion': discussion.id, 'name': "[%s] %s" % ('', USER.name), 'body': BODY, 'author': USER.id, 'important': False, 'email_to': demo.email, }) # check if server-side cache is working correctly self.env.cache.invalidate() self.assertIn(email, discussion.emails) self.assertNotIn(email, discussion.important_emails) email.important = True self.assertIn(email, discussion.important_emails) # check that when trigger an onchange, we don't reset important emails # (force `invalidate` as but appear in onchange only when we get a cache # miss) self.env.cache.invalidate() self.assertEqual(len(discussion.messages), 4) values = { 'name': "Foo Bar", 'moderator': demo.id, 'categories': [Command.link(cat.id) for cat in discussion.categories], 'messages': [Command.link(msg.id) for msg in discussion.messages], 'participants': [Command.link(usr.id) for usr in discussion.participants], 'important_messages': [Command.link(msg.id) for msg in discussion.important_messages], 'important_emails': [Command.link(eml.id) for eml in discussion.important_emails], } self.env.cache.invalidate() result = discussion.onchange(values, 'name', field_onchange) self.assertEqual( result['value']['important_emails'], [Command.clear(), Command.update(email.id, { 'name': u'[Foo Bar] %s' % USER.name, 'body': BODY, 'author': USER.name_get()[0], 'size': len(BODY), 'important': True, 'email_to': demo.email, })], ) def test_onchange_related(self): value = { 'message': 1, 'message_name': False, 'message_currency': 2, } field_onchange = { 'message': '1', 'message_name': None, 'message_currency': None, } onchange_result = { 'message_name': 'Hey dude!', 'message_currency': self.env.user.name_get()[0], } self.env.cache.invalidate() Message = self.env['test_new_api.related'] result = Message.onchange(value, 'message', field_onchange) self.assertEqual(result['value'], onchange_result) self.env.cache.invalidate() Message = self.env(user=self.user_demo.id)['test_new_api.related'] result = Message.onchange(value, 'message', field_onchange) self.assertEqual(result['value'], onchange_result) def test_onchange_many2one_one2many(self): """ Setting a many2one field should not read the inverse one2many. """ discussion = self.env.ref('test_new_api.discussion_0') field_onchange = self.Message._onchange_spec() self.assertEqual(field_onchange.get('discussion'), '1') values = { 'discussion': discussion.id, 'name': "[%s] %s" % ('', self.env.user.name), 'body': False, 'author': self.env.uid, 'size': 0, } called = [False] orig_read = type(discussion).read def mock_read(self, fields=None, load='_classic_read'): if discussion in self and 'messages' in (fields or ()): called[0] = True return orig_read(self, fields, load) # changing 'discussion' on message should not read 'messages' on discussion with patch.object(type(discussion), 'read', mock_read, create=True): self.env.cache.invalidate() self.Message.onchange(values, 'discussion', field_onchange) self.assertFalse(called[0], "discussion.messages has been read") def test_onchange_one2many_many2one_in_form(self): order = self.env['test_new_api.monetary_order'].create({ 'currency_id': self.env.ref('base.USD').id, }) # this call to onchange() is made when creating a new line in field # order.line_ids; check what happens when the line's form view contains # the inverse many2one field values = {'order_id': {'id': order.id, 'currency_id': order.currency_id.id}} field_onchange = dict.fromkeys(['order_id', 'subtotal'], '') result = self.env['test_new_api.monetary_order_line'].onchange(values, [], field_onchange) self.assertEqual(result['value']['order_id'], (order.id, order.display_name)) def test_onchange_inherited(self): """ Setting an inherited field should assign the field on the parent record. """ foo, bar = self.env['test_new_api.multi.tag'].create([{'name': 'Foo'}, {'name': 'Bar'}]) view = self.env['ir.ui.view'].create({ 'name': 'Payment form view', 'model': 'test_new_api.payment', 'arch': """ <form> <field name="move_id" readonly="1" required="0"/> <field name="tag_id"/> <field name="tag_name"/> <field name="tag_repeat"/> <field name="tag_string"/> </form> """, }) # both fields 'tag_id' and 'tag_name' are inherited through 'move_id'; # assigning 'tag_id' should modify 'move_id.tag_id' accordingly, which # should in turn recompute `move.tag_name` and `tag_name` form = Form(self.env['test_new_api.payment'], view) self.assertEqual(form.tag_name, False) form.tag_id = foo self.assertEqual(form.tag_name, 'Foo') self.assertEqual(form.tag_string, '') form.tag_repeat = 2 self.assertEqual(form.tag_name, 'Foo') self.assertEqual(form.tag_string, 'FooFoo') payment = form.save() self.assertEqual(payment.tag_id, foo) self.assertEqual(payment.tag_name, 'Foo') self.assertEqual(payment.tag_repeat, 2) self.assertEqual(payment.tag_string, 'FooFoo') with Form(payment, view) as form: form.tag_id = bar self.assertEqual(form.tag_name, 'Bar') self.assertEqual(form.tag_string, 'BarBar') form.tag_repeat = 3 self.assertEqual(form.tag_name, 'Bar') self.assertEqual(form.tag_string, 'BarBarBar') self.assertEqual(payment.tag_id, bar) self.assertEqual(payment.tag_name, 'Bar') self.assertEqual(payment.tag_repeat, 3) self.assertEqual(payment.tag_string, 'BarBarBar') class TestComputeOnchange(common.TransactionCase): def test_create(self): model = self.env['test_new_api.compute.onchange'] # compute 'bar' (readonly) and 'baz' (editable) record = model.create({'active': True}) self.assertEqual(record.bar, "r") self.assertEqual(record.baz, "z") # compute 'bar' and 'baz' record = model.create({'active': True, 'foo': "foo"}) self.assertEqual(record.bar, "foor") self.assertEqual(record.baz, "fooz") # compute 'bar' but not 'baz' record = model.create({'active': True, 'foo': "foo", 'bar': "bar", 'baz': "baz"}) self.assertEqual(record.bar, "foor") self.assertEqual(record.baz, "baz") # compute 'bar' and 'baz', but do not change its value record = model.create({'active': False, 'foo': "foo"}) self.assertEqual(record.bar, "foor") self.assertEqual(record.baz, False) # compute 'bar' but not 'baz' record = model.create({'active': False, 'foo': "foo", 'bar': "bar", 'baz': "baz"}) self.assertEqual(record.bar, "foor") self.assertEqual(record.baz, "baz") def test_copy(self): Model = self.env['test_new_api.compute.onchange'] # create tags tag_foo, tag_bar = self.env['test_new_api.multi.tag'].create([ {'name': 'foo1'}, {'name': 'bar1'}, ]) # compute 'bar' (readonly), 'baz', 'line_ids' and 'tag_ids' (editable) record = Model.create({'active': True, 'foo': "foo1"}) self.assertEqual(record.bar, "foo1r") self.assertEqual(record.baz, "foo1z") self.assertEqual(record.line_ids.mapped('foo'), ['foo1']) self.assertEqual(record.tag_ids, tag_foo) # manually update 'baz' and 'lines' to test copy attribute record.write({ 'baz': "baz1", 'line_ids': [Command.create({'foo': 'bar'})], 'tag_ids': [Command.link(tag_bar.id)], }) self.assertEqual(record.bar, "foo1r") self.assertEqual(record.baz, "baz1") self.assertEqual(record.line_ids.mapped('foo'), ['foo1', 'bar']) self.assertEqual(record.tag_ids, tag_foo + tag_bar) # copy the record, and check results copied = record.copy() self.assertEqual(copied.foo, "foo1 (copy)") # copied and modified self.assertEqual(copied.bar, "foo1 (copy)r") # computed self.assertEqual(copied.baz, "baz1") # copied self.assertEqual(record.line_ids.mapped('foo'), ['foo1', 'bar']) # copied self.assertEqual(record.tag_ids, tag_foo + tag_bar) # copied def test_write(self): model = self.env['test_new_api.compute.onchange'] record = model.create({'active': True, 'foo': "foo"}) self.assertEqual(record.bar, "foor") self.assertEqual(record.baz, "fooz") # recompute 'bar' (readonly) and 'baz' (editable) record.write({'foo': "foo1"}) self.assertEqual(record.bar, "foo1r") self.assertEqual(record.baz, "foo1z") # recompute 'bar' but not 'baz' record.write({'foo': "foo2", 'bar': "bar2", 'baz': "baz2"}) self.assertEqual(record.bar, "foo2r") self.assertEqual(record.baz, "baz2") # recompute 'bar' and 'baz', but do not change its value record.write({'active': False, 'foo': "foo3"}) self.assertEqual(record.bar, "foo3r") self.assertEqual(record.baz, "baz2") # recompute 'bar' but not 'baz' record.write({'active': False, 'foo': "foo4", 'bar': "bar4", 'baz': "baz4"}) self.assertEqual(record.bar, "foo4r") self.assertEqual(record.baz, "baz4") def test_set(self): model = self.env['test_new_api.compute.onchange'] record = model.create({'active': True, 'foo': "foo"}) self.assertEqual(record.bar, "foor") self.assertEqual(record.baz, "fooz") # recompute 'bar' (readonly) and 'baz' (editable) record.foo = "foo1" self.assertEqual(record.bar, "foo1r") self.assertEqual(record.baz, "foo1z") # do not recompute 'baz' record.baz = "baz2" self.assertEqual(record.bar, "foo1r") self.assertEqual(record.baz, "baz2") # recompute 'baz', but do not change its value record.active = False self.assertEqual(record.bar, "foo1r") self.assertEqual(record.baz, "baz2") # recompute 'baz', but do not change its value record.foo = "foo3" self.assertEqual(record.bar, "foo3r") self.assertEqual(record.baz, "baz2") # do not recompute 'baz' record.baz = "baz4" self.assertEqual(record.bar, "foo3r") self.assertEqual(record.baz, "baz4") def test_set_new(self): model = self.env['test_new_api.compute.onchange'] record = model.new({'active': True}) self.assertEqual(record.bar, "r") self.assertEqual(record.baz, "z") # recompute 'bar' (readonly) and 'baz' (editable) record.foo = "foo1" self.assertEqual(record.bar, "foo1r") self.assertEqual(record.baz, "foo1z") # do not recompute 'baz' record.baz = "baz2" self.assertEqual(record.bar, "foo1r") self.assertEqual(record.baz, "baz2") # recompute 'baz', but do not change its value record.active = False self.assertEqual(record.bar, "foo1r") self.assertEqual(record.baz, "baz2") # recompute 'baz', but do not change its value record.foo = "foo3" self.assertEqual(record.bar, "foo3r") self.assertEqual(record.baz, "baz2") # do not recompute 'baz' record.baz = "baz4" self.assertEqual(record.bar, "foo3r") self.assertEqual(record.baz, "baz4") def test_onchange(self): # check computations of 'bar' (readonly) and 'baz' (editable) form = common.Form(self.env['test_new_api.compute.onchange']) self.assertEqual(form.bar, "r") self.assertEqual(form.baz, False) form.active = True self.assertEqual(form.bar, "r") self.assertEqual(form.baz, "z") form.foo = "foo1" self.assertEqual(form.bar, "foo1r") self.assertEqual(form.baz, "foo1z") form.baz = "baz2" self.assertEqual(form.bar, "foo1r") self.assertEqual(form.baz, "baz2") form.active = False self.assertEqual(form.bar, "foo1r") self.assertEqual(form.baz, "baz2") form.foo = "foo3" self.assertEqual(form.bar, "foo3r") self.assertEqual(form.baz, "baz2") form.active = True self.assertEqual(form.bar, "foo3r") self.assertEqual(form.baz, "foo3z") with form.line_ids.new() as line: # check computation of 'bar' (readonly) self.assertEqual(line.foo, False) self.assertEqual(line.bar, "r") line.foo = "foo" self.assertEqual(line.foo, "foo") self.assertEqual(line.bar, "foor") record = form.save() self.assertEqual(record.bar, "foo3r") self.assertEqual(record.baz, "foo3z") form = common.Form(record) self.assertEqual(form.bar, "foo3r") self.assertEqual(form.baz, "foo3z") form.foo = "foo4" self.assertEqual(form.bar, "foo4r") self.assertEqual(form.baz, "foo4z") form.baz = "baz5" self.assertEqual(form.bar, "foo4r") self.assertEqual(form.baz, "baz5") form.active = False self.assertEqual(form.bar, "foo4r") self.assertEqual(form.baz, "baz5") form.foo = "foo6" self.assertEqual(form.bar, "foo6r") self.assertEqual(form.baz, "baz5") def test_onchange_default(self): form = common.Form(self.env['test_new_api.compute.onchange'].with_context( default_active=True, default_foo="foo", default_baz="baz", )) # 'baz' is computed editable, so when given a default value it should # 'not be recomputed, even if a dependency also has a default value self.assertEqual(form.foo, "foo") self.assertEqual(form.bar, "foor") self.assertEqual(form.baz, "baz") def test_onchange_once(self): """ Modifies `foo` field which will trigger an onchange method and checks it was triggered only one time. """ form = Form(self.env['test_new_api.compute.onchange'].with_context(default_foo="oof")) record = form.save() self.assertEqual(record.foo, "oof") self.assertEqual(record.count, 1, "value onchange must be called only one time") def test_onchange_one2many(self): record = self.env['test_new_api.model_parent_m2o'].create({ 'name': 'Family', 'child_ids': [ Command.create({'name': 'W', 'cost': 10}), Command.create({'name': 'X', 'cost': 10}), Command.create({'name': 'Y'}), Command.create({'name': 'Z'}), ], }) record.flush() self.assertEqual(record.child_ids.mapped('name'), list('WXYZ')) self.assertEqual(record.cost, 22) # modifying a line should not recompute the cost on other lines with common.Form(record) as form: with form.child_ids.edit(1) as line: line.name = 'XXX' self.assertEqual(form.cost, 15) with form.child_ids.edit(1) as line: line.cost = 20 self.assertEqual(form.cost, 32) with form.child_ids.edit(2) as line: line.cost = 30 self.assertEqual(form.cost, 61) def test_onchange_editable_compute_one2many(self): # create a record with a computed editable field ('edit') on lines record = self.env['test_new_api.compute_editable'].create({'line_ids': [(0, 0, {'value': 7})]}) record.flush() line = record.line_ids self.assertRecordValues(line, [{'value': 7, 'edit': 7, 'count': 0}]) # retrieve the onchange spec for calling 'onchange' spec = Form(record)._view['onchange'] # The onchange on 'line_ids' should increment 'count' and keep the value # of 'edit' (this field should not be recomputed), whatever the order of # the fields in the dictionary. This ensures that the value set by the # user on a computed editable field on a line is not lost. line_ids = [ Command.update(line.id, {'value': 8, 'edit': 9, 'count': 0}), Command.create({'value': 8, 'edit': 9, 'count': 0}), ] result = record.onchange({'line_ids': line_ids}, 'line_ids', spec) expected = {'value': { 'line_ids': [ Command.clear(), Command.update(line.id, {'value': 8, 'edit': 9, 'count': 8}), Command.create({'value': 8, 'edit': 9, 'count': 8}), ], }} self.assertEqual(result, expected) # change dict order in lines, and try again line_ids = [ (op, id_, dict(reversed(list(vals.items())))) for op, id_, vals in line_ids ] result = record.onchange({'line_ids': line_ids}, 'line_ids', spec) self.assertEqual(result, expected) def test_computed_editable_one2many_domain(self): """ Test a computed, editable one2many field with a domain. """ record = self.env['test_new_api.one2many'].create({'name': 'foo'}) self.assertRecordValues(record.line_ids, [ {'name': 'foo', 'count': 1}, ]) # trigger recomputation by changing name record.name = 'bar' self.assertRecordValues(record.line_ids, [ {'name': 'foo', 'count': 1}, {'name': 'bar', 'count': 1}, ]) # manually adding a line should not trigger recomputation record.line_ids.create({'name': 'baz', 'container_id': record.id}) self.assertRecordValues(record.line_ids, [ {'name': 'foo', 'count': 1}, {'name': 'bar', 'count': 1}, {'name': 'baz', 'count': 1}, ]) # changing the field in the domain should not trigger recomputation... record.line_ids[-1].count = 2 self.assertRecordValues(record.line_ids, [ {'name': 'foo', 'count': 1}, {'name': 'bar', 'count': 1}, {'name': 'baz', 'count': 2}, ]) # ...and may show cache inconsistencies record.line_ids[-1].count = 0 self.assertRecordValues(record.line_ids, [ {'name': 'foo', 'count': 1}, {'name': 'bar', 'count': 1}, {'name': 'baz', 'count': 0}, ]) record.flush() record.invalidate_cache() self.assertRecordValues(record.line_ids, [ {'name': 'foo', 'count': 1}, {'name': 'bar', 'count': 1}, ])
39.713519
37,013
14,371
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.tests.common import TransactionCase from odoo.exceptions import MissingError from odoo import Command class One2manyCase(TransactionCase): def setUp(self): super(One2manyCase, self).setUp() self.Line = self.env["test_new_api.multi.line"] self.multi = self.env["test_new_api.multi"].create({ "name": "What is up?" }) # data for One2many with inverse field Integer self.Edition = self.env["test_new_api.creativework.edition"] self.Book = self.env["test_new_api.creativework.book"] self.Movie = self.env["test_new_api.creativework.movie"] book_model_id = self.env['ir.model'].search([('model', '=', self.Book._name)]).id movie_model_id = self.env['ir.model'].search([('model', '=', self.Movie._name)]).id books_data = ( ('Imaginary book', ()), ('Another imaginary book', ()), ('Nineteen Eighty Four', ('First edition', 'Fourth Edition')) ) movies_data = ( ('The Gold Rush', ('1925 (silent)', '1942')), ('Imaginary movie', ()), ('Another imaginary movie', ()) ) for name, editions in books_data: book_id = self.Book.create({'name': name}).id for edition in editions: self.Edition.create({'res_model_id': book_model_id, 'name': edition, 'res_id': book_id}) for name, editions in movies_data: movie_id = self.Movie.create({'name': name}).id for edition in editions: self.Edition.create({'res_model_id': movie_model_id, 'name': edition, 'res_id': movie_id}) def operations(self): """Run operations on o2m fields to check all works fine.""" # Check the lines first self.assertItemsEqual( self.multi.lines.mapped('name'), [str(i) for i in range(10)]) # Modify the first line and drop the last one self.multi.lines[0].name = "hello" self.multi.lines = self.multi.lines[:-1] self.assertEqual(len(self.multi.lines), 9) self.assertIn("hello", self.multi.lines.mapped('name')) if not self.multi.id: return # Invalidate the cache and check again; this crashes if the value # of self.multi.lines in cache contains new records self.multi.invalidate_cache() self.assertEqual(len(self.multi.lines), 9) self.assertIn("hello", self.multi.lines.mapped('name')) def test_new_one_by_one(self): """Check lines created with ``new()`` and appended one by one.""" for name in range(10): self.multi.lines |= self.Line.new({"name": str(name)}) self.operations() def test_new_single(self): """Check lines created with ``new()`` and added in one step.""" self.multi.lines = self.Line.browse( [self.Line.new({"name": str(name)}).id for name in range(10)] ) self.operations() def test_create_one_by_one(self): """Check lines created with ``create()`` and appended one by one.""" for name in range(10): self.multi.lines |= self.Line.create({"name": str(name)}) self.operations() def test_create_single(self): """Check lines created with ``create()`` and added in one step.""" self.multi.lines = self.Line.browse( [self.Line.create({"name": str(name)}).id for name in range(10)] ) self.operations() def test_rpcstyle_one_by_one(self): """Check lines created with RPC style and appended one by one.""" for name in range(10): self.multi.lines = [Command.create({"name": str(name)})] self.operations() def test_rpcstyle_one_by_one_on_new(self): self.multi = self.env["test_new_api.multi"].new({ "name": "What is up?" }) for name in range(10): self.multi.lines = [Command.create({"name": str(name)})] self.operations() def test_rpcstyle_single(self): """Check lines created with RPC style and added in one step""" self.multi.lines = [Command.create({'name': str(name)}) for name in range(10)] self.operations() def test_rpcstyle_single_on_new(self): self.multi = self.env["test_new_api.multi"].new({ "name": "What is up?" }) self.multi.lines = [Command.create({'name': str(name)}) for name in range(10)] self.operations() def test_many2one_integer(self): """Test several models one2many with same inverse Integer field""" # utility function to convert records to tuples with id,name t = lambda records: records.mapped(lambda r: (r.id, r.name)) books = self.Book.search([]) books_with_edition = books.filtered(lambda r: r.editions) movies = self.Movie.search([]) movies_without_edition = movies.filtered(lambda r: not r.editions) movies_with_edition = movies.filtered(lambda r: r.editions) movie_editions = movies_with_edition.editions one_movie_edition = movie_editions[0] res_movies_without_edition = self.Movie.search([('editions', '=', False)]) self.assertItemsEqual(t(res_movies_without_edition), t(movies_without_edition)) res_movies_with_edition = self.Movie.search([('editions', '!=', False)]) self.assertItemsEqual(t(res_movies_with_edition), t(movies_with_edition)) res_books_with_movie_edition = self.Book.search([('editions', 'in', movie_editions.ids)]) self.assertFalse(t(res_books_with_movie_edition)) res_books_without_movie_edition = self.Book.search([('editions', 'not in', movie_editions.ids)]) self.assertItemsEqual(t(res_books_without_movie_edition), t(books)) res_books_without_one_movie_edition = self.Book.search([('editions', 'not in', movie_editions[:1].ids)]) self.assertItemsEqual(t(res_books_without_one_movie_edition), t(books)) res_books_with_one_movie_edition_name = self.Book.search([('editions', '=', movie_editions[:1].name)]) self.assertFalse(t(res_books_with_one_movie_edition_name)) res_books_without_one_movie_edition_name = self.Book.search([('editions', '!=', movie_editions[:1].name)]) self.assertItemsEqual(t(res_books_without_one_movie_edition_name), t(books)) res_movies_not_of_edition_name = self.Movie.search([('editions', '!=', one_movie_edition.name)]) self.assertItemsEqual(t(res_movies_not_of_edition_name), t(movies.filtered(lambda r: one_movie_edition not in r.editions))) def test_merge_partner(self): model = self.env['test_new_api.field_with_caps'] partner = self.env['res.partner'] p1 = partner.create({'name': 'test1'}) p2 = partner.create({'name': 'test2'}) model1 = model.create({'pArTneR_321_id': p1.id}) model2 = model.create({'pArTneR_321_id': p2.id}) self.env['base.partner.merge.automatic.wizard']._merge((p1 + p2).ids, p1) self.assertFalse(p2.exists()) self.assertTrue(p1.exists()) self.assertEqual(model1.pArTneR_321_id, p1) self.assertTrue(model2.exists()) self.assertEqual(model2.pArTneR_321_id, p1) def test_merge_partner_archived(self): partner = self.env['res.partner'] p1 = partner.create({'name': 'test1'}) p2 = partner.create({'name': 'test2'}) p3 = partner.create({'name': 'test3', 'active': False}) partners_ids = (p1 + p2 + p3) wizard = self.env['base.partner.merge.automatic.wizard'].with_context(active_ids=partners_ids.ids, active_model='res.partner').create({}) self.assertEqual(wizard.partner_ids, partners_ids) self.assertEqual(wizard.dst_partner_id, p2) wizard.action_merge() self.assertFalse(p1.exists()) self.assertTrue(p2.exists()) self.assertFalse(p3.exists()) def test_cache_invalidation(self): """ Cache invalidation for one2many with integer inverse. """ record0 = self.env['test_new_api.attachment.host'].create({}) with self.assertQueryCount(0): self.assertFalse(record0.attachment_ids, "inconsistent cache") # creating attachment must compute name and invalidate attachment_ids attachment = self.env['test_new_api.attachment'].create({ 'res_model': record0._name, 'res_id': record0.id, }) attachment.flush() with self.assertQueryCount(0): self.assertEqual(attachment.name, record0.display_name, "field should be computed") with self.assertQueryCount(1): self.assertEqual(record0.attachment_ids, attachment, "inconsistent cache") # creating a host should not attempt to recompute attachment.name with self.assertQueryCount(1): record1 = self.env['test_new_api.attachment.host'].create({}) with self.assertQueryCount(0): # field res_id should not have been invalidated attachment.res_id with self.assertQueryCount(0): self.assertFalse(record1.attachment_ids, "inconsistent cache") # writing on res_id must recompute name and invalidate attachment_ids attachment.res_id = record1.id attachment.flush() with self.assertQueryCount(0): self.assertEqual(attachment.name, record1.display_name, "field should be recomputed") with self.assertQueryCount(1): self.assertEqual(record1.attachment_ids, attachment, "inconsistent cache") with self.assertQueryCount(1): self.assertFalse(record0.attachment_ids, "inconsistent cache") def test_recompute(self): """ test recomputation of fields that indirecly depend on one2many """ discussion = self.env.ref('test_new_api.discussion_0') self.assertTrue(discussion.messages) # detach message from discussion message = discussion.messages[0] message.discussion = False # DLE P54: a computed stored field should not depend on the context # writing on the one2many and actually modifying the relation must # trigger recomputation of fields that depend on its inverse many2one # self.assertNotIn(message, discussion.messages) # discussion.with_context(compute_name='X').write({'messages': [(4, message.id)]}) # self.assertEqual(message.name, 'X') # writing on the one2many without modifying the relation should not # trigger recomputation of fields that depend on its inverse many2one # self.assertIn(message, discussion.messages) # discussion.with_context(compute_name='Y').write({'messages': [(4, message.id)]}) # self.assertEqual(message.name, 'X') def test_dont_write_the_existing_childs(self): """ test that the existing child should not be changed when adding a new child to the parent. This is the behaviour of the form view.""" parent = self.env['test_new_api.model_parent_m2o'].create({ 'name': 'parent', 'child_ids': [Command.create({'name': 'A'})], }) a = parent.child_ids[0] parent.write({'child_ids': [Command.link(a.id), Command.create({'name': 'B'})]}) def test_recomputation_ends(self): """ Regression test for neverending recomputation. """ parent = self.env['test_new_api.model_parent_m2o'].create({'name': 'parent'}) child = self.env['test_new_api.model_child_m2o'].create({'name': 'A', 'parent_id': parent.id}) self.assertEqual(child.size1, 6) # delete parent, and check that recomputation ends parent.unlink() parent.flush() def test_compute_stored_many2one_one2many(self): container = self.env['test_new_api.compute.container'].create({'name': 'Foo'}) self.assertFalse(container.member_ids) member = self.env['test_new_api.compute.member'].create({'name': 'Foo'}) # at this point, member.container_id must be computed for member to # appear in container.member_ids self.assertEqual(container.member_ids, member) def test_reward_line_delete(self): order = self.env['test_new_api.order'].create({ 'line_ids': [ Command.create({'product': 'a'}), Command.create({'product': 'b'}), Command.create({'product': 'b', 'reward': True}), ], }) line0, line1, line2 = order.line_ids # this is what the client sends to delete the 2nd line; it should not # crash when deleting the 2nd line automatically deletes the 3rd line order.write({ 'line_ids': [ Command.link(line0.id), Command.delete(line1.id), Command.link(line2.id), ], }) self.assertEqual(order.line_ids, line0) # but linking a missing line on purpose is an error with self.assertRaises(MissingError): order.write({ 'line_ids': [Command.link(line0.id), Command.link(line1.id)], }) def test_parent_id(self): Team = self.env['test_new_api.team'] Member = self.env['test_new_api.team.member'] team1 = Team.create({'name': 'ORM'}) team2 = Team.create({'name': 'Bugfix', 'parent_id': team1.id}) team3 = Team.create({'name': 'Support', 'parent_id': team2.id}) Member.create({'name': 'Raphael', 'team_id': team1.id}) member2 = Member.create({'name': 'Noura', 'team_id': team3.id}) Member.create({'name': 'Ivan', 'team_id': team2.id}) # In this specific case... self.assertEqual(member2.id, member2.team_id.parent_id.id) # ...we had an infinite recursion on making the following search. with self.assertRaises(ValueError): Team.search([('member_ids', 'child_of', member2.id)]) # Also, test a simple infinite loop if record is marked as a parent of itself team1.parent_id = team1.id # Check that the search is not stuck in the loop Team.search([('id', 'parent_of', team1.id)]) Team.search([('id', 'child_of', team1.id)])
43.680851
14,371
330
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.tests import common class TestAttributes(common.TransactionCase): def test_we_cannot_add_attributes(self): Model = self.env['test_new_api.category'] instance = Model.create({'name': 'Foo'}) with self.assertRaises(AttributeError): instance.unknown = 42
27.5
330
9,114
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.exceptions import UserError, AccessError from odoo.tests import common from odoo.tools import frozendict from odoo import Command class TestCompanyCheck(common.TransactionCase): def setUp(self): super(TestCompanyCheck, self).setUp() self.company_a = self.env['res.company'].create({ 'name': 'Company A' }) self.company_b = self.env['res.company'].create({ 'name': 'Company B' }) self.parent_company_a_id = self.env['test_new_api.model_parent'].create({ 'name': 'M1', 'company_id': self.company_a.id, }) self.parent_company_b_id = self.env['test_new_api.model_parent'].create({ 'name': 'M2', 'company_id': self.company_b.id, }) self.company_c = self.env['res.company'].create({ 'name': 'Company C' }) self.test_user = self.env['res.users'].create({ 'name': 'Test', 'login': 'test', 'company_id': self.company_a.id, 'company_ids': (self.company_a | self.company_c).ids, }) def test_company_check_0(self): """ Check the option _check_company_auto is well set on records""" m1 = self.env['test_new_api.model_child'].create({'company_id': self.company_a.id}) self.assertTrue(m1._check_company_auto) def test_company_check_1(self): """ Check you can create an object if the company are consistent""" self.env['test_new_api.model_child'].create({ 'name': 'M1', 'company_id': self.company_a.id, 'parent_id': self.parent_company_a_id.id, }) def test_company_check_2(self): """ Check you cannot create a record if the company is inconsistent""" with self.assertRaises(UserError): self.env['test_new_api.model_child'].create({ 'name': 'M1', 'company_id': self.company_b.id, 'parent_id': self.parent_company_a_id.id, }) def test_company_check_3(self): """ Check you can create a record with the inconsistent company if there are no check""" self.env['test_new_api.model_child_nocheck'].create({ 'name': 'M1', 'company_id': self.company_b.id, 'parent_id': self.parent_company_a_id.id, }) def test_company_check_4(self): """ Check the company consistency is respected at write. """ child = self.env['test_new_api.model_child'].create({ 'name': 'M1', 'company_id': self.company_a.id, 'parent_id': self.parent_company_a_id.id, }) with self.assertRaises(UserError): child.company_id = self.company_b.id with self.assertRaises(UserError): child.parent_id = self.parent_company_b_id.id child.write({ 'parent_id': self.parent_company_b_id.id, 'company_id': self.company_b.id, }) def test_company_environment(self): """ Check the company context on the environment is verified. """ user = self.test_user.with_user(self.test_user).with_context(allowed_company_ids=[]) # When accessing company/companies, check raises error if unauthorized/unexisting company. with self.assertRaises(AccessError): user.with_context(allowed_company_ids=[self.company_a.id, self.company_b.id, self.company_c.id]).env.companies with self.assertRaises(AccessError): user.with_context(allowed_company_ids=[self.company_b.id]).env.company with self.assertRaises(AccessError): # crap in company context is not allowed. user.with_context(allowed_company_ids=['company_qsdf', 'company564654']).env.companies # In sudo mode, context check is bypassed. companies = (self.company_a | self.company_b) self.assertEqual( user.sudo().with_context(allowed_company_ids=companies.ids).env.companies, companies ) self.assertEqual( user.sudo().with_context( allowed_company_ids=[self.company_b.id, 'abc']).env.company, self.company_b ) """ wrong_env = user.sudo().with_context( allowed_company_ids=[self.company_a.id, self.company_b.id, 'abc']) wrong_env.env.companies.mapped('name') # Wrong SQL query due to wrong company id. """ # Fallbacks when no allowed_company_ids context key self.assertEqual(user.env.company, user.company_id) self.assertEqual(user.env.companies, user.company_ids) def test_with_company(self): """ Check that with_company() works as expected """ user = self.test_user.with_user(self.test_user).with_context(allowed_company_ids=[]) self.assertEqual(user.env.companies, user.company_ids) self.assertEqual(user.with_company(user.env.company).env.company, user.env.company) self.assertEqual( user.with_company(self.company_a).env.company, user.with_company(self.company_a.id).env.company ) # Falsy values shouldn't change current environment, record, or context. for falsy in [False, None, 0, '', self.env['res.company'], []]: no_change = user.with_company(falsy) self.assertEqual(no_change, user) self.assertEqual(no_change.env.context, user.env.context) self.assertEqual(no_change.env, user.env) comp_a_user = user.with_company(user.company_id) comp_a_user2 = user.with_context(allowed_company_ids=user.company_id.ids) # Using with_company(c) or with_context(allowed_company_ids=[c]) # should return the same context # and the same environment (reused if no changes) self.assertEqual(comp_a_user.env, comp_a_user2.env) self.assertEqual(comp_a_user.env.context, comp_a_user2.env.context) # When there were no company in the context, using with_company # restricts both env.company and env.companies. self.assertEqual(comp_a_user.env.company, user.company_id) self.assertEqual(comp_a_user.env.companies, user.company_id) # Reordering allowed_company_ids ctxt key # Ensure with_company reorders the context key content # and by consequent changes env.company comp_c_a_user = comp_a_user.with_company(self.company_c) self.assertEqual(comp_c_a_user.env.company, self.company_c) self.assertEqual(comp_c_a_user.env.companies, self.company_c + self.company_a) self.assertEqual(comp_c_a_user.env.companies[0], self.company_c) self.assertEqual(comp_c_a_user.env.companies[1], self.company_a) self.assertEqual( comp_c_a_user.env.context['allowed_company_ids'], [self.company_c.id, self.company_a.id], ) comp_a_c_user = comp_c_a_user.with_company(self.company_a) self.assertEqual(comp_a_c_user.env.companies[0], self.company_a) self.assertEqual(comp_a_c_user.env.companies[1], self.company_c) self.assertEqual( comp_a_c_user.env.context['allowed_company_ids'], [self.company_a.id, self.company_c.id], ) def test_company_check_no_access(self): """ Test that company_check validates correctly the companies on the different records, even if the use has no access to one of the records, example, a private address set by an onchange """ user = self.env['res.users'].create({ 'name': 'My Classic User', 'login': 'My Classic User', 'groups_id': [Command.set(self.env.ref('base.group_user').ids)], }) with common.Form(self.env['test_new_api.model_private_address_onchange'].with_user(user)) as form: form.name = 'My Classic Name' form.company_id = self.env.user.company_id with self.assertRaises(AccessError): form.address_id.name form.save() def test_company_sticky_with_context(self): context = frozendict({'nothing_to_see_here': True}) companies_1 = frozendict({'allowed_company_ids': [1]}) companies_2 = frozendict({'allowed_company_ids': [2]}) User = self.env['res.users'].with_context(context) self.assertEqual(User.env.context, context) User = User.with_context(**companies_1) self.assertEqual(User.env.context, dict(context, **companies_1)) # 'allowed_company_ids' is replaced if present in keys User = User.with_context(**companies_2) self.assertEqual(User.env.context, dict(context, **companies_2)) # 'allowed_company_ids' is replaced if present in new context User = User.with_context(companies_1) self.assertEqual(User.env.context, companies_1) # 'allowed_company_ids' is sticky User = User.with_context(context) self.assertEqual(User.env.context, dict(context, **companies_1))
41.616438
9,114
51,498
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime from odoo import models, fields, api, _, Command from odoo.exceptions import AccessError, ValidationError class Category(models.Model): _name = 'test_new_api.category' _description = 'Test New API Category' _order = 'name' _parent_store = True _parent_name = 'parent' name = fields.Char(required=True) color = fields.Integer('Color Index') parent = fields.Many2one('test_new_api.category', ondelete='cascade') parent_path = fields.Char(index=True) depth = fields.Integer(compute="_compute_depth") root_categ = fields.Many2one(_name, compute='_compute_root_categ') display_name = fields.Char(compute='_compute_display_name', recursive=True, inverse='_inverse_display_name') dummy = fields.Char(store=False) discussions = fields.Many2many('test_new_api.discussion', 'test_new_api_discussion_category', 'category', 'discussion') _sql_constraints = [ ('positive_color', 'CHECK(color >= 0)', 'The color code must be positive !') ] @api.depends('name', 'parent.display_name') # this definition is recursive def _compute_display_name(self): for cat in self: if cat.parent: cat.display_name = cat.parent.display_name + ' / ' + cat.name else: cat.display_name = cat.name @api.depends('parent') def _compute_root_categ(self): for cat in self: current = cat while current.parent: current = current.parent cat.root_categ = current @api.depends('parent_path') def _compute_depth(self): for cat in self: cat.depth = cat.parent_path.count('/') - 1 def _inverse_display_name(self): for cat in self: names = cat.display_name.split('/') # determine sequence of categories categories = [] for name in names[:-1]: category = self.search([('name', 'ilike', name.strip())]) categories.append(category[0]) categories.append(cat) # assign parents following sequence for parent, child in zip(categories, categories[1:]): if parent and child: child.parent = parent # assign name of last category, and reassign display_name (to normalize it) cat.name = names[-1].strip() def _read(self, fields): # DLE P45: `test_31_prefetch`, # with self.assertRaises(AccessError): # cat1.name if self.search_count([('id', 'in', self._ids), ('name', '=', 'NOACCESS')]): raise AccessError('Sorry') return super(Category, self)._read(fields) class Discussion(models.Model): _name = 'test_new_api.discussion' _description = 'Test New API Discussion' name = fields.Char(string='Title', required=True, help="General description of what this discussion is about.") moderator = fields.Many2one('res.users') categories = fields.Many2many('test_new_api.category', 'test_new_api_discussion_category', 'discussion', 'category') participants = fields.Many2many('res.users', context={'active_test': False}) messages = fields.One2many('test_new_api.message', 'discussion', copy=True) message_concat = fields.Text(string='Message concatenate') important_messages = fields.One2many('test_new_api.message', 'discussion', domain=[('important', '=', True)]) very_important_messages = fields.One2many( 'test_new_api.message', 'discussion', domain=lambda self: self._domain_very_important()) emails = fields.One2many('test_new_api.emailmessage', 'discussion') important_emails = fields.One2many('test_new_api.emailmessage', 'discussion', domain=[('important', '=', True)]) def _domain_very_important(self): """Ensure computed O2M domains work as expected.""" return [("important", "=", True)] @api.onchange('name') def _onchange_name(self): # test onchange modifying one2many field values if self.env.context.get('generate_dummy_message') and self.name == '{generate_dummy_message}': # update body of existings messages and emails for message in self.messages: message.body = 'not last dummy message' for message in self.important_messages: message.body = 'not last dummy message' # add new dummy message message_vals = self.messages._add_missing_default_values({'body': 'dummy message', 'important': True}) self.messages |= self.messages.new(message_vals) self.important_messages |= self.messages.new(message_vals) @api.onchange('moderator') def _onchange_moderator(self): self.participants |= self.moderator @api.onchange('messages') def _onchange_messages(self): self.message_concat = "\n".join(["%s:%s" % (m.name, m.body) for m in self.messages]) class Message(models.Model): _name = 'test_new_api.message' _description = 'Test New API Message' discussion = fields.Many2one('test_new_api.discussion', ondelete='cascade') body = fields.Text() author = fields.Many2one('res.users', default=lambda self: self.env.user) name = fields.Char(string='Title', compute='_compute_name', store=True) display_name = fields.Char(string='Abstract', compute='_compute_display_name') size = fields.Integer(compute='_compute_size', search='_search_size') double_size = fields.Integer(compute='_compute_double_size') discussion_name = fields.Char(related='discussion.name', string="Discussion Name", readonly=False) author_partner = fields.Many2one( 'res.partner', compute='_compute_author_partner', search='_search_author_partner') important = fields.Boolean() label = fields.Char(translate=True) priority = fields.Integer() @api.constrains('author', 'discussion') def _check_author(self): for message in self.with_context(active_test=False): if message.discussion and message.author not in message.discussion.participants: raise ValidationError(_("Author must be among the discussion participants.")) @api.depends('author.name', 'discussion.name') def _compute_name(self): for message in self: message.name = self._context.get('compute_name', "[%s] %s" % (message.discussion.name or '', message.author.name or '')) @api.constrains('name') def _check_name(self): # dummy constraint to check on computed field for message in self: if message.name.startswith("[X]"): raise ValidationError("No way!") @api.depends('author.name', 'discussion.name', 'body') def _compute_display_name(self): for message in self: stuff = "[%s] %s: %s" % (message.author.name, message.discussion.name or '', message.body or '') message.display_name = stuff[:80] @api.depends('body') def _compute_size(self): for message in self: message.size = len(message.body or '') def _search_size(self, operator, value): if operator not in ('=', '!=', '<', '<=', '>', '>=', 'in', 'not in'): return [] # retrieve all the messages that match with a specific SQL query self.flush(['body']) query = """SELECT id FROM "%s" WHERE char_length("body") %s %%s""" % \ (self._table, operator) self.env.cr.execute(query, (value,)) ids = [t[0] for t in self.env.cr.fetchall()] # return domain with an implicit AND return [('id', 'in', ids), (1, '=', 1)] @api.depends('size') def _compute_double_size(self): for message in self: # This illustrates a subtle situation: message.double_size depends # on message.size. When the latter is computed, message.size is # assigned, which would normally invalidate message.double_size. # However, this may not happen while message.double_size is being # computed: the last statement below would fail, because # message.double_size would be undefined. message.double_size = 0 size = message.size message.double_size = message.double_size + size @api.depends('author', 'author.partner_id') def _compute_author_partner(self): for message in self: message.author_partner = message.author.partner_id @api.model def _search_author_partner(self, operator, value): return [('author.partner_id', operator, value)] def write(self, vals): if 'priority' in vals: vals['priority'] = 5 return super().write(vals) class EmailMessage(models.Model): _name = 'test_new_api.emailmessage' _description = 'Test New API Email Message' _inherits = {'test_new_api.message': 'message'} message = fields.Many2one('test_new_api.message', 'Message', required=True, ondelete='cascade') email_to = fields.Char('To') class Multi(models.Model): """ Model for testing multiple onchange methods in cascade that modify a one2many field several times. """ _name = 'test_new_api.multi' _description = 'Test New API Multi' name = fields.Char(related='partner.name', readonly=True) partner = fields.Many2one('res.partner') lines = fields.One2many('test_new_api.multi.line', 'multi') partners = fields.One2many(related='partner.child_ids') tags = fields.Many2many('test_new_api.multi.tag', domain=[('name', 'ilike', 'a')]) @api.onchange('name') def _onchange_name(self): for line in self.lines: line.name = self.name @api.onchange('partner') def _onchange_partner(self): for line in self.lines: line.partner = self.partner class MultiLine(models.Model): _name = 'test_new_api.multi.line' _description = 'Test New API Multi Line' multi = fields.Many2one('test_new_api.multi', ondelete='cascade') name = fields.Char() partner = fields.Many2one(related='multi.partner', store=True) tags = fields.Many2many('test_new_api.multi.tag') class MultiLine2(models.Model): _name = 'test_new_api.multi.line2' _inherit = 'test_new_api.multi.line' _description = 'Test New API Multi Line 2' class MultiTag(models.Model): _name = 'test_new_api.multi.tag' _description = 'Test New API Multi Tag' name = fields.Char() class Edition(models.Model): _name = 'test_new_api.creativework.edition' _description = 'Test New API Creative Work Edition' name = fields.Char() res_id = fields.Integer(required=True) res_model_id = fields.Many2one('ir.model', required=True, ondelete='cascade') res_model = fields.Char(related='res_model_id.model', store=True, readonly=False) class Book(models.Model): _name = 'test_new_api.creativework.book' _description = 'Test New API Creative Work Book' name = fields.Char() editions = fields.One2many( 'test_new_api.creativework.edition', 'res_id', domain=[('res_model', '=', _name)] ) class Movie(models.Model): _name = 'test_new_api.creativework.movie' _description = 'Test New API Creative Work Movie' name = fields.Char() editions = fields.One2many( 'test_new_api.creativework.edition', 'res_id', domain=[('res_model', '=', _name)] ) class MixedModel(models.Model): _name = 'test_new_api.mixed' _description = 'Test New API Mixed' number = fields.Float(digits=(10, 2), default=3.14) number2 = fields.Float(digits='New API Precision') date = fields.Date() moment = fields.Datetime() now = fields.Datetime(compute='_compute_now') lang = fields.Selection(string='Language', selection='_get_lang') reference = fields.Reference(string='Related Document', selection='_reference_models') comment1 = fields.Html(sanitize=False) comment2 = fields.Html(sanitize_attributes=True, strip_classes=False) comment3 = fields.Html(sanitize_attributes=True, strip_classes=True) comment4 = fields.Html(sanitize_attributes=True, strip_style=True) currency_id = fields.Many2one('res.currency', default=lambda self: self.env.ref('base.EUR')) amount = fields.Monetary() def _compute_now(self): # this is a non-stored computed field without dependencies for message in self: message.now = fields.Datetime.now() @api.model def _get_lang(self): return self.env['res.lang'].get_installed() @api.model def _reference_models(self): models = self.env['ir.model'].sudo().search([('state', '!=', 'manual')]) return [(model.model, model.name) for model in models if not model.model.startswith('ir.')] class BoolModel(models.Model): _name = 'domain.bool' _description = 'Boolean Domain' bool_true = fields.Boolean('b1', default=True) bool_false = fields.Boolean('b2', default=False) bool_undefined = fields.Boolean('b3') class Foo(models.Model): _name = 'test_new_api.foo' _description = 'Test New API Foo' name = fields.Char() value1 = fields.Integer(change_default=True) value2 = fields.Integer() text = fields.Char(trim=False) class Bar(models.Model): _name = 'test_new_api.bar' _description = 'Test New API Bar' name = fields.Char() foo = fields.Many2one('test_new_api.foo', compute='_compute_foo', search='_search_foo') value1 = fields.Integer(related='foo.value1', readonly=False) value2 = fields.Integer(related='foo.value2', readonly=False) text1 = fields.Char('Text1', related='foo.text', readonly=False) text2 = fields.Char('Text2', related='foo.text', readonly=False, trim=True) @api.depends('name') def _compute_foo(self): for bar in self: bar.foo = self.env['test_new_api.foo'].search([('name', '=', bar.name)], limit=1) def _search_foo(self, operator, value): assert operator == 'in' records = self.env['test_new_api.foo'].browse(value) return [('name', 'in', records.mapped('name'))] class Related(models.Model): _name = 'test_new_api.related' _description = 'Test New API Related' name = fields.Char() # related fields with a single field related_name = fields.Char(related='name', string='A related on Name', readonly=False) related_related_name = fields.Char(related='related_name', string='A related on a related on Name', readonly=False) message = fields.Many2one('test_new_api.message') message_name = fields.Text(related="message.body", related_sudo=False, string='Message Body') message_currency = fields.Many2one(related="message.author", string='Message Author') class ComputeReadonly(models.Model): _name = 'test_new_api.compute.readonly' _description = 'Model with a computed readonly field' foo = fields.Char(default='') bar = fields.Char(compute='_compute_bar', store=True) @api.depends('foo') def _compute_bar(self): for record in self: record.bar = record.foo class ComputeInverse(models.Model): _name = 'test_new_api.compute.inverse' _description = 'Model with a computed inversed field' foo = fields.Char() bar = fields.Char(compute='_compute_bar', inverse='_inverse_bar', store=True) baz = fields.Char() @api.depends('foo') def _compute_bar(self): self._context.get('log', []).append('compute') for record in self: record.bar = record.foo def _inverse_bar(self): self._context.get('log', []).append('inverse') for record in self: record.foo = record.bar @api.constrains('bar', 'baz') def _check_constraint(self): if self._context.get('log_constraint'): self._context.get('log', []).append('constraint') class MultiComputeInverse(models.Model): """ Model with the same inverse method for several fields. """ _name = 'test_new_api.multi_compute_inverse' _description = 'Test New API Multi Compute Inverse' foo = fields.Char(default='', required=True) bar1 = fields.Char(compute='_compute_bars', inverse='_inverse_bar1', store=True) bar2 = fields.Char(compute='_compute_bars', inverse='_inverse_bar23', store=True) bar3 = fields.Char(compute='_compute_bars', inverse='_inverse_bar23', store=True) @api.depends('foo') def _compute_bars(self): self._context.get('log', []).append('compute') for record in self: substrs = record.foo.split('/') + ['', '', ''] record.bar1, record.bar2, record.bar3 = substrs[:3] def _inverse_bar1(self): self._context.get('log', []).append('inverse1') for record in self: record.write({'foo': '/'.join([record.bar1, record.bar2, record.bar3])}) def _inverse_bar23(self): self._context.get('log', []).append('inverse23') for record in self: record.write({'foo': '/'.join([record.bar1, record.bar2, record.bar3])}) class Move(models.Model): _name = 'test_new_api.move' _description = 'Move' line_ids = fields.One2many('test_new_api.move_line', 'move_id', domain=[('visible', '=', True)]) quantity = fields.Integer(compute='_compute_quantity', store=True) tag_id = fields.Many2one('test_new_api.multi.tag') tag_name = fields.Char(related='tag_id.name') tag_repeat = fields.Integer() tag_string = fields.Char(compute='_compute_tag_string') # This field can fool the ORM during onchanges! When editing a payment # record, modified fields are assigned to the parent record. When # determining the dependent records, the ORM looks for the payments related # to this record by the field `move_id`. As this field is an inverse of # `move_id`, it uses it. If that field was not initialized properly, the # ORM determines its value to be... empty (instead of the payment record.) payment_ids = fields.One2many('test_new_api.payment', 'move_id') @api.depends('line_ids.quantity') def _compute_quantity(self): for record in self: record.quantity = sum(line.quantity for line in record.line_ids) @api.depends('tag_name', 'tag_repeat') def _compute_tag_string(self): for record in self: record.tag_string = (record.tag_name or "") * record.tag_repeat class MoveLine(models.Model): _name = 'test_new_api.move_line' _description = 'Move Line' move_id = fields.Many2one('test_new_api.move', required=True, ondelete='cascade') visible = fields.Boolean(default=True) quantity = fields.Integer() class Payment(models.Model): _name = 'test_new_api.payment' _description = 'Payment inherits from Move' _inherits = {'test_new_api.move': 'move_id'} move_id = fields.Many2one('test_new_api.move', required=True, ondelete='cascade') class Order(models.Model): _name = _description = 'test_new_api.order' line_ids = fields.One2many('test_new_api.order.line', 'order_id') class OrderLine(models.Model): _name = _description = 'test_new_api.order.line' order_id = fields.Many2one('test_new_api.order', required=True, ondelete='cascade') product = fields.Char() reward = fields.Boolean() def unlink(self): # also delete associated reward lines reward_lines = [ other_line for line in self if not line.reward for other_line in line.order_id.line_ids if other_line.reward and other_line.product == line.product ] self = self.union(*reward_lines) return super().unlink() class CompanyDependent(models.Model): _name = 'test_new_api.company' _description = 'Test New API Company' foo = fields.Char(company_dependent=True) date = fields.Date(company_dependent=True) moment = fields.Datetime(company_dependent=True) tag_id = fields.Many2one('test_new_api.multi.tag', company_dependent=True) truth = fields.Boolean(company_dependent=True) count = fields.Integer(company_dependent=True) phi = fields.Float(company_dependent=True, digits=(2, 5)) class CompanyDependentAttribute(models.Model): _name = 'test_new_api.company.attr' _description = 'Test New API Company Attribute' company = fields.Many2one('test_new_api.company') quantity = fields.Integer() bar = fields.Char(compute='_compute_bar', store=True) @api.depends('quantity', 'company.foo') def _compute_bar(self): for record in self: record.bar = (record.company.foo or '') * record.quantity class ComputeRecursive(models.Model): _name = 'test_new_api.recursive' _description = 'Test New API Recursive' name = fields.Char(required=True) parent = fields.Many2one('test_new_api.recursive', ondelete='cascade') full_name = fields.Char(compute='_compute_full_name', recursive=True) display_name = fields.Char(compute='_compute_display_name', recursive=True, store=True) @api.depends('name', 'parent.full_name') def _compute_full_name(self): for rec in self: if rec.parent: rec.full_name = rec.parent.full_name + " / " + rec.name else: rec.full_name = rec.name @api.depends('name', 'parent.display_name') def _compute_display_name(self): for rec in self: if rec.parent: rec.display_name = rec.parent.display_name + " / " + rec.name else: rec.display_name = rec.name class ComputeRecursiveTree(models.Model): _name = 'test_new_api.recursive.tree' _description = 'Test New API Recursive with one2many field' name = fields.Char(required=True) parent_id = fields.Many2one('test_new_api.recursive.tree', ondelete='cascade') children_ids = fields.One2many('test_new_api.recursive.tree', 'parent_id') display_name = fields.Char(compute='_compute_display_name', recursive=True, store=True) @api.depends('name', 'children_ids.display_name') def _compute_display_name(self): for rec in self: children_names = rec.mapped('children_ids.display_name') rec.display_name = '%s(%s)' % (rec.name, ', '.join(children_names)) class ComputeCascade(models.Model): _name = 'test_new_api.cascade' _description = 'Test New API Cascade' foo = fields.Char() bar = fields.Char(compute='_compute_bar') # depends on foo baz = fields.Char(compute='_compute_baz', store=True) # depends on bar @api.depends('foo') def _compute_bar(self): for record in self: record.bar = "[%s]" % (record.foo or "") @api.depends('bar') def _compute_baz(self): for record in self: record.baz = "<%s>" % (record.bar or "") class ComputeReadWrite(models.Model): _name = 'test_new_api.compute.readwrite' _description = 'Model with a computed non-readonly field' foo = fields.Char() bar = fields.Char(compute='_compute_bar', store=True, readonly=False) @api.depends('foo') def _compute_bar(self): for record in self: record.bar = record.foo class ComputeOnchange(models.Model): _name = 'test_new_api.compute.onchange' _description = "Compute method as an onchange" active = fields.Boolean() foo = fields.Char() bar = fields.Char(compute='_compute_bar', store=True) baz = fields.Char(compute='_compute_baz', store=True, readonly=False) count = fields.Integer(default=0) line_ids = fields.One2many( 'test_new_api.compute.onchange.line', 'record_id', compute='_compute_line_ids', store=True, readonly=False ) tag_ids = fields.Many2many( 'test_new_api.multi.tag', compute='_compute_tag_ids', store=True, readonly=False, ) @api.onchange('foo') def _onchange_foo(self): self.count += 1 @api.depends('foo') def _compute_bar(self): for record in self: record.bar = (record.foo or "") + "r" @api.depends('active', 'foo') def _compute_baz(self): for record in self: if record.active: record.baz = (record.foo or "") + "z" @api.depends('foo') def _compute_line_ids(self): for record in self: if not record.foo: continue if any(line.foo == record.foo for line in record.line_ids): continue # add a line with the same value as 'foo' record.line_ids = [Command.create({'foo': record.foo})] @api.depends('foo') def _compute_tag_ids(self): Tag = self.env['test_new_api.multi.tag'] for record in self: if record.foo: record.tag_ids = Tag.search([('name', '=', record.foo)]) def copy(self, default=None): default = dict(default or {}, foo="%s (copy)" % (self.foo or "")) return super().copy(default) class ComputeOnchangeLine(models.Model): _name = 'test_new_api.compute.onchange.line' _description = "Line-like model for test_new_api.compute.onchange" record_id = fields.Many2one('test_new_api.compute.onchange', ondelete='cascade') foo = fields.Char() bar = fields.Char(compute='_compute_bar') @api.depends('foo') def _compute_bar(self): for line in self: line.bar = (line.foo or "") + "r" class ComputeDynamicDepends(models.Model): _name = 'test_new_api.compute.dynamic.depends' _description = "Computed field with dynamic dependencies" name1 = fields.Char() name2 = fields.Char() name3 = fields.Char() full_name = fields.Char(compute='_compute_full_name') def _get_full_name_fields(self): # the fields to use are stored in a config parameter depends = self.env['ir.config_parameter'].get_param('test_new_api.full_name', '') return depends.split(',') if depends else [] @api.depends(lambda self: self._get_full_name_fields()) def _compute_full_name(self): fnames = self._get_full_name_fields() for record in self: record.full_name = ", ".join(filter(None, (record[fname] for fname in fnames))) class ComputeUnassigned(models.Model): _name = 'test_new_api.compute.unassigned' _description = "Model with computed fields left unassigned" foo = fields.Char() bar = fields.Char(compute='_compute_bar') bare = fields.Char(compute='_compute_bare', readonly=False) bars = fields.Char(compute='_compute_bars', store=True) bares = fields.Char(compute='_compute_bares', readonly=False, store=True) @api.depends('foo') def _compute_bar(self): for record in self: if record.foo == "assign": record.bar = record.foo @api.depends('foo') def _compute_bare(self): for record in self: if record.foo == "assign": record.bare = record.foo @api.depends('foo') def _compute_bars(self): for record in self: if record.foo == "assign": record.bars = record.foo @api.depends('foo') def _compute_bares(self): for record in self: if record.foo == "assign": record.bares = record.foo class ComputeOne2many(models.Model): _name = 'test_new_api.one2many' _description = "A computed editable one2many field with a domain" name = fields.Char() line_ids = fields.One2many( 'test_new_api.one2many.line', 'container_id', compute='_compute_line_ids', store=True, readonly=False, domain=[('count', '>', 0)], ) @api.depends('name') def _compute_line_ids(self): # increment counter of line with the same name, or create a new line for record in self: if not record.name: continue for line in record.line_ids: if line.name == record.name: line.count += 1 break else: record.line_ids = [(0, 0, {'name': record.name})] class ComputeOne2manyLine(models.Model): _name = 'test_new_api.one2many.line' _description = "Line of a computed one2many" name = fields.Char() count = fields.Integer(default=1) container_id = fields.Many2one('test_new_api.one2many', required=True) class ModelBinary(models.Model): _name = 'test_new_api.model_binary' _description = 'Test Image field' binary = fields.Binary() binary_related_store = fields.Binary("Binary Related Store", related='binary', store=True, readonly=False) binary_related_no_store = fields.Binary("Binary Related No Store", related='binary', store=False, readonly=False) binary_computed = fields.Binary(compute='_compute_binary') @api.depends('binary') def _compute_binary(self): # arbitrary value: 'bin_size' must have no effect for record in self: record.binary_computed = [(record.id, bool(record.binary))] class ModelImage(models.Model): _name = 'test_new_api.model_image' _description = 'Test Image field' name = fields.Char(required=True) image = fields.Image() image_512 = fields.Image("Image 512", related='image', max_width=512, max_height=512, store=True, readonly=False) image_256 = fields.Image("Image 256", related='image', max_width=256, max_height=256, store=False, readonly=False) image_128 = fields.Image("Image 128", max_width=128, max_height=128) class BinarySvg(models.Model): _name = 'test_new_api.binary_svg' _description = 'Test SVG upload' name = fields.Char(required=True) image_attachment = fields.Binary(attachment=True) image_wo_attachment = fields.Binary(attachment=False) class MonetaryBase(models.Model): _name = 'test_new_api.monetary_base' _description = 'Monetary Base' base_currency_id = fields.Many2one('res.currency') amount = fields.Monetary(currency_field='base_currency_id') class MonetaryRelated(models.Model): _name = 'test_new_api.monetary_related' _description = 'Monetary Related' monetary_id = fields.Many2one('test_new_api.monetary_base') currency_id = fields.Many2one('res.currency', related='monetary_id.base_currency_id') amount = fields.Monetary(related='monetary_id.amount') total = fields.Monetary() class MonetaryCustom(models.Model): _name = 'test_new_api.monetary_custom' _description = 'Monetary Related Custom' monetary_id = fields.Many2one('test_new_api.monetary_base') x_currency_id = fields.Many2one('res.currency', related='monetary_id.base_currency_id') x_amount = fields.Monetary(related='monetary_id.amount') class MonetaryInherits(models.Model): _name = 'test_new_api.monetary_inherits' _description = 'Monetary Inherits' _inherits = {'test_new_api.monetary_base': 'monetary_id'} monetary_id = fields.Many2one('test_new_api.monetary_base', required=True, ondelete='cascade') currency_id = fields.Many2one('res.currency') class MonetaryOrder(models.Model): _name = 'test_new_api.monetary_order' _description = 'Sales Order' currency_id = fields.Many2one('res.currency') line_ids = fields.One2many('test_new_api.monetary_order_line', 'order_id') total = fields.Monetary(compute='_compute_total', store=True) @api.depends('line_ids.subtotal') def _compute_total(self): for record in self: record.total = sum(line.subtotal for line in record.line_ids) class MonetaryOrderLine(models.Model): _name = 'test_new_api.monetary_order_line' _description = 'Sales Order Line' order_id = fields.Many2one('test_new_api.monetary_order', required=True, ondelete='cascade') subtotal = fields.Float(digits=(10, 2)) class FieldWithCaps(models.Model): _name = 'test_new_api.field_with_caps' _description = 'Model with field defined with capital letters' pArTneR_321_id = fields.Many2one('res.partner') class Selection(models.Model): _name = 'test_new_api.selection' _description = "Selection" state = fields.Selection([('foo', 'Foo'), ('bar', 'Bar')]) other = fields.Selection([('foo', 'Foo'), ('bar', 'Bar')]) class RequiredM2O(models.Model): _name = 'test_new_api.req_m2o' _description = 'Required Many2one' foo = fields.Many2one('res.currency', required=True, ondelete='cascade') bar = fields.Many2one('res.country', required=True) class RequiredM2OTransient(models.TransientModel): _name = 'test_new_api.req_m2o_transient' _description = 'Transient Model with Required Many2one' foo = fields.Many2one('res.currency', required=True, ondelete='restrict') bar = fields.Many2one('res.country', required=True) class Attachment(models.Model): _name = 'test_new_api.attachment' _description = 'Attachment' res_model = fields.Char(required=True) res_id = fields.Integer(required=True) name = fields.Char(compute='_compute_name', compute_sudo=True, store=True) @api.depends('res_model', 'res_id') def _compute_name(self): for rec in self: rec.name = self.env[rec.res_model].browse(rec.res_id).display_name # DLE P55: `test_cache_invalidation` def modified(self, fnames, *args, **kwargs): if not self: return comodel = self.env[self.res_model] if 'res_id' in fnames and 'attachment_ids' in comodel: field = comodel._fields['attachment_ids'] record = comodel.browse(self.res_id) self.env.cache.invalidate([(field, record._ids)]) record.modified(['attachment_ids']) return super(Attachment, self).modified(fnames, *args, **kwargs) class AttachmentHost(models.Model): _name = 'test_new_api.attachment.host' _description = 'Attachment Host' attachment_ids = fields.One2many( 'test_new_api.attachment', 'res_id', auto_join=True, domain=lambda self: [('res_model', '=', self._name)], ) class DecimalPrecisionTestModel(models.Model): _name = 'decimal.precision.test' _description = 'Decimal Precision Test' float = fields.Float() float_2 = fields.Float(digits=(16, 2)) float_4 = fields.Float(digits=(16, 4)) class ModelA(models.Model): _name = 'test_new_api.model_a' _description = 'Model A' name = fields.Char() a_restricted_b_ids = fields.Many2many('test_new_api.model_b', relation='rel_model_a_model_b_1') b_restricted_b_ids = fields.Many2many('test_new_api.model_b', relation='rel_model_a_model_b_2', ondelete='restrict') class ModelB(models.Model): _name = 'test_new_api.model_b' _description = 'Model B' name = fields.Char() a_restricted_a_ids = fields.Many2many('test_new_api.model_a', relation='rel_model_a_model_b_1', ondelete='restrict') b_restricted_a_ids = fields.Many2many('test_new_api.model_a', relation='rel_model_a_model_b_2') class ModelParent(models.Model): _name = 'test_new_api.model_parent' _description = 'Model Multicompany parent' name = fields.Char() company_id = fields.Many2one('res.company', required=True) class ModelChild(models.Model): _name = 'test_new_api.model_child' _description = 'Model Multicompany child' _check_company_auto = True name = fields.Char() company_id = fields.Many2one('res.company', required=True) parent_id = fields.Many2one('test_new_api.model_parent', check_company=True) class ModelChildNoCheck(models.Model): _name = 'test_new_api.model_child_nocheck' _description = 'Model Multicompany child' _check_company_auto = True name = fields.Char() company_id = fields.Many2one('res.company', required=True) parent_id = fields.Many2one('test_new_api.model_parent', check_company=False) class ModelPrivateAddressOnchange(models.Model): _name = 'test_new_api.model_private_address_onchange' _description = 'Model Private Address Onchange' _check_company_auto = True name = fields.Char() company_id = fields.Many2one('res.company', required=True) address_id = fields.Many2one('res.partner', check_company=True) @api.onchange('name') def _onchange_name(self): if self.name and not self.address_id: self.address_id = self.env['res.partner'].sudo().create({ 'name': self.name, 'type': 'private', }) # model with explicit and stored field 'display_name' class Display(models.Model): _name = 'test_new_api.display' _description = 'Model that overrides display_name' display_name = fields.Char(compute='_compute_display_name', store=True) def _compute_display_name(self): for record in self: record.display_name = 'My id is %s' % (record.id) # abstract model with automatic and non-stored field 'display_name' class Mixin(models.AbstractModel): _name = 'test_new_api.mixin' _description = 'Dummy mixin model' # in this model extension, the field 'display_name' should not be inherited from # 'test_new_api.mixin' class ExtendedDisplay(models.Model): _name = 'test_new_api.display' _inherit = ['test_new_api.mixin', 'test_new_api.display'] class ModelActiveField(models.Model): _name = 'test_new_api.model_active_field' _description = 'A model with active field' name = fields.Char() active = fields.Boolean(default=True) parent_id = fields.Many2one('test_new_api.model_active_field') children_ids = fields.One2many('test_new_api.model_active_field', 'parent_id') all_children_ids = fields.One2many('test_new_api.model_active_field', 'parent_id', context={'active_test': False}) active_children_ids = fields.One2many('test_new_api.model_active_field', 'parent_id', context={'active_test': True}) parent_active = fields.Boolean(string='Active Parent', related='parent_id.active', store=True) class ModelMany2oneReference(models.Model): _name = 'test_new_api.model_many2one_reference' _description = 'dummy m2oref model' res_model = fields.Char('Resource Model') res_id = fields.Many2oneReference('Resource ID', model_field='res_model') class InverseM2oRef(models.Model): _name = 'test_new_api.inverse_m2o_ref' _description = 'dummy m2oref inverse model' model_ids = fields.One2many('test_new_api.model_many2one_reference', 'res_id', string="Models") model_ids_count = fields.Integer("Count", compute='_compute_model_ids_count') @api.depends('model_ids') def _compute_model_ids_count(self): for rec in self: rec.model_ids_count = len(rec.model_ids) class ModelChildM2o(models.Model): _name = 'test_new_api.model_child_m2o' _description = 'dummy model with override write and ValidationError' name = fields.Char('Name') parent_id = fields.Many2one('test_new_api.model_parent_m2o', ondelete='cascade') size1 = fields.Integer(compute='_compute_sizes', store=True) size2 = fields.Integer(compute='_compute_sizes', store=True) cost = fields.Integer(compute='_compute_cost', store=True, readonly=False) @api.depends('parent_id.name') def _compute_sizes(self): for record in self: record.size1 = len(self.parent_id.name) record.size2 = len(self.parent_id.name) @api.depends('name') def _compute_cost(self): for record in self: record.cost = len(record.name) def write(self, vals): res = super(ModelChildM2o, self).write(vals) if self.name == 'A': raise ValidationError('the first existing child should not be changed when adding a new child to the parent') return res class ModelParentM2o(models.Model): _name = 'test_new_api.model_parent_m2o' _description = 'dummy model with multiple childs' name = fields.Char('Name') child_ids = fields.One2many('test_new_api.model_child_m2o', 'parent_id', string="Children") cost = fields.Integer(compute='_compute_cost', store=True) @api.depends('child_ids.cost') def _compute_cost(self): for record in self: record.cost = sum(child.cost for child in record.child_ids) class Country(models.Model): _name = 'test_new_api.country' _description = 'Country, ordered by name' _order = 'name, id' name = fields.Char() class City(models.Model): _name = 'test_new_api.city' _description = 'City, ordered by country then name' _order = 'country_id, name, id' name = fields.Char() country_id = fields.Many2one('test_new_api.country') # abstract model with a selection field class StateMixin(models.AbstractModel): _name = 'test_new_api.state_mixin' _description = 'Dummy state mixin model' state = fields.Selection([ ('draft', 'Draft'), ('confirmed', 'Confirmed'), ('done', 'Done'), ]) class SelectionBase(models.Model): _name = 'test_new_api.model_selection_base' _description = "Model with a base selection field" my_selection = fields.Selection([ ('foo', "Foo"), ('bar', "Bar"), ]) class SelectionBaseNullExplicit(models.Model): _inherit = 'test_new_api.model_selection_base' _description = "Model with a selection field extension with ondelete null" my_selection = fields.Selection(selection_add=[ ('quux', "Quux"), ], ondelete={'quux': 'set null'}) class SelectionBaseNullImplicit(models.Model): _inherit = 'test_new_api.model_selection_base' _description = "Model with a selection field extension without ondelete" my_selection = fields.Selection(selection_add=[ ('ham', "Ham"), ]) class SelectionRequired(models.Model): _name = 'test_new_api.model_selection_required' _description = "Model with a required selection field" active = fields.Boolean(default=True) my_selection = fields.Selection([ ('foo', "Foo"), ('bar', "Bar"), ], required=True, default='foo') class SelectionRequiredDefault(models.Model): _inherit = 'test_new_api.model_selection_required' _description = "Model with a selection field extension with ondelete default" my_selection = fields.Selection(selection_add=[ ('baz', "Baz"), ], ondelete={'baz': 'set default'}) class SelectionRequiredCascade(models.Model): _inherit = 'test_new_api.model_selection_required' _description = "Model with a selection field extension with ondelete cascade" my_selection = fields.Selection(selection_add=[ ('eggs', "Eggs"), ], ondelete={'eggs': 'cascade'}) class SelectionRequiredLiteral(models.Model): _inherit = 'test_new_api.model_selection_required' _description = "Model with a selection field extension with ondelete set <option>" my_selection = fields.Selection(selection_add=[ ('bacon', "Bacon"), ], ondelete={'bacon': 'set bar'}) class SelectionRequiredMultiple(models.Model): _inherit = 'test_new_api.model_selection_required' _description = "Model with a selection field extension with multiple ondelete policies" my_selection = fields.Selection(selection_add=[ ('pikachu', "Pikachu"), ('eevee', "Eevee"), ], ondelete={'pikachu': 'set default', 'eevee': lambda r: r.write({'my_selection': 'bar'})}) class SelectionRequiredCallback(models.Model): _inherit = 'test_new_api.model_selection_required' _description = "Model with a selection field extension with ondelete callback" my_selection = fields.Selection(selection_add=[ ('knickers', "Oh la la"), ], ondelete={ 'knickers': lambda recs: recs.write({'active': False, 'my_selection': 'foo'}), }) class SelectionNonStored(models.Model): _name = 'test_new_api.model_selection_non_stored' _description = "Model with non-stored selection field" my_selection = fields.Selection([ ('foo', "Foo"), ('bar', "Bar"), ], store=False) class SelectionRequiredForWriteOverride(models.Model): _name = 'test_new_api.model_selection_required_for_write_override' _description = "Model with required selection field for an extension with write override" my_selection = fields.Selection([ ('foo', "Foo"), ('bar', "Bar"), ], required=True, default='foo') class SelectionRequiredWithWriteOverride(models.Model): _inherit = 'test_new_api.model_selection_required_for_write_override' my_selection = fields.Selection(selection_add=[ ('divinity', "Divinity: Original Sin 2"), ], ondelete={'divinity': 'set default'}) def write(self, vals): if 'my_selection' in vals: raise ValueError("No... no no no") return super().write(vals) # Special classes to ensure the correct usage of a shared cache amongst users. # See the method test_shared_cache_computed_field class SharedCacheComputeParent(models.Model): _name = 'test_new_api.model_shared_cache_compute_parent' _description = 'model_shared_cache_compute_parent' name = fields.Char(string="Task Name") line_ids = fields.One2many( 'test_new_api.model_shared_cache_compute_line', 'parent_id', string="Timesheets") total_amount = fields.Integer(compute='_compute_total_amount', store=True, compute_sudo=True) @api.depends('line_ids.amount') def _compute_total_amount(self): for parent in self: parent.total_amount = sum(parent.line_ids.mapped('amount')) class ShareCacheComputeLine(models.Model): _name = 'test_new_api.model_shared_cache_compute_line' _description = 'model_shared_cache_compute_line' parent_id = fields.Many2one('test_new_api.model_shared_cache_compute_parent') amount = fields.Integer() user_id = fields.Many2one('res.users', default= lambda self: self.env.user) # Note: There is an ir.rule about this. class ComputeContainer(models.Model): _name = _description = 'test_new_api.compute.container' name = fields.Char() member_ids = fields.One2many('test_new_api.compute.member', 'container_id') class ComputeMember(models.Model): _name = _description = 'test_new_api.compute.member' name = fields.Char() container_id = fields.Many2one('test_new_api.compute.container', compute='_compute_container', store=True) @api.depends('name') def _compute_container(self): container = self.env['test_new_api.compute.container'] for member in self: member.container_id = container.search([('name', '=', member.name)], limit=1) class ComputeEditable(models.Model): _name = _description = 'test_new_api.compute_editable' line_ids = fields.One2many('test_new_api.compute_editable.line', 'parent_id') @api.onchange('line_ids') def _onchange_line_ids(self): for line in self.line_ids: # even if 'same' is not in the view, it should be the same as 'value' line.count += line.same class ComputeEditableLine(models.Model): _name = _description = 'test_new_api.compute_editable.line' parent_id = fields.Many2one('test_new_api.compute_editable') value = fields.Integer() same = fields.Integer(compute='_compute_same', store=True) edit = fields.Integer(compute='_compute_edit', store=True, readonly=False) count = fields.Integer() @api.depends('value') def _compute_same(self): for line in self: line.same = line.value @api.depends('value') def _compute_edit(self): for line in self: line.edit = line.value class ConstrainedUnlinks(models.Model): _name = 'test_new_api.model_constrained_unlinks' _description = 'Model with unlink override that is constrained' foo = fields.Char() bar = fields.Integer() @api.ondelete(at_uninstall=False) def _unlink_except_bar_gt_five(self): for rec in self: if rec.bar and rec.bar > 5: raise ValueError("Nooooooooo bar can't be greater than five!!") @api.ondelete(at_uninstall=True) def _unlink_except_prosciutto(self): for rec in self: if rec.foo and rec.foo == 'prosciutto': raise ValueError("You didn't say if you wanted it crudo or cotto...") class TriggerLeft(models.Model): _name = 'test_new_api.trigger.left' _description = 'model with a related many2one' middle_ids = fields.One2many('test_new_api.trigger.middle', 'left_id') right_id = fields.Many2one(related='middle_ids.right_id', store=True) class TriggerMiddle(models.Model): _name = 'test_new_api.trigger.middle' _description = 'model linking test_new_api.trigger.left and test_new_api.trigger.right' left_id = fields.Many2one('test_new_api.trigger.left', required=True) right_id = fields.Many2one('test_new_api.trigger.right', required=True) class TriggerRight(models.Model): _name = 'test_new_api.trigger.right' _description = 'model with a dependency on the inverse of the related many2one' left_ids = fields.One2many('test_new_api.trigger.left', 'right_id') left_size = fields.Integer(compute='_compute_left_size', store=True) @api.depends('left_ids') def _compute_left_size(self): for record in self: record.left_size = len(record.left_ids) class Crew(models.Model): _name = 'test_new_api.crew' _description = 'All yaaaaaarrrrr by ship' _table = 'test_new_api_crew' # this actually represents the union of two relations pirate/ship and # prisoner/ship, where some of the many2one fields can be NULL pirate_id = fields.Many2one('test_new_api.pirate') prisoner_id = fields.Many2one('test_new_api.prisoner') ship_id = fields.Many2one('test_new_api.ship') class Ship(models.Model): _name = 'test_new_api.ship' _description = 'Yaaaarrr machine' name = fields.Char('Name') pirate_ids = fields.Many2many('test_new_api.pirate', 'test_new_api_crew', 'ship_id', 'pirate_id') prisoner_ids = fields.Many2many('test_new_api.prisoner', 'test_new_api_crew', 'ship_id', 'prisoner_id') class Pirate(models.Model): _name = 'test_new_api.pirate' _description = 'Yaaarrr' name = fields.Char('Name') ship_ids = fields.Many2many('test_new_api.ship', 'test_new_api_crew', 'pirate_id', 'ship_id') class Prisoner(models.Model): _name = 'test_new_api.prisoner' _description = 'Yaaarrr minions' name = fields.Char('Name') ship_ids = fields.Many2many('test_new_api.ship', 'test_new_api_crew', 'prisoner_id', 'ship_id') class Team(models.Model): _name = 'test_new_api.team' _description = 'Odoo Team' name = fields.Char() parent_id = fields.Many2one('test_new_api.team') member_ids = fields.One2many('test_new_api.team.member', 'team_id') class TeamMember(models.Model): _name = 'test_new_api.team.member' _description = 'Odoo Developer' name = fields.Char('Name') team_id = fields.Many2one('test_new_api.team') parent_id = fields.Many2one('test_new_api.team', related='team_id.parent_id')
35.34523
51,498
6,189
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models def selection_fn(model): return [(str(key), val) for key, val in enumerate(["Corge", "Grault", "Wheee", "Moog"])] def compute_fn(records): for record in records: record.value = 3 def inverse_fn(records): pass MODELS = [ ('boolean', fields.Boolean()), ('integer', fields.Integer()), ('float', fields.Float()), ('decimal', fields.Float(digits=(16, 3))), ('string.bounded', fields.Char(size=16)), ('string.required', fields.Char(size=None, required=True)), ('string', fields.Char(size=None)), ('date', fields.Date()), ('datetime', fields.Datetime()), ('text', fields.Text()), ('selection', fields.Selection([('1', "Foo"), ('2', "Bar"), ('3', "Qux"), ('4', '')])), ('selection.function', fields.Selection(selection_fn)), # just relate to an integer ('many2one', fields.Many2one('export.integer')), ('one2many', fields.One2many('export.one2many.child', 'parent_id')), ('many2many', fields.Many2many('export.many2many.other')), ('function', fields.Integer(compute=compute_fn, inverse=inverse_fn)), # related: specialization of fields.function, should work the same way # TODO: reference ] for name, field in MODELS: class NewModel(models.Model): _name = 'export.%s' % name _description = 'Export: %s' % name _rec_name = 'value' const = fields.Integer(default=4) value = field def name_get(self): return [(record.id, "%s:%s" % (self._name, record.value)) for record in self] @api.model def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None): if isinstance(name, str) and name.split(':')[0] == self._name: return self._search([('value', operator, int(name.split(':')[1]))], access_rights_uid=name_get_uid) else: return [] class One2ManyChild(models.Model): _name = 'export.one2many.child' _description = 'Export One to Many Child' # FIXME: orm.py:1161, fix to name_get on m2o field _rec_name = 'value' parent_id = fields.Many2one('export.one2many') str = fields.Char() m2o = fields.Many2one('export.integer') value = fields.Integer() def name_get(self): return [(record.id, "%s:%s" % (self._name, record.value)) for record in self] @api.model def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None): if isinstance(name, str) and name.split(':')[0] == self._name: return self._search([('value', operator, int(name.split(':')[1]))], access_rights_uid=name_get_uid) else: return [] class One2ManyMultiple(models.Model): _name = 'export.one2many.multiple' _description = 'Export One To Many Multiple' _rec_name = 'parent_id' parent_id = fields.Many2one('export.one2many.recursive') const = fields.Integer(default=36) child1 = fields.One2many('export.one2many.child.1', 'parent_id') child2 = fields.One2many('export.one2many.child.2', 'parent_id') class One2ManyChildMultiple(models.Model): _name = 'export.one2many.multiple.child' # FIXME: orm.py:1161, fix to name_get on m2o field _rec_name = 'value' _description = 'Export One To Many Multiple Child' parent_id = fields.Many2one('export.one2many.multiple') str = fields.Char() value = fields.Integer() def name_get(self): return [(record.id, "%s:%s" % (self._name, record.value)) for record in self] class One2ManyChild1(models.Model): _name = 'export.one2many.child.1' _inherit = 'export.one2many.multiple.child' _description = 'Export One to Many Child 1' class One2ManyChild2(models.Model): _name = 'export.one2many.child.2' _inherit = 'export.one2many.multiple.child' _description = 'Export One To Many Child 2' class Many2ManyChild(models.Model): _name = 'export.many2many.other' _description = 'Export Many to Many Other' # FIXME: orm.py:1161, fix to name_get on m2o field _rec_name = 'value' str = fields.Char() value = fields.Integer() def name_get(self): return [(record.id, "%s:%s" % (self._name, record.value)) for record in self] @api.model def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None): if isinstance(name, str) and name.split(':')[0] == self._name: return self._search([('value', operator, int(name.split(':')[1]))], access_rights_uid=name_get_uid) else: return [] class SelectionWithDefault(models.Model): _name = 'export.selection.withdefault' _description = 'Export Selection With Default' const = fields.Integer(default=4) value = fields.Selection([('1', "Foo"), ('2', "Bar")], default='2') class RecO2M(models.Model): _name = 'export.one2many.recursive' _description = 'Export One To Many Recursive' _rec_name = 'value' value = fields.Integer() child = fields.One2many('export.one2many.multiple', 'parent_id') class OnlyOne(models.Model): _name = 'export.unique' _description = 'Export Unique' value = fields.Integer() value2 = fields.Integer() value3 = fields.Integer() _sql_constraints = [ ('value_unique', 'unique (value)', "The value must be unique"), ('pair_unique', 'unique (value2, value3)', "The values must be unique"), ] class InheritsParent(models.Model): _name = _description = 'export.inherits.parent' value_parent = fields.Integer() class InheritsChild(models.Model): _name = _description = 'export.inherits.child' _inherits = {'export.inherits.parent': 'parent_id'} parent_id = fields.Many2one('export.inherits.parent', required=True, ondelete='cascade') value = fields.Integer() class Many2String(models.Model): _name = _description = 'export.m2o.str' child_id = fields.Many2one('export.m2o.str.child') class ChidToString(models.Model): _name = _description = 'export.m2o.str.child' name = fields.Char()
33.274194
6,189
313
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'test-import-export', 'version': '0.1', 'category': 'Hidden/Tests', 'description': """A module to test import/export.""", 'depends': ['base'], 'data': ['ir.model.access.csv'], 'installable': True, 'auto_install': False, 'license': 'LGPL-3', }
26.083333
313
55,404
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import json import pkgutil import re from odoo import fields from odoo.addons.base.tests.common import SavepointCaseWithUserDemo from odoo.tests import common from odoo.tools.misc import mute_logger def message(msg, type='error', from_=0, to_=0, record=0, field='value', **kwargs): return dict(kwargs, type=type, rows={'from': from_, 'to': to_}, record=record, field=field, message=msg) def moreaction(**kwargs): return dict(kwargs, type='ir.actions.act_window', target='new', context={'create': False}, name='Possible Values', view_mode='tree,form', views=[(False, 'list'), (False, 'form')], help=u"See all possible values") def values(seq, field='value'): return [item[field] for item in seq] class ImporterCase(common.TransactionCase): model_name = False def __init__(self, *args, **kwargs): super(ImporterCase, self).__init__(*args, **kwargs) self.model = None def setUp(self): super(ImporterCase, self).setUp() self.model = self.env[self.model_name] self.env['ir.model.data'].clear_caches() self.cr.cache.clear() def import_(self, fields, rows, context=None): context = context or {} context.update({ 'import_file': True }) return self.model.with_context(context or {}).load(fields, rows) def read(self, fields=('value',), domain=(), context=None): records = self.model.with_context(context or {}).search(domain) return records.read(fields) def browse(self, domain=(), context=None): return self.model.with_context(context or {}).search(domain) def xid(self, record): ModelData = self.env['ir.model.data'] data = ModelData.search([('model', '=', record._name), ('res_id', '=', record.id)]) if data: d = data.read(['name', 'module'])[0] if d['module']: return '%s.%s' % (d['module'], d['name']) return d['name'] name = record.display_name # fix dotted name_get results, otherwise xid lookups blow up name = name.replace('.', '-') ModelData.create({ 'name': name, 'model': record._name, 'res_id': record.id, 'module': '__test__' }) return '__test__.' + name def add_translations(self, name, type, code, *tnx): self.env['res.lang']._activate_lang(code) Translations = self.env['ir.translation'] for source, value in tnx: Translations.create({ 'name': name, 'lang': code, 'type': type, 'src': source, 'value': value, 'state': 'translated', }) class test_ids_stuff(ImporterCase): model_name = 'export.integer' def test_create_with_id(self): result = self.import_(['.id', 'value'], [['42', '36']]) self.assertIs(result['ids'], False) self.assertEqual(result['messages'], [{ 'type': 'error', 'rows': {'from': 0, 'to': 0}, 'record': 0, 'field': '.id', 'message': u"Unknown database identifier '42'", }]) def test_create_with_xid(self): result = self.import_(['id', 'value'], [['somexmlid', '42']]) self.assertEqual(len(result['ids']), 1) self.assertFalse(result['messages']) self.assertEqual( '__import__.somexmlid', self.xid(self.browse()[0])) def test_update_with_id(self): record = self.model.create({'value': 36}) self.assertEqual( 36, record.value) result = self.import_(['.id', 'value'], [[str(record.id), '42']]) self.assertEqual(len(result['ids']), 1) self.assertFalse(result['messages']) self.assertEqual( [42], # updated value to imported values(self.read())) def test_update_with_xid(self): self.import_(['id', 'value'], [['somexmlid', '36']]) self.assertEqual([36], values(self.read())) self.import_(['id', 'value'], [['somexmlid', '1234567']]) self.assertEqual([1234567], values(self.read())) class test_boolean_field(ImporterCase): model_name = 'export.boolean' def test_empty(self): self.assertEqual( self.import_(['value'], []), {'ids': [], 'messages': [], 'nextrow': False}) def test_exported(self): result = self.import_(['value'], [['False'], ['True'], ]) self.assertEqual(len(result['ids']), 2) self.assertFalse(result['messages']) records = self.read() self.assertEqual([ False, True, ], values(records)) def test_falses(self): for lang, source, value in [('fr_FR', 'no', u'non'), ('de_DE', 'no', u'nein'), ('ru_RU', 'no', u'нет'), ('nl_BE', 'false', u'vals'), ('lt_LT', 'false', u'klaidingas')]: self.add_translations('test_import.py', 'code', lang, (source, value)) falses = [[u'0'], [u'no'], [u'false'], [u'FALSE'], [u''], [u'non'], # no, fr [u'nein'], # no, de [u'нет'], # no, ru [u'vals'], # false, nl [u'klaidingas'], # false, lt, ] result = self.import_(['value'], falses) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), len(falses)) self.assertEqual([False] * len(falses), values(self.read())) def test_trues(self): # Since importing wrong boolean values is now returning error, import should not return any ids if an error is raised. trues = [['None'], ['nil'], ['()'], ['f'], ['#f'], # Problem: OpenOffice (and probably excel) output localized booleans ['VRAI'], ['ok'], ['true'], ['yes'], ['1'], ] result = self.import_(['value'], trues) self.assertEqual(result['ids'], False) self.assertEqual(result['messages'], [{ 'rows': {'from': i, 'to': i}, 'type': 'error', 'record': i, 'field': 'value', 'message': "Unknown value '%s' for boolean field 'Value'" % v[0], 'moreinfo': "Use '1' for yes and '0' for no", 'field_name': 'Value' } for i, v in enumerate(trues) if v[0] not in ('true', 'yes', '1')]) # Only correct boolean values are accepted. result = self.import_(['value'], [['1'], ['yes'], ['true']]) self.assertEqual(len(result['ids']), 3) self.assertEqual( [True] * 3, values(self.read())) class test_integer_field(ImporterCase): model_name = 'export.integer' def test_none(self): self.assertEqual( self.import_(['value'], []), {'ids': [], 'messages': [], 'nextrow': False}) def test_empty(self): result = self.import_(['value'], [['']]) self.assertEqual(len(result['ids']), 1) self.assertFalse(result['messages']) self.assertEqual( [False], values(self.read())) def test_zero(self): result = self.import_(['value'], [['0']]) self.assertEqual(len(result['ids']), 1) self.assertFalse(result['messages']) result = self.import_(['value'], [['-0']]) self.assertEqual(len(result['ids']), 1) self.assertFalse(result['messages']) self.assertEqual([False, False], values(self.read())) def test_positives(self): result = self.import_(['value'], [ ['1'], ['42'], [str(2**31-1)], ['12345678'] ]) self.assertEqual(len(result['ids']), 4) self.assertFalse(result['messages']) self.assertEqual([ 1, 42, 2**31-1, 12345678 ], values(self.read())) def test_negatives(self): result = self.import_(['value'], [ ['-1'], ['-42'], [str(-(2**31 - 1))], [str(-(2**31))], ['-12345678'] ]) self.assertEqual(len(result['ids']), 5) self.assertFalse(result['messages']) self.assertEqual([ -1, -42, -(2**31 - 1), -(2**31), -12345678 ], values(self.read())) @mute_logger('odoo.sql_db', 'odoo.models') def test_out_of_range(self): result = self.import_(['value'], [[str(2**31)]]) self.assertIs(result['ids'], False) self.assertEqual(result['messages'], [{ 'type': 'error', 'rows': {'from': 0, 'to': 0}, 'record': 0, 'message': "integer out of range\n" }]) result = self.import_(['value'], [[str(-2**32)]]) self.assertIs(result['ids'], False) self.assertEqual(result['messages'], [{ 'type': 'error', 'rows': {'from': 0, 'to': 0}, 'record': 0, 'message': "integer out of range\n" }]) def test_nonsense(self): result = self.import_(['value'], [['zorglub']]) self.assertIs(result['ids'], False) self.assertEqual(result['messages'], [{ 'field_name': 'Value', 'type': 'error', 'rows': {'from': 0, 'to': 0}, 'record': 0, 'field': 'value', 'message': u"'zorglub' does not seem to be an integer for field 'Value'", }]) class test_float_field(ImporterCase): model_name = 'export.float' def test_none(self): self.assertEqual( self.import_(['value'], []), {'ids': [], 'messages': [], 'nextrow': False}) def test_empty(self): result = self.import_(['value'], [['']]) self.assertEqual(len(result['ids']), 1) self.assertFalse(result['messages']) self.assertEqual( [False], values(self.read())) def test_zero(self): result = self.import_(['value'], [['0']]) self.assertEqual(len(result['ids']), 1) self.assertFalse(result['messages']) result = self.import_(['value'], [['-0']]) self.assertEqual(len(result['ids']), 1) self.assertFalse(result['messages']) self.assertEqual([False, False], values(self.read())) def test_positives(self): result = self.import_(['value'], [ ['1'], ['42'], [str(2**31-1)], ['12345678'], [str(2**33)], ['0.000001'], ]) self.assertEqual(len(result['ids']), 6) self.assertFalse(result['messages']) self.assertEqual([ 1, 42, 2**31-1, 12345678, 2.0**33, .000001 ], values(self.read())) def test_negatives(self): result = self.import_(['value'], [ ['-1'], ['-42'], [str(-2**31 + 1)], [str(-2**31)], ['-12345678'], [str(-2**33)], ['-0.000001'], ]) self.assertEqual(len(result['ids']), 7) self.assertFalse(result['messages']) self.assertEqual([ -1, -42, -(2**31 - 1), -(2**31), -12345678, -2.0**33, -.000001 ], values(self.read())) def test_nonsense(self): result = self.import_(['value'], [['foobar']]) self.assertIs(result['ids'], False) self.assertEqual(result['messages'], [ message(u"'foobar' does not seem to be a number for field 'Value'", field_name='Value')]) class test_string_field(ImporterCase): model_name = 'export.string.bounded' def test_empty(self): result = self.import_(['value'], [['']]) self.assertEqual(len(result['ids']), 1) self.assertFalse(result['messages']) self.assertEqual([False], values(self.read())) def test_imported(self): result = self.import_(['value'], [ [u'foobar'], [u'foobarbaz'], [u'Með suð í eyrum við spilum endalaust'], [u"People 'get' types. They use them all the time. Telling " u"someone he can't pound a nail with a banana doesn't much " u"surprise him."] ]) self.assertEqual(len(result['ids']), 4) self.assertFalse(result['messages']) self.assertEqual([ u"foobar", u"foobarbaz", u"Með suð í eyrum ", u"People 'get' typ", ], values(self.read())) class test_unbound_string_field(ImporterCase): model_name = 'export.string' def test_imported(self): result = self.import_(['value'], [ [u'í dag viðrar vel til loftárása'], # ackbar.jpg [u"If they ask you about fun, you tell them – fun is a filthy" u" parasite"] ]) self.assertEqual(len(result['ids']), 2) self.assertFalse(result['messages']) self.assertEqual([ u"í dag viðrar vel til loftárása", u"If they ask you about fun, you tell them – fun is a filthy parasite" ], values(self.read())) class test_required_string_field(ImporterCase): model_name = 'export.string.required' @mute_logger('odoo.sql_db', 'odoo.models') def test_empty(self): result = self.import_(['value'], [[]]) self.assertEqual(result['messages'], [message( u"Missing required value for the field 'Value' (value)")]) self.assertIs(result['ids'], False) @mute_logger('odoo.sql_db', 'odoo.models') def test_not_provided(self): result = self.import_(['const'], [['12']]) self.assertEqual(result['messages'], [message( u"Missing required value for the field 'Value' (value)")]) self.assertIs(result['ids'], False) @mute_logger('odoo.sql_db', 'odoo.models') def test_ignore_excess_messages(self): result = self.import_(['const'], [[str(n)] for n in range(100)]) self.assertIs(result['ids'], False) self.assertEqual(len(result['messages']), 11) for m in result['messages'][:-1]: self.assertEqual(m['type'], 'error') self.assertEqual(m['message'], u"Missing required value for the field 'Value' (value)") last = result['messages'][-1] self.assertEqual(last['type'], 'warning') self.assertEqual( last['message'], u"Found more than 10 errors and more than one error per 10 records, interrupted to avoid showing too many errors." ) class test_text(ImporterCase): model_name = 'export.text' def test_empty(self): result = self.import_(['value'], [['']]) self.assertEqual(len(result['ids']), 1) self.assertFalse(result['messages']) self.assertEqual([False], values(self.read())) def test_imported(self): s = (u"Breiðskífa er notað um útgefna hljómplötu sem inniheldur " u"stúdíóupptökur frá einum flytjanda. Breiðskífur eru oftast " u"milli 25-80 mínútur og er lengd þeirra oft miðuð við 33⅓ " u"snúninga 12 tommu vínylplötur (sem geta verið allt að 30 mín " u"hvor hlið).\n\nBreiðskífur eru stundum tvöfaldar og eru þær þá" u" gefnar út á tveimur geisladiskum eða tveimur vínylplötum.") result = self.import_(['value'], [[s]]) self.assertEqual(len(result['ids']), 1) self.assertFalse(result['messages']) self.assertEqual([s], values(self.read())) class test_selection(ImporterCase): model_name = 'export.selection' translations_fr = [ ("Foo", "tete"), ("Bar", "titi"), ("Qux", "toto"), ] def test_imported(self): result = self.import_(['value'], [ ['Qux'], ['Bar'], ['Foo'], ['2'], ]) self.assertEqual(len(result['ids']), 4) self.assertFalse(result['messages']) self.assertEqual(['3', '2', '1', '2'], values(self.read())) def test_imported_translated(self): self.add_translations( 'ir.model.fields.selection,name', 'model', 'fr_FR', *self.translations_fr) result = self.import_(['value'], [ ['toto'], ['tete'], ['titi'], ], context={'lang': 'fr_FR'}) self.assertEqual(len(result['ids']), 3) self.assertFalse(result['messages']) self.assertEqual(['3', '1', '2'], values(self.read())) result = self.import_(['value'], [['Foo']], context={'lang': 'fr_FR'}) self.assertEqual(len(result['ids']), 1) self.assertFalse(result['messages']) def test_invalid(self): result = self.import_(['value'], [['Baz']]) self.assertIs(result['ids'], False) self.assertEqual(result['messages'], [message( u"Value 'Baz' not found in selection field 'Value'", moreinfo="Foo Bar Qux 4".split(), field_name='Value', field_path=['value'])]) result = self.import_(['value'], [['42']]) self.assertIs(result['ids'], False) self.assertEqual(result['messages'], [message( u"Value '42' not found in selection field 'Value'", moreinfo="Foo Bar Qux 4".split(), field_name='Value', field_path=['value'])]) class test_selection_with_default(ImporterCase): model_name = 'export.selection.withdefault' def test_empty(self): """ Empty cells should set corresponding field to False """ result = self.import_(['value'], [['']]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) self.assertEqual( values(self.read()), [False]) def test_default(self): """ Non-provided cells should set corresponding field to default """ result = self.import_(['const'], [['42']]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) self.assertEqual( values(self.read()), ['2']) class test_selection_function(ImporterCase): model_name = 'export.selection.function' translations_fr = [ ("Corge", "toto"), ("Grault", "titi"), ("Wheee", "tete"), ("Moog", "tutu"), ] def test_imported(self): """ import uses fields_get, so translates import label (may or may not be good news) *and* serializes the selection function to reverse it: import does not actually know that the selection field uses a function """ # NOTE: conflict between a value and a label => pick first result = self.import_(['value'], [ ['3'], ["Grault"], ]) self.assertEqual(len(result['ids']), 2) self.assertFalse(result['messages']) self.assertEqual(values(self.read()), ['3', '1']) def test_translated(self): """ Expects output of selection function returns translated labels """ self.add_translations( 'ir.model.fields.selection,name', 'model', 'fr_FR', *self.translations_fr) result = self.import_(['value'], [ ['titi'], ['tete'], ], context={'lang': 'fr_FR'}) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 2) self.assertEqual(values(self.read()), ['1', '2']) result = self.import_(['value'], [['Wheee']], context={'lang': 'fr_FR'}) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) class test_m2o(ImporterCase): model_name = 'export.many2one' def test_by_name(self): # create integer objects record1 = self.env['export.integer'].create({'value': 42}) record2 = self.env['export.integer'].create({'value': 36}) # get its name name1 = dict(record1.name_get())[record1.id] name2 = dict(record2.name_get())[record2.id] # preheat the oven for _ in range(5): self.env.cr.execute('SAVEPOINT xxx') self.import_(['value'], [[name1], [name1], [name2]]) self.env.cr.execute('ROLLBACK TO SAVEPOINT xxx') self.env.cr.execute('RELEASE SAVEPOINT xxx') # 1 x SAVEPOINT model_load # 3 x name_search # 1 x SAVEPOINT # 3 x insert # 1 x RELEASE SAVEPOINT # => 9 with self.assertQueryCount(9): result = self.import_(['value'], [ # import by name_get [name1], [name1], [name2], ]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 3) # correct ids assigned to corresponding records self.assertEqual([ (record1.id, name1), (record1.id, name1), (record2.id, name2),], values(self.read())) def test_by_xid(self): record = self.env['export.integer'].create({'value': 42}) xid = self.xid(record) result = self.import_(['value/id'], [[xid]]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) b = self.browse() self.assertEqual(42, b[0].value.value) def test_by_id(self): record = self.env['export.integer'].create({'value': 42}) result = self.import_(['value/.id'], [[record.id]]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) b = self.browse() self.assertEqual(42, b[0].value.value) def test_by_names(self): record1 = self.env['export.integer'].create({'value': 42}) record2 = self.env['export.integer'].create({'value': 42}) name1 = dict(record1.name_get())[record1.id] name2 = dict(record2.name_get())[record2.id] # names should be the same self.assertEqual(name1, name2) result = self.import_(['value'], [[name2]]) self.assertEqual( result['messages'], [message(u"Found multiple matches for value 'export.integer:42' in field 'Value' (2 matches)", type='warning')]) self.assertEqual(len(result['ids']), 1) self.assertEqual([ (record1.id, name1) ], values(self.read())) def test_fail_by_implicit_id(self): """ Can't implicitly import records by id """ # create integer objects record1 = self.env['export.integer'].create({'value': 42}) record2 = self.env['export.integer'].create({'value': 36}) # Because name_search all the things. Fallback schmallback result = self.import_(['value'], [ # import by id, without specifying it [record1.id], [record2.id], [record1.id], ]) self.assertEqual(result['messages'], [ message(u"No matching record found for name '%s' in field 'Value'" % id, from_=index, to_=index, record=index, moreinfo=moreaction(res_model='export.integer'), field_name='Value', field_path=['value'], field_type='name', value=id) for index, id in enumerate([record1.id, record2.id, record1.id])]) self.assertIs(result['ids'], False) @mute_logger('odoo.sql_db') def test_fail_id_mistype(self): result = self.import_(['value/.id'], [["foo"]]) self.assertEqual(result['messages'], [ message(u"Invalid database id 'foo' for the field 'Value'", moreinfo=moreaction(res_model='ir.model.data', domain=[('model', '=', 'export.integer')]), field_name='Value', field_path=['value', '.id']) ]) self.assertIs(result['ids'], False) def test_sub_field(self): """ Does not implicitly create the record, does not warn that you can't import m2o subfields (at all)... """ result = self.import_(['value/value'], [['42']]) self.assertEqual(result['messages'], [ message(u"Can not create Many-To-One records indirectly, import " u"the field separately")]) self.assertIs(result['ids'], False) def test_fail_noids(self): result = self.import_(['value'], [['nameisnoexist:3']]) self.assertEqual(result['messages'], [message( u"No matching record found for name 'nameisnoexist:3' " u"in field 'Value'", moreinfo=moreaction( res_model='export.integer'), field_name='Value', field_path=['value'], field_type='name', value='nameisnoexist:3' )]) self.assertIs(result['ids'], False) result = self.import_(['value/id'], [['noxidhere']]) self.assertEqual(result['messages'], [message( u"No matching record found for external id 'noxidhere' " u"in field 'Value'", moreinfo=moreaction( res_model='ir.model.data', domain=[('model', '=', 'export.integer')]), field_name='Value', field_path=['value', 'id'], field_type="external id", value="noxidhere")]) self.assertIs(result['ids'], False) result = self.import_(['value/.id'], [['66']]) self.assertEqual(result['messages'], [message( u"No matching record found for database id '66' " u"in field 'Value'", moreinfo=moreaction( res_model='ir.model.data', domain=[('model', '=', 'export.integer')]), field_name='Value', field_path=['value', '.id'], field_type="database id", value="66")]) self.assertIs(result['ids'], False) def test_fail_multiple(self): result = self.import_( ['value', 'value/id'], [['somename', 'somexid']]) self.assertEqual(result['messages'], [message( u"Ambiguous specification for field 'Value', only provide one of " u"name, external id or database id")]) self.assertIs(result['ids'], False) def test_name_create_enabled_m2o(self): result = self.import_(['value'], [[101]]) self.assertEqual(result['messages'], [message( u"No matching record found for name '101' " u"in field 'Value'", moreinfo=moreaction( res_model='export.integer'), field_name='Value', field_path=['value'], field_type='name', value=101)]) self.assertIs(result['ids'], False) context = { 'name_create_enabled_fields': {'value': True}, } result = self.import_(['value'], [[101]], context=context) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) class TestInvalidStrings(ImporterCase): model_name = 'export.m2o.str' @mute_logger('odoo.sql_db') def test_fail_unpaired_surrogate(self): result = self.import_(['child_id'], [['\uddff']]) self.assertTrue(result['messages']) self.assertIn('surrogates', result['messages'][0]['message']) @mute_logger('odoo.sql_db') def test_fail_nul(self): result = self.import_(['child_id'], [['\x00']]) self.assertTrue(result['messages']) self.assertIn('NUL', result['messages'][0]['message']) class test_m2m(ImporterCase): model_name = 'export.many2many' # apparently, one and only thing which works is a # csv_internal_sep-separated list of ids, xids, or names (depending if # m2m/.id, m2m/id or m2m[/anythingelse] def test_ids(self): id1 = self.env['export.many2many.other'].create({'value': 3, 'str': 'record0'}).id id2 = self.env['export.many2many.other'].create({'value': 44, 'str': 'record1'}).id id3 = self.env['export.many2many.other'].create({'value': 84, 'str': 'record2'}).id id4 = self.env['export.many2many.other'].create({'value': 9, 'str': 'record3'}).id id5 = self.env['export.many2many.other'].create({'value': 99, 'str': 'record4'}).id result = self.import_(['value/.id'], [ ['%d,%d' % (id1, id2)], ['%d,%d,%d' % (id1, id3, id4)], ['%d,%d,%d' % (id1, id2, id3)], ['%d' % id5] ]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 4) ids = lambda records: [record.id for record in records] b = self.browse() self.assertEqual(ids(b[0].value), [id1, id2]) self.assertEqual(values(b[0].value), [3, 44]) self.assertEqual(ids(b[2].value), [id1, id2, id3]) self.assertEqual(values(b[2].value), [3, 44, 84]) def test_noids(self): result = self.import_(['value/.id'], [['42']]) self.assertEqual(result['messages'], [message( u"No matching record found for database id '42' in field " u"'Value'", moreinfo=moreaction( res_model='ir.model.data', domain=[('model', '=', 'export.many2many.other')]), field_name='Value', field_path=['value', '.id'], field_type="database id", value='42')]) self.assertIs(result['ids'], False) def test_xids(self): record0 = self.env['export.many2many.other'].create({'value': 3, 'str': 'record0'}) record1 = self.env['export.many2many.other'].create({'value': 44, 'str': 'record1'}) record2 = self.env['export.many2many.other'].create({'value': 84, 'str': 'record2'}) record3 = self.env['export.many2many.other'].create({'value': 9, 'str': 'record3'}) result = self.import_(['value/id'], [ ['%s,%s' % (self.xid(record0), self.xid(record1))], ['%s' % self.xid(record3)], ['%s,%s' % (self.xid(record2), self.xid(record1))], ]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 3) b = self.browse() self.assertCountEqual(values(b[0].value), [3, 44]) self.assertCountEqual(values(b[2].value), [44, 84]) def test_noxids(self): result = self.import_(['value/id'], [['noxidforthat']]) self.assertEqual(result['messages'], [message( u"No matching record found for external id 'noxidforthat' in field" u" 'Value'", moreinfo=moreaction( res_model='ir.model.data', domain=[('model', '=', 'export.many2many.other')]), field_name='Value', field_path=['value', 'id'], field_type='external id', value='noxidforthat')]) self.assertIs(result['ids'], False) def test_names(self): record0 = self.env['export.many2many.other'].create({'value': 3, 'str': 'record0'}) record1 = self.env['export.many2many.other'].create({'value': 44, 'str': 'record1'}) record2 = self.env['export.many2many.other'].create({'value': 84, 'str': 'record2'}) record3 = self.env['export.many2many.other'].create({'value': 9, 'str': 'record3'}) name = lambda record: record.display_name result = self.import_(['value'], [ ['%s,%s' % (name(record1), name(record2))], ['%s,%s,%s' % (name(record0), name(record1), name(record2))], ['%s,%s' % (name(record0), name(record3))], ]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 3) b = self.browse() self.assertEqual(values(b[1].value), [3, 44, 84]) self.assertEqual(values(b[2].value), [3, 9]) def test_nonames(self): result = self.import_(['value'], [['wherethem2mhavenonames']]) self.assertEqual(result['messages'], [message( u"No matching record found for name 'wherethem2mhavenonames' in " u"field 'Value'", moreinfo=moreaction( res_model='export.many2many.other'), field_name='Value', field_path=['value'], field_type="name", value='wherethem2mhavenonames')]) self.assertIs(result['ids'], False) def test_import_to_existing(self): id1 = self.env['export.many2many.other'].create({'value': 3, 'str': 'record0'}).id id2 = self.env['export.many2many.other'].create({'value': 44, 'str': 'record1'}).id id3 = self.env['export.many2many.other'].create({'value': 84, 'str': 'record2'}).id id4 = self.env['export.many2many.other'].create({'value': 9, 'str': 'record3'}).id xid = 'myxid' result = self.import_(['id', 'value/.id'], [[xid, '%d,%d' % (id1, id2)]]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) result = self.import_(['id', 'value/.id'], [[xid, '%d,%d' % (id3, id4)]]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) b = self.browse() self.assertEqual(len(b), 1) # TODO: replacement of existing m2m values is correct? self.assertEqual(values(b[0].value), [84, 9]) class test_o2m(ImporterCase): model_name = 'export.one2many' def test_name_get(self): s = u'Java is a DSL for taking large XML files and converting them ' \ u'to stack traces' result = self.import_( ['const', 'value'], [['5', s]]) self.assertEqual(result['messages'], [message( u"No matching record found for name '%s' in field 'Value'" % s[:50], moreinfo=moreaction(res_model='export.one2many.child'), field_name='Value', field_path=['value'], field_type='name', value=s[:50])]) self.assertIs(result['ids'], False) def test_single(self): result = self.import_(['const', 'value/value'], [ ['5', '63'] ]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) (b,) = self.browse() self.assertEqual(b.const, 5) self.assertEqual(values(b.value), [63]) def test_multicore(self): result = self.import_(['const', 'value/value'], [ ['5', '63'], ['6', '64'], ]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 2) b1, b2 = self.browse() self.assertEqual(b1.const, 5) self.assertEqual(values(b1.value), [63]) self.assertEqual(b2.const, 6) self.assertEqual(values(b2.value), [64]) def test_multisub(self): result = self.import_(['const', 'value/value'], [ ['5', '63'], ['', '64'], ['', '65'], ['', '66'], ]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) (b,) = self.browse() self.assertEqual(set(values(b.value)), set([63, 64, 65, 66])) def test_multi_subfields(self): result = self.import_(['value/str', 'const', 'value/value'], [ ['this', '5', '63'], ['is', '', '64'], ['the', '', '65'], ['rhythm', '', '66'], ]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) (b,) = self.browse() self.assertEqual(set(values(b.value.sorted())), set([63, 64, 65, 66])) self.assertEqual( values(b.value.sorted(), 'str'), 'this is the rhythm'.split()) def test_subfields_fail_by_implicit_id(self): result = self.import_(['value/parent_id'], [['noxidforthat']]) self.assertEqual(result['messages'], [message( u"No matching record found for name 'noxidforthat' in field 'Value/Parent'", moreinfo=moreaction(res_model='export.one2many'), field_name='Value', field_path=['value', 'parent_id'], field_type='name', value='noxidforthat')]) self.assertIs(result['ids'], False) def test_link_inline(self): """ m2m-style specification for o2ms """ id1 = self.env['export.one2many.child'].create({'str': 'Bf', 'value': 109}).id id2 = self.env['export.one2many.child'].create({'str': 'Me', 'value': 262}).id result = self.import_(['const', 'value/.id'], [ ['42', '%d,%d' % (id1, id2)] ]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) [b] = self.browse() self.assertEqual(b.const, 42) # automatically forces link between core record and o2ms self.assertEqual(set(values(b.value)), set([109, 262])) self.assertEqual(values(b.value, field='parent_id'), [b, b]) def test_link(self): """ O2M relating to an existing record (update) force a LINK_TO as well """ id1 = self.env['export.one2many.child'].create({'str': 'Bf', 'value': 109}).id id2 = self.env['export.one2many.child'].create({'str': 'Me', 'value': 262}).id result = self.import_(['const', 'value/.id'], [ ['42', str(id1)], ['', str(id2)], ]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) [b] = self.browse() self.assertEqual(b.const, 42) # automatically forces link between core record and o2ms self.assertCountEqual(values(b.value), [109, 262]) self.assertEqual(values(b.value, field='parent_id'), [b, b]) def test_link_2(self): id1 = self.env['export.one2many.child'].create({'str': 'Bf', 'value': 109}).id id2 = self.env['export.one2many.child'].create({'str': 'Me', 'value': 262}).id result = self.import_(['const', 'value/.id', 'value/value'], [ ['42', str(id1), '1'], ['', str(id2), '2'], ]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) [b] = self.browse() self.assertEqual(b.const, 42) self.assertEqual(set(values(b.value)), set([1, 2])) self.assertEqual(values(b.value, field='parent_id'), [b, b]) def test_o2m_repeated_with_xids(self): # concern: formerly this would link existing records, and fault if # the records did not exist. This is more in line with other XID uses, # however it does make thing work where they'd previously fail for # well-defined reasons. result = self.import_(['id', 'const', 'value/id', 'value/value'], [ ['a', '5', 'aa', '11'], ['', '', 'ab', '12'], ['', '', 'ac', '13'], ['', '', 'ad', '14'], ['b', '10', 'ba', '15'], ['', '', 'bb', '16'], ]) self.assertFalse(result['messages']) result = self.import_(['id', 'const', 'value/id', 'value/value'], [ ['a', '5', 'aa', '11'], ['', '', 'ab', '12'], ['', '', 'ac', '13'], ['', '', 'ad', '14'], ['b', '8', 'ba', '25'], ['', '', 'bb', '16'], ]) self.assertFalse(result['messages']) [a, b] = self.browse().sorted(lambda r: r.const) self.assertEqual(len(a.value), 4) self.assertEqual(len(b.value), 2) self.assertEqual(b.const, 8) self.assertEqual(b.value.mapped('value'), [25, 16]) def test_name_create_enabled_m2o_in_o2m(self): result = self.import_(['value/m2o'], [[101]]) self.assertEqual(result['messages'], [message( u"No matching record found for name '101' " u"in field 'Value/M2O'", moreinfo=moreaction( res_model='export.integer'), field_name='Value', field_path=['value', 'm2o'], field_type='name', value=101)]) self.assertEqual(result['ids'], False) context = { 'name_create_enabled_fields': {'value/m2o': True}, } result = self.import_(['value/m2o'], [[101]], context=context) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) [b] = self.browse() self.assertEqual(b.value.m2o.value, 101) class test_o2m_multiple(ImporterCase): model_name = 'export.one2many.multiple' def test_multi_mixed(self): result = self.import_(['const', 'child1/value', 'child2/value'], [ ['5', '11', '21'], ['', '12', '22'], ['', '13', '23'], ['', '14', ''], ]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) [b] = self.browse() self.assertEqual(set(values(b.child1)), set([11, 12, 13, 14])) self.assertEqual(set(values(b.child2)), set([21, 22, 23])) def test_multi(self): result = self.import_(['const', 'child1/value', 'child2/value'], [ ['5', '11', '21'], ['', '12', ''], ['', '13', ''], ['', '14', ''], ['', '', '22'], ['', '', '23'], ]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) [b] = self.browse() self.assertEqual(set(values(b.child1)), set([11, 12, 13, 14])) self.assertEqual(set(values(b.child2)), set([21, 22, 23])) def test_multi_fullsplit(self): result = self.import_(['const', 'child1/value', 'child2/value'], [ ['5', '11', ''], ['', '12', ''], ['', '13', ''], ['', '14', ''], ['', '', '21'], ['', '', '22'], ['', '', '23'], ]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) [b] = self.browse() self.assertEqual(b.const, 5) self.assertEqual(set(values(b.child1)), set([11, 12, 13, 14])) self.assertEqual(set(values(b.child2)), set([21, 22, 23])) class test_realworld(SavepointCaseWithUserDemo): @classmethod def setUpClass(cls): super(test_realworld, cls).setUpClass() cls._load_partners_set() def test_bigfile(self): data = json.loads(pkgutil.get_data(self.__module__, 'contacts_big.json').decode('utf-8')) result = self.env['res.partner'].load(['name', 'mobile', 'email', 'image_1920'], data) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), len(data)) def test_backlink(self): fnames = ["name", "type", "street", "city", "country_id", "category_id", "is_company", "parent_id"] data = json.loads(pkgutil.get_data(self.__module__, 'contacts.json').decode('utf-8')) result = self.env['res.partner'].load(fnames, data) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), len(data)) def test_recursive_o2m(self): """ The content of the o2m field's dict needs to go through conversion as it may be composed of convertables or other relational fields """ self.env['ir.model.data'].clear_caches() Model = self.env['export.one2many.recursive'] result = Model.load( ['value', 'child/const', 'child/child1/str', 'child/child2/value'], [ ['4', '42', 'foo', '55'], ['', '43', 'bar', '56'], ['', '', 'baz', ''], ['', '55', 'qux', '57'], ['5', '99', 'wheee', ''], ['', '98', '', '12'], ], ) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 2) b = Model.browse(result['ids']) self.assertEqual((b[0].value, b[1].value), (4, 5)) self.assertEqual([child.str for child in b[0].child.sorted()[1].child1], ['bar', 'baz']) self.assertFalse(len(b[1].child.sorted()[1].child1)) self.assertEqual([child.value for child in b[1].child.sorted()[1].child2], [12]) def test_o2m_subfields_fail_by_implicit_id(self): self.env['ir.model.data'].clear_caches() Model = self.env['export.one2many.recursive'] result = Model.with_context(import_file=True).load( ['child/child1/parent_id'], [['5'],], ) self.assertEqual(result['messages'], [message( u"No matching record found for name '5' in field 'Child/Child1/Parent'", field='child', moreinfo=moreaction(res_model='export.one2many.multiple'), field_name='Child', field_path=['child', 'child1', 'parent_id'], field_type='name', value='5')]) self.assertIs(result['ids'], False) class test_date(ImporterCase): model_name = 'export.date' def test_empty(self): self.assertEqual( self.import_(['value'], []), {'ids': [], 'messages': [], 'nextrow': False}) def test_basic(self): result = self.import_(['value'], [['2012-02-03']]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) def test_invalid(self): result = self.import_(['value'], [['not really a date']]) self.assertEqual(result['messages'], [ message(u"'not really a date' does not seem to be a valid date " u"for field 'Value'", moreinfo=u"Use the format '2012-12-31'", field_name='Value', field_path=['value'])]) self.assertIs(result['ids'], False) class test_datetime(ImporterCase): model_name = 'export.datetime' def test_empty(self): self.assertEqual( self.import_(['value'], []), {'ids': [], 'messages': [], 'nextrow': False}) def test_basic(self): result = self.import_(['value'], [['2012-02-03 11:11:11']]) self.assertFalse(result['messages']) self.assertEqual(len(result['ids']), 1) def test_invalid(self): result = self.import_(['value'], [['not really a datetime']]) self.assertEqual(result['messages'], [ message(u"'not really a datetime' does not seem to be a valid " u"datetime for field 'Value'", moreinfo=u"Use the format '2012-12-31 23:59:59'", field_name='Value', field_path=['value'])]) self.assertIs(result['ids'], False) def test_checktz1(self): """ Imported date should be interpreted as being in the tz provided by the context """ # write dummy tz in user (Asia/Hovd UTC+0700), should be superseded by # context self.env.user.write({'tz': 'Asia/Hovd'}) # UTC+1400 result = self.import_( ['value'], [['2012-02-03 11:11:11']], {'tz': 'Pacific/Kiritimati'}) self.assertFalse(result['messages']) self.assertEqual( [fields.Datetime.to_string(value['value']) for value in self.read(domain=[('id', 'in', result['ids'])])], ['2012-02-02 21:11:11']) # UTC-0930 result = self.import_( ['value'], [['2012-02-03 11:11:11']], {'tz': 'Pacific/Marquesas'}) self.assertFalse(result['messages']) self.assertEqual( [fields.Datetime.to_string(value['value']) for value in self.read(domain=[('id', 'in', result['ids'])])], ['2012-02-03 20:41:11']) def test_usertz(self): """ If the context does not hold a timezone, the importing user's tz should be used """ # UTC +1000 self.env.user.write({'tz': 'Asia/Yakutsk'}) result = self.import_( ['value'], [['2012-02-03 11:11:11']]) self.assertFalse(result['messages']) self.assertEqual( [fields.Datetime.to_string(value['value']) for value in self.read(domain=[('id', 'in', result['ids'])])], ['2012-02-03 01:11:11']) def test_notz(self): """ If there is no tz either in the context or on the user, falls back to UTC """ self.env.user.write({'tz': False}) result = self.import_(['value'], [['2012-02-03 11:11:11']]) self.assertFalse(result['messages']) self.assertEqual( [fields.Datetime.to_string(value['value']) for value in self.read(domain=[('id', 'in', result['ids'])])], ['2012-02-03 11:11:11']) class test_unique(ImporterCase): model_name = 'export.unique' @mute_logger('odoo.sql_db') def test_unique(self): result = self.import_(['value'], [ ['1'], ['1'], ['2'], ['3'], ['3'], ]) self.assertFalse(result['ids']) self.assertEqual(result['messages'], [ dict(message=u"The value for the field 'value' already exists " u"(this is probably 'Value' in the current model).", type='error', rows={'from': 1, 'to': 1}, record=1, field='value'), dict(message=u"The value for the field 'value' already exists " u"(this is probably 'Value' in the current model).", type='error', rows={'from': 4, 'to': 4}, record=4, field='value'), ]) @mute_logger('odoo.sql_db') def test_unique_pair(self): result = self.import_(['value2', 'value3'], [ ['0', '1'], ['1', '0'], ['1', '1'], ['1', '1'], ]) self.assertFalse(result['ids']) self.assertEqual(len(result['messages']), 1) message = result['messages'][0] self.assertEqual(message['type'], 'error') self.assertEqual(message['record'], 3) self.assertEqual(message['rows'], {'from': 3, 'to': 3}) m = re.match( r"The values for the fields '([^']+)' already exist " r"\(they are probably '([^']+)' in the current model\)\.", message['message'] ) self.assertIsNotNone(m) self.assertItemsEqual( m.group(1).split(', '), ['value2', 'value3'] ) self.assertItemsEqual( m.group(2).split(', '), ['Value2', 'Value3'] ) class test_inherits(ImporterCase): """ The import process should only assign a new xid (derived from the childs') if the child is being created and triggers the creation of the parent """ model_name = 'export.inherits.child' def test_create_no_parent(self): r = self.import_(['id', 'value_parent', 'value'], [ ['xxx.child', '0', '1'], ]) rec = self.env[self.model_name].browse(r['ids']) self.assertEqual(rec.value_parent, 0) self.assertEqual(rec.value, 1) self.assertEqual(rec.parent_id.value_parent, 0) self.assertEqual( rec._get_external_ids()[rec.id], ['xxx.child'], ) self.assertEqual( rec.parent_id._get_external_ids()[rec.parent_id.id], ['xxx.child_export_inherits_parent'], ) def test_create_parent_no_xid(self): parent = self.env['export.inherits.parent'].create({'value_parent': 0}) r = self.import_(['id', 'parent_id/.id', 'value'], [ ['xxx.child', str(parent.id), '1'], ]) rec = self.env[self.model_name].browse(r['ids']) self.assertEqual(rec.value_parent, 0) self.assertEqual(rec.parent_id, parent) self.assertEqual( rec._get_external_ids()[rec.id], ['xxx.child'], ) self.assertEqual( rec.parent_id._get_external_ids()[rec.parent_id.id], [], "no xid should be created for the parent" ) def test_create_parent_with_xid(self): parent = self.env['export.inherits.parent'].create({'value_parent': 0}) pid = self.env['ir.model.data'].create({ 'model': 'export.inherits.parent', 'res_id': parent.id, 'module': 'xxx', 'name': 'parent', }) r = self.import_(['id', 'parent_id/.id', 'value'], [ ['xxx.child', str(parent.id), '1'], ]) rec = self.env[self.model_name].browse(r['ids']) self.assertEqual(rec.value_parent, 0) self.assertEqual(rec.parent_id, parent) self.assertTrue(pid.exists().res_id, parent.id) self.assertEqual( rec._get_external_ids()[rec.id], ['xxx.child'], ) self.assertEqual( rec.parent_id._get_external_ids()[rec.parent_id.id], ['xxx.parent'], ) def test_create_parent_by_xid(self): parent = self.env['export.inherits.parent'].create({'value_parent': 0}) pid = self.env['ir.model.data'].create({ 'model': 'export.inherits.parent', 'res_id': parent.id, 'module': 'xxx', 'name': 'parent', }) r = self.import_(['id', 'parent_id/id', 'value'], [ ['xxx.child', 'xxx.parent', '1'], ]) rec = self.env[self.model_name].browse(r['ids']) self.assertEqual(rec.value_parent, 0) self.assertEqual(rec.parent_id, parent) self.assertTrue(pid.exists().res_id, parent.id) self.assertEqual( rec._get_external_ids()[rec.id], ['xxx.child'], ) self.assertEqual( rec.parent_id._get_external_ids()[rec.parent_id.id], ['xxx.parent'], ) def test_update_parent_no_xid(self): parent = self.env['export.inherits.parent'].create({'value_parent': 0}) child = self.env[self.model_name].create({ 'parent_id': parent.id, 'value': 1, }) self.env['ir.model.data'].create({ 'model': self.model_name, 'res_id': child.id, 'module': 'xxx', 'name': 'child' }) self.import_(['id', 'value'], [ ['xxx.child', '42'] ]) self.assertEqual(child.value, 42) self.assertEqual(child.parent_id, parent) self.assertEqual( child._get_external_ids()[child.id], ['xxx.child'], ) self.assertEqual( parent._get_external_ids()[parent.id], [], ) def test_update_parent_with_xid(self): parent = self.env['export.inherits.parent'].create({'value_parent': 0}) child = self.env[self.model_name].create({ 'parent_id': parent.id, 'value': 1, }) pid, cid = self.env['ir.model.data'].create([{ 'model': 'export.inherits.parent', 'res_id': parent.id, 'module': 'xxx', 'name': 'parent', }, { 'model': self.model_name, 'res_id': child.id, 'module': 'xxx', 'name': 'child' }]) self.import_(['id', 'value'], [ ['xxx.child', '42'] ]) self.assertEqual(child.value, 42) self.assertEqual(child.parent_id, parent) self.assertEqual(pid.exists().res_id, parent.id) self.assertEqual(cid.exists().res_id, child.id) self.assertEqual( child._get_external_ids()[child.id], ['xxx.child'], ) self.assertEqual( parent._get_external_ids()[parent.id], ['xxx.parent'], )
37.722563
55,339
23,925
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import itertools import pstats from cProfile import Profile from odoo import fields, Command from odoo.tests import common class CreatorCase(common.TransactionCase): model_name = False def __init__(self, *args, **kwargs): super(CreatorCase, self).__init__(*args, **kwargs) self.model = None def setUp(self): super(CreatorCase, self).setUp() self.model = self.env[self.model_name] def make(self, value, context=None): return self.model.with_context(**(context or {})).create({'value': value}) def export(self, value, fields=('value',), context=None): record = self.make(value, context=context) record.invalidate_cache() return record._export_rows([f.split('/') for f in fields]) class test_xids(CreatorCase): model_name = 'export.boolean' def test_no_module(self): record = self.make(True) # add existing xid without module self.env['ir.model.data'].create({ 'module': '', 'name': 'x', 'model': self.model_name, 'res_id': record.id, }) record.invalidate_cache() self.assertEqual( record._export_rows([['id'], ['value']]), [[u'x', True]] ) class test_boolean_field(CreatorCase): model_name = 'export.boolean' def test_true(self): self.assertEqual( self.export(True), [[True]]) def test_false(self): """ ``False`` value to boolean fields is unique in being exported as a (unicode) string, not a boolean """ self.assertEqual( self.export(False), [[False]]) class test_integer_field(CreatorCase): model_name = 'export.integer' def test_empty(self): self.assertEqual(self.model.search([]).ids, [], "Test model should have no records") def test_0(self): self.assertEqual( self.export(0), [[0]]) def test_basic_value(self): self.assertEqual( self.export(42), [[42]]) def test_negative(self): self.assertEqual( self.export(-32), [[-32]]) def test_huge(self): self.assertEqual( self.export(2**31-1), [[2147483647]]) class test_float_field(CreatorCase): model_name = 'export.float' def test_0(self): self.assertEqual( self.export(0.0), [[0.0]]) def test_epsilon(self): self.assertEqual( self.export(0.000000000027), [[0.000000000027]]) def test_negative(self): self.assertEqual( self.export(-2.42), [[-2.42]]) def test_positive(self): self.assertEqual( self.export(47.36), [[47.36]]) def test_big(self): self.assertEqual( self.export(87654321.4678), [[87654321.4678]]) class test_decimal_field(CreatorCase): model_name = 'export.decimal' def test_0(self): self.assertEqual( self.export(0.0), [[0.0]]) def test_epsilon(self): """ epsilon gets sliced to 0 due to precision """ self.assertEqual( self.export(0.000000000027), [[0.0]]) def test_negative(self): self.assertEqual( self.export(-2.42), [[-2.42]]) def test_positive(self): self.assertEqual( self.export(47.36), [[47.36]]) def test_big(self): self.assertEqual( self.export(87654321.4678), [[87654321.468]]) class test_string_field(CreatorCase): model_name = 'export.string.bounded' def test_empty(self): self.assertEqual( self.export(""), [['']]) def test_within_bounds(self): self.assertEqual( self.export("foobar"), [[u"foobar"]]) def test_out_of_bounds(self): self.assertEqual( self.export("C for Sinking, " "Java for Drinking, " "Smalltalk for Thinking. " "...and Power to the Penguin!"), [[u"C for Sinking, J"]]) class test_unbound_string_field(CreatorCase): model_name = 'export.string' def test_empty(self): self.assertEqual( self.export(""), [['']]) def test_small(self): self.assertEqual( self.export("foobar"), [[u"foobar"]]) def test_big(self): self.assertEqual( self.export("We flew down weekly to meet with IBM, but they " "thought the way to measure software was the amount " "of code we wrote, when really the better the " "software, the fewer lines of code."), [[u"We flew down weekly to meet with IBM, but they thought the " u"way to measure software was the amount of code we wrote, " u"when really the better the software, the fewer lines of " u"code."]]) class test_text(CreatorCase): model_name = 'export.text' def test_empty(self): self.assertEqual( self.export(""), [['']]) def test_small(self): self.assertEqual( self.export("foobar"), [[u"foobar"]]) def test_big(self): self.assertEqual( self.export("So, `bind' is `let' and monadic programming is" " equivalent to programming in the A-normal form. That" " is indeed all there is to monads"), [[u"So, `bind' is `let' and monadic programming is equivalent to" u" programming in the A-normal form. That is indeed all there" u" is to monads"]]) def test_numeric(self): self.assertEqual( self.export(42), [["42"]]) class test_date(CreatorCase): model_name = 'export.date' def test_empty(self): self.assertEqual( self.export(False), [['']]) def test_basic(self): self.assertEqual( self.export('2011-11-07'), [[fields.Date.from_string('2011-11-07')]]) class test_datetime(CreatorCase): model_name = 'export.datetime' def test_empty(self): self.assertEqual( self.export(False), [['']]) def test_basic(self): """ Export value with no TZ set on the user """ self.env.user.write({'tz': False}) self.assertEqual( self.export('2011-11-07 21:05:48'), [[fields.Datetime.from_string('2011-11-07 21:05:48')]]) def test_tz(self): """ Export converts the value in the user's TZ .. note:: on the other hand, export uses user lang for name_get """ self.assertEqual( self.export('2011-11-07 21:05:48', context={'tz': 'Pacific/Norfolk'}), [[fields.Datetime.from_string('2011-11-08 08:35:48')]]) class test_selection(CreatorCase): model_name = 'export.selection' translations_fr = [ ("Qux", "toto"), ("Bar", "titi"), ("Foo", "tete"), ] def test_empty(self): self.assertEqual( self.export(False), [['']]) def test_value(self): """ selections export the *label* for their value """ self.assertEqual( self.export('2'), [[u"Bar"]]) def test_localized_export(self): self.env['res.lang']._activate_lang('fr_FR') ir_field = self.env['ir.model.fields']._get('export.selection', 'value') selection = ir_field.selection_ids translations = dict(self.translations_fr) for sel_fr, sel in zip(selection.with_context(lang='fr_FR'), selection): sel_fr.name = translations.get(sel.name, sel_fr.name) self.assertEqual( self.export('2', context={'lang': 'fr_FR'}), [[u'titi']]) class test_selection_function(CreatorCase): model_name = 'export.selection.function' def test_empty(self): self.assertEqual( self.export(False), [['']]) def test_value(self): # selection functions export the *value* itself self.assertEqual( self.export('1'), [['1']]) self.assertEqual( self.export('3'), [['3']]) self.assertEqual( self.export('0'), [['0']]) class test_m2o(CreatorCase): model_name = 'export.many2one' def test_empty(self): self.assertEqual( self.export(False), [['']]) def test_basic(self): """ Exported value is the name_get of the related object """ record = self.env['export.integer'].create({'value': 42}) name = dict(record.name_get())[record.id] self.assertEqual( self.export(record.id), [[name]]) def test_path(self): """ Can recursively export fields of m2o via path """ record = self.env['export.integer'].create({'value': 42}) self.assertEqual( self.export(record.id, fields=['value/.id', 'value/value']), [[str(record.id), 42]]) def test_external_id(self): record = self.env['export.integer'].create({'value': 42}) # Expecting the m2o target model name in the external id, # not this model's name self.assertRegex( self.export(record.id, fields=['value/id'])[0][0], u'__export__.export_integer_%d_[0-9a-f]{8}' % record.id) def test_identical(self): m2o = self.env['export.integer'].create({'value': 42}).id records = \ ( self.make(m2o) | self.make(m2o) | self.make(m2o) | self.make(m2o) ) records.invalidate_cache() xp = [r[0] for r in records._export_rows([['value', 'id']])] self.assertEqual(len(xp), 4) self.assertRegex( xp[0], u'__export__.export_integer_%d_[0-9a-f]{8}' % m2o ) self.assertEqual(set(xp), {xp[0]}) class test_o2m(CreatorCase): model_name = 'export.one2many' commands = [ Command.create({'value': 4, 'str': 'record1'}), Command.create({'value': 42, 'str': 'record2'}), Command.create({'value': 36, 'str': 'record3'}), Command.create({'value': 4, 'str': 'record4'}), Command.create({'value': 13, 'str': 'record5'}), ] names = [ u'export.one2many.child:%d' % d['value'] for c, _, d in commands ] def test_empty(self): self.assertEqual( self.export(False), [['']]) def test_single(self): self.assertEqual( self.export([Command.create({'value': 42})]), # name_get result [[u'export.one2many.child:42']]) def test_single_subfield(self): self.assertEqual( self.export([Command.create({'value': 42})], fields=['value', 'value/value']), [[u'export.one2many.child:42', 42]]) def test_integrate_one_in_parent(self): self.assertEqual( self.export([Command.create({'value': 42})], fields=['const', 'value/value']), [[4, 42]]) def test_multiple_records(self): self.assertEqual( self.export(self.commands, fields=['const', 'value/value']), [ [4, 4], [u'', 42], [u'', 36], [u'', 4], [u'', 13], ]) def test_multiple_records_name(self): self.assertEqual( self.export(self.commands, fields=['const', 'value']), [ [4, u'export.one2many.child:4'], [u'', u'export.one2many.child:42'], [u'', u'export.one2many.child:36'], [u'', u'export.one2many.child:4'], [u'', u'export.one2many.child:13'], ]) def test_multiple_records_id(self): export = self.export(self.commands, fields=['const', 'value/.id']) records = self.env['export.one2many.child'].search([]) self.assertEqual( export, [ [4, str(records[0].id)], ['', str(records[1].id)], ['', str(records[2].id)], ['', str(records[3].id)], ['', str(records[4].id)], ]) def test_multiple_records_with_name_before(self): self.assertEqual( self.export(self.commands, fields=['const', 'value', 'value/value']), [ [4, u'export.one2many.child:4', 4], ['', u'export.one2many.child:42', 42], ['', u'export.one2many.child:36', 36], ['', u'export.one2many.child:4', 4], ['', u'export.one2many.child:13', 13], ]) def test_multiple_records_with_name_after(self): self.assertEqual( self.export(self.commands, fields=['const', 'value/value', 'value']), [ [4, 4, u'export.one2many.child:4'], ['', 42, u'export.one2many.child:42'], ['', 36, u'export.one2many.child:36'], ['', 4, u'export.one2many.child:4'], ['', 13, u'export.one2many.child:13'], ]) def test_multiple_subfields_neighbour(self): self.assertEqual( self.export(self.commands, fields=['const', 'value/str','value/value']), [ [4, u'record1', 4], ['', u'record2', 42], ['', u'record3', 36], ['', u'record4', 4], ['', u'record5', 13], ]) def test_multiple_subfields_separated(self): self.assertEqual( self.export(self.commands, fields=['value/str', 'const', 'value/value']), [ [u'record1', 4, 4], [u'record2', '', 42], [u'record3', '', 36], [u'record4', '', 4], [u'record5', '', 13], ]) class test_o2m_multiple(CreatorCase): model_name = 'export.one2many.multiple' def make(self, value=None, **values): if value is not None: values['value'] = value return self.model.create(values) def export(self, value=None, fields=('child1', 'child2',), context=None, **values): record = self.make(value, **values) return record._export_rows([f.split('/') for f in fields]) def test_empty(self): self.assertEqual( self.export(child1=False, child2=False), [['', '']]) def test_single_per_side(self): self.assertEqual( self.export(child1=False, child2=[Command.create({'value': 42})]), [['', u'export.one2many.child.2:42']]) self.assertEqual( self.export(child1=[Command.create({'value': 43})], child2=False), [[u'export.one2many.child.1:43', '']]) self.assertEqual( self.export(child1=[Command.create({'value': 43})], child2=[Command.create({'value': 42})]), [[u'export.one2many.child.1:43', u'export.one2many.child.2:42']]) def test_single_integrate_subfield(self): fields = ['const', 'child1/value', 'child2/value'] self.assertEqual( self.export(child1=False, child2=[Command.create({'value': 42})], fields=fields), [[36, '', 42]]) self.assertEqual( self.export(child1=[Command.create({'value': 43})], child2=False, fields=fields), [[36, 43, '']]) self.assertEqual( self.export(child1=[Command.create({'value': 43})], child2=[Command.create({'value': 42})], fields=fields), [[36, 43, 42]]) def test_multiple(self): """ With two "concurrent" o2ms, exports the first line combined, then exports the rows for the first o2m, then the rows for the second o2m. """ fields = ['const', 'child1/value', 'child2/value'] child1 = [Command.create({'value': v, 'str': 'record%.02d' % index}) for index, v in zip(itertools.count(), [4, 42, 36, 4, 13])] child2 = [Command.create({'value': v, 'str': 'record%.02d' % index}) for index, v in zip(itertools.count(10), [8, 12, 8, 55, 33, 13])] self.assertEqual( self.export(child1=child1, child2=False, fields=fields), [ [36, 4, ''], ['', 42, ''], ['', 36, ''], ['', 4, ''], ['', 13, ''], ]) self.assertEqual( self.export(child1=False, child2=child2, fields=fields), [ [36, '', 8], ['', '', 12], ['', '', 8], ['', '', 55], ['', '', 33], ['', '', 13], ]) self.assertEqual( self.export(child1=child1, child2=child2, fields=fields), [ [36, 4, 8], ['', 42, ''], ['', 36, ''], ['', 4, ''], ['', 13, ''], ['', '', 12], ['', '', 8], ['', '', 55], ['', '', 33], ['', '', 13], ]) class test_m2m(CreatorCase): model_name = 'export.many2many' commands = [ Command.create({'value': 4, 'str': 'record000'}), Command.create({'value': 42, 'str': 'record001'}), Command.create({'value': 36, 'str': 'record010'}), Command.create({'value': 4, 'str': 'record011'}), Command.create({'value': 13, 'str': 'record100'}), ] names = [ u'export.many2many.other:%d' % d['value'] for c, _, d in commands ] def test_empty(self): self.assertEqual( self.export(False), [['']]) def test_single(self): self.assertEqual( self.export([Command.create({'value': 42})]), # name_get result [[u'export.many2many.other:42']]) def test_single_subfield(self): self.assertEqual( self.export([Command.create({'value': 42})], fields=['value', 'value/value'], context={'import_compat': False}), [[u'export.many2many.other:42', 42]]) def test_integrate_one_in_parent(self): self.assertEqual( self.export([Command.create({'value': 42})], fields=['const', 'value/value'], context={'import_compat': False}), [[4, 42]]) def test_multiple_records(self): self.assertEqual( self.export(self.commands, fields=['const', 'value/value'], context={'import_compat': False}), [ [4, 4], [u'', 42], [u'', 36], [u'', 4], [u'', 13], ]) def test_multiple_records_name(self): self.assertEqual( self.export(self.commands, fields=['const', 'value']), [ [4, 'export.many2many.other:4,export.many2many.other:42,export.many2many.other:36,export.many2many.other:4,export.many2many.other:13'], ]) self.assertEqual( self.export(self.commands, fields=['const', 'value'], context={'import_compat': False}), [ [4, u'export.many2many.other:4'], ['', u'export.many2many.other:42'], ['', u'export.many2many.other:36'], ['', u'export.many2many.other:4'], ['', u'export.many2many.other:13'], ]) def test_multiple_records_subfield(self): r = self.make(self.commands) xid = self.env['ir.model.data'].create({ 'name': 'whopwhopwhop', 'module': '__t__', 'model': r._name, 'res_id': r.id, }).complete_name sids = [ self.env['ir.model.data'].create({ 'name': sub.str, 'module': '__t__', 'model': sub._name, 'res_id': sub.id, }).complete_name for sub in r.value ] r.invalidate_cache() self.assertEqual( r._export_rows([['value', 'id']]), [['__t__.record000,__t__.record001,__t__.record010,__t__.record011,__t__.record100']] ) self.assertEqual( r.with_context(import_compat=True)._export_rows([['value', 'id']]), [['__t__.record000,__t__.record001,__t__.record010,__t__.record011,__t__.record100']] ) self.assertEqual( r.with_context(import_compat=True)._export_rows([['value'], ['value', 'id']]), [['', '__t__.record000,__t__.record001,__t__.record010,__t__.record011,__t__.record100']] ) self.assertEqual( r.with_context(import_compat=False)._export_rows([['id'], ['value', 'id'], ['value', 'value']]), [ [xid, u'__t__.record000', 4], [u'', u'__t__.record001', 42], [u'', u'__t__.record010', 36], [u'', u'__t__.record011', 4], [u'', u'__t__.record100', 13] ] ) self.assertEqual( r.with_context(import_compat=False)._export_rows([['id'], ['value', 'value'], ['value', 'id']]), [ [xid, 4, u'__t__.record000'], [u'', 42, u'__t__.record001'], [u'', 36, u'__t__.record010'], [u'', 4, u'__t__.record011'], [u'', 13, u'__t__.record100'] ] ) class test_function(CreatorCase): model_name = 'export.function' def test_value(self): """ Exports value normally returned by accessing the function field """ self.assertEqual( self.export(42), [[3]]) @common.tagged('-standard', 'bench') class test_xid_perfs(common.TransactionCase): def setUp(self): super(test_xid_perfs, self).setUp() self.profile = Profile() @self.addCleanup def _dump(): stats = pstats.Stats(self.profile) stats.strip_dirs() stats.sort_stats('cumtime') stats.print_stats(20) self.profile = None def test_basic(self): Model = self.env['export.integer'] for i in range(10000): Model.create({'value': i}) Model.invalidate_cache() records = Model.search([]) self.profile.runcall(records._export_rows, [['id'], ['value']]) def test_m2o_single(self): rid = self.env['export.integer'].create({'value': 42}).id Model = self.env['export.many2one'] for _ in range(10000): Model.create({'value': rid}) Model.invalidate_cache() records = Model.search([]) self.profile.runcall(records._export_rows, [['id'], ['value','id']]) def test_m2o_each(self): Model = self.env['export.many2one'] Integer = self.env['export.integer'] for i in range(10000): Model.create({ 'value': Integer.create({'value': i}).id }) Model.invalidate_cache() records = Model.search([]) self.profile.runcall(records._export_rows, [['id'], ['value', 'id']])
31.646825
23,925
955
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class TestModel(models.Model): _name = 'test_convert.test_model' _description = "Test Convert Model" @api.model def action_test_date(self, today_date): return True @api.model def action_test_time(self, cur_time): return True @api.model def action_test_timezone(self, timezone): return True class Usered(models.Model): _name = 'test_convert.usered' _description = "z test model ignore" name = fields.Char() user_id = fields.Many2one('res.users', default=lambda self: self.env.user) tz = fields.Char(default=lambda self: self.env.context.get('tz') or self.env.user.tz) @api.model def model_method(self, *args, **kwargs): return self, args, kwargs def method(self, *args, **kwargs): return self, args, kwargs
27.285714
955
317
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'test_convert', 'description': "Data for xml conversion tests", 'version': '0.0.1', 'category': 'Hidden/Tests', 'data': [ 'ir.model.access.csv', ], 'license': 'LGPL-3', }
24.384615
317
5,128
py
PYTHON
15.0
# -*- coding: utf-8 -*- """ Tests the ability to update environmental information on various nodes (e.g. change user, add context keys, ...) """ import os.path from lxml import etree from lxml.builder import E from odoo.tests import common from odoo.tools import config from odoo.tools.convert import xml_import odoo = E.odoo data = E.data record = E.record field = E.field function = E.function class TestEnv(common.TransactionCase): def setUp(self): super().setUp() self._importer = xml_import(self.env.cr, 'test_convert', None, 'init') def importer(self, doc): etree.RelaxNG( etree.parse( os.path.join(config['root_path'], 'import_xml.rng') ) ).assert_(doc) self._importer.parse(doc) def test_uid_data_record(self): self.importer( odoo( record( field("a", name="name"), model="test_convert.usered", id="test_convert.testing" ), uid="base.default_user" ) ) r = self.env.ref('test_convert.testing') self.assertEqual(r.name, 'a') self.assertEqual(r.create_uid, self.env.ref('base.default_user')) self.assertEqual(r.user_id, self.env.ref('base.default_user')) def test_uid_data_function(self): self.importer( odoo( function( model="test_convert.usered", name="create", eval="[[{'name': 'b'}]]", ), uid="base.default_user" ) ) r = self.env['test_convert.usered'].search([]) self.assertEqual(r.name, 'b') self.assertEqual(r.create_uid, self.env.ref('base.default_user')) self.assertEqual(r.user_id, self.env.ref('base.default_user')) def test_uid_record(self): self.importer( odoo( record( field('c', name="name"), model="test_convert.usered", id="test_convert.testing", uid="base.default_user" ), uid="base.user_root" ) ) r = self.env.ref('test_convert.testing') self.assertEqual(r.name, 'c') self.assertEqual(r.create_uid, self.env.ref('base.default_user')) self.assertEqual(r.user_id, self.env.ref('base.default_user')) def test_uid_function(self): self.importer( odoo( function( model="test_convert.usered", name="create", uid="base.default_user", eval="[[{'name': 'd'}]]" ), uid="base.user_root" ) ) r = self.env['test_convert.usered'].search([]) self.assertEqual(r.name, 'd') self.assertEqual(r.create_uid, self.env.ref('base.default_user')) self.assertEqual(r.user_id, self.env.ref('base.default_user')) def test_context_data_function(self): self.env.user.tz = 'UTC' self.importer( odoo( function( model="test_convert.usered", name="create", eval="[[{'name': 'e'}]]", ), context="{'tz': 'Asia/Kabul'}", ) ) r = self.env['test_convert.usered'].search([]) self.assertEqual(r.name, 'e') self.assertEqual(r.tz, 'Asia/Kabul') def test_context_function(self): self.env.user.tz = 'UTC' self.importer( odoo( function( model="test_convert.usered", name="create", context="{'tz': 'Pacific/Apia'}", eval="[[{'name': 'e'}]]", ), context="{'tz': 'Asia/Kabul'}", ) ) r = self.env['test_convert.usered'].search([]) self.assertEqual(r.name, 'e') self.assertEqual(r.tz, 'Pacific/Apia') def test_context_data_record(self): self.env.user.tz = 'UTC' self.importer( odoo( record( field("f", name="name"), model="test_convert.usered", ), context="{'tz': 'America/Knox_IN'}" ) ) r = self.env['test_convert.usered'].search([]) self.assertEqual(r.name, 'f') self.assertEqual(r.tz, 'America/Knox_IN') def test_context_record(self): self.env.user.tz = 'UTC' self.importer( odoo( record( field("f", name="name"), model="test_convert.usered", context="{'tz': 'America/Adak'}", ), context="{'tz': 'America/Knox_IN'}" ) ) r = self.env['test_convert.usered'].search([]) self.assertEqual(r.name, 'f') self.assertEqual(r.tz, 'America/Adak')
30.891566
5,128
6,284
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import collections import unittest from lxml import etree as ET from lxml.builder import E import odoo from odoo.tests import common from odoo.tools.convert import xml_import, _eval_xml Field = E.field Value = E.value class TestEvalXML(common.TransactionCase): def eval_xml(self, node, obj=None): return _eval_xml(obj, node, self.env) def test_char(self): self.assertEqual( self.eval_xml(Field("foo")), "foo") self.assertEqual( self.eval_xml(Field("None")), "None") def test_int(self): self.assertIsNone( self.eval_xml(Field("None", type='int')), "what the fuck?") self.assertEqual( self.eval_xml(Field(" 42 ", type="int")), 42) with self.assertRaises(ValueError): self.eval_xml(Field("4.82", type="int")) with self.assertRaises(ValueError): self.eval_xml(Field("Whelp", type="int")) def test_float(self): self.assertEqual( self.eval_xml(Field("4.78", type="float")), 4.78) with self.assertRaises(ValueError): self.eval_xml(Field("None", type="float")) with self.assertRaises(ValueError): self.eval_xml(Field("Foo", type="float")) def test_list(self): self.assertEqual( self.eval_xml(Field(type="list")), []) self.assertEqual( self.eval_xml(Field( Value("foo"), Value("5", type="int"), Value("4.76", type="float"), Value("None", type="int"), type="list" )), ["foo", 5, 4.76, None]) def test_file(self): Obj = collections.namedtuple('Obj', ['module', 'idref']) obj = Obj('test_convert', None) self.assertEqual( self.eval_xml(Field('test_file.txt', type='file'), obj), 'test_convert,test_file.txt') with self.assertRaises(IOError): self.eval_xml(Field('test_nofile.txt', type='file'), obj) def test_function(self): obj = xml_import(self.cr, 'test_convert', None, 'init') # pass args in eval xml = E.function( model="test_convert.usered", name="model_method", eval="[1, 2]", ) rec, args, kwargs = self.eval_xml(xml, obj) self.assertEqual(rec.env.context, self.env.context) self.assertEqual(rec.ids, []) self.assertEqual(args, (1, 2)) self.assertEqual(kwargs, {}) xml = E.function( model="test_convert.usered", name="method", eval="[1, 2]", ) rec, args, kwargs = self.eval_xml(xml, obj) self.assertEqual(rec.env.context, self.env.context) self.assertEqual(rec.ids, [1]) self.assertEqual(args, (2,)) self.assertEqual(kwargs, {}) # pass args in child elements xml = E.function( E.value(eval="1"), E.value(eval="2"), model="test_convert.usered", name="model_method", ) rec, args, kwargs = self.eval_xml(xml, obj) self.assertEqual(rec.env.context, self.env.context) self.assertEqual(rec.ids, []) self.assertEqual(args, (1, 2)) self.assertEqual(kwargs, {}) xml = E.function( E.value(eval="1"), E.value(eval="2"), model="test_convert.usered", name="method", ) rec, args, kwargs = self.eval_xml(xml, obj) self.assertEqual(rec.env.context, self.env.context) self.assertEqual(rec.ids, [1]) self.assertEqual(args, (2,)) self.assertEqual(kwargs, {}) def test_function_kwargs(self): obj = xml_import(self.cr, 'test_convert', None, 'init') # pass args and kwargs in child elements xml = E.function( E.value(eval="1"), E.value(name="foo", eval="2"), model="test_convert.usered", name="model_method", ) rec, args, kwargs = self.eval_xml(xml, obj) self.assertEqual(rec.env.context, self.env.context) self.assertEqual(rec.ids, []) self.assertEqual(args, (1,)) self.assertEqual(kwargs, {'foo': 2}) xml = E.function( E.value(eval="1"), E.value(name="foo", eval="2"), model="test_convert.usered", name="method", ) rec, args, kwargs = self.eval_xml(xml, obj) self.assertEqual(rec.env.context, self.env.context) self.assertEqual(rec.ids, [1]) self.assertEqual(args, ()) self.assertEqual(kwargs, {'foo': 2}) # pass args and context in kwargs xml = E.function( E.value(eval="1"), E.value(name="context", eval="{'foo': 2}"), model="test_convert.usered", name="model_method", ) rec, args, kwargs = self.eval_xml(xml, obj) self.assertEqual(rec.env.context, {'foo': 2}) self.assertEqual(rec.ids, []) self.assertEqual(args, (1,)) self.assertEqual(kwargs, {}) xml = E.function( E.value(eval="1"), E.value(name="context", eval="{'foo': 2}"), model="test_convert.usered", name="method", ) rec, args, kwargs = self.eval_xml(xml, obj) self.assertEqual(rec.env.context, {'foo': 2}) self.assertEqual(rec.ids, [1]) self.assertEqual(args, ()) self.assertEqual(kwargs, {}) def test_function_function(self): obj = xml_import(self.cr, 'test_convert', None, 'init') xml = E.function( E.function(model="test_convert.usered", name="search", eval="[[]]"), model="test_convert.usered", name="method", ) rec, args, kwargs = self.eval_xml(xml, obj) self.assertEqual(rec.env.context, {}) self.assertEqual(rec.ids, []) self.assertEqual(args, ()) self.assertEqual(kwargs, {}) @unittest.skip("not tested") def test_xml(self): pass @unittest.skip("not tested") def test_html(self): pass
31.898477
6,284
3,496
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api from odoo.tools import populate, pycompat class TestPopulateModel(models.Model): _name = 'test.populate' _description = 'Test Populate' name = fields.Char(default='Foo') state = fields.Selection([('a', 'A'), ('b', 'B')], default='a') active = fields.Boolean('Active', default=True) category_id = fields.Many2one('test.populate.category', 'Category') some_ref = fields.Integer('Reference') dependant_field_1 = fields.Char('Dependant 1') dependant_field_2 = fields.Char('Dependant 2') sequence = fields.Integer("Sequence") _populate_dependencies = ['test.populate.category'] _populate_sizes = { 'small': 20, 'medium': 30, 'large': 100, } def _populate_factories(self): # cross dependant field in a sub generator, cartesian product of two fields dependant_factories = [ ('dependant_field_1', populate.cartesian(['d1_1', 'd1_2'])), ('dependant_field_2', populate.cartesian(['d2_1', 'd2_2', 'd2_3_{counter}'])), ] def generate_dependant(iterator, *args): dependants_generator = populate.chain_factories(dependant_factories, self._name) for dependant_values in dependants_generator: values = next(iterator) yield {**dependant_values, **values, '__complete': values['__complete'] and dependant_values['__complete']} def get_name(values=None, counter=0, **kwargs): active = 'active' if values['active'] else 'inactive' cat = 'filling' if values['__complete'] else 'corner' return '%s_%s_%s' % (active, cat, counter) category_ids = self.env.registry.populated_models['test.populate.category'] return [ ('active', populate.cartesian([True, False], [3, 1])), ('state', populate.cartesian([False] + self.env['test.populate']._fields['state'].get_values(self.env))), ('some_ref', populate.iterate([False, 1, 2, 3, 4])), ('_dependant', generate_dependant), ('name', populate.compute(get_name)), ('category_id', populate.randomize([False] + category_ids)), ('sequence', populate.randint(1, 10)) ] class TestPopulateDependencyModel(models.Model): _name = 'test.populate.category' _description = 'Test Populate Category' _populate_sizes = { 'small': 3, 'medium': 10, 'large': 20, } name = fields.Char('Name', required=True, default='Cat1') active = fields.Boolean('Active', default=True) def _populate_factories(self): return [ ('active', populate.cartesian([True, False], [9, 1])), ('name', populate.cartesian(['Cat1', 'Cat2', 'Cat3'])), ] class TestNoPopulateModelInherit(models.Model): _name = 'test.populate.inherit' _inherit = 'test.populate' _description = 'Test populate inherit' additionnal_field = fields.Char(required=True) def _populate_factories(self): return super()._populate_factories() + [ ('additionnal_field', populate.iterate(['V1', 'V2', 'V3'])), ] class TestNoPopulateModel(models.Model): _name = 'test.no.populate' _description = 'A model with no populate method and a required field, should not crash' name = fields.Char(required=True)
36.416667
3,496
311
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'test-populate', 'version': '0.1', 'category': 'Tests', 'description': """A module to test populate.""", 'depends': ['base'], 'data': [ 'ir.model.access.csv', ], 'installable': True, 'auto_install': False, 'license': 'LGPL-3', }
22.214286
311
7,205
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import collections import logging from odoo.tests import common from odoo.cli.populate import Populate from odoo.tools import mute_logger, populate from unittest.mock import patch _logger = logging.getLogger(__name__) # todo patch cursor commit class TestPopulate(common.TransactionCase): def setUp(self): super(TestPopulate, self).setUp() patcher = patch.object(self.cr, 'commit') patcher.start() self.addCleanup(patcher.stop) def test_dependency(self): ordered_models = Populate._get_ordered_models(self.env, ['test.populate']) ordered_models_names = [model._name for model in ordered_models] self.assertEqual(ordered_models_names, ['test.populate.category', 'test.populate']) @mute_logger('odoo.cli.populate') def test_no_populate(self): """ Check that model with no populate method are not populated""" model = 'test.no.populate' populated = Populate.populate(self.env, 'small', [model]) new = populated[model] self.assertFalse(new) @mute_logger('odoo.cli.populate') def test_populate(self): """ Check that model with populate methods are correctly populated""" model = 'test.populate' populated = Populate.populate(self.env, 'small', [model]) records = self.check_test_populate_values(populated, model) # pseudo random after cartesian with ~ 1/4 False, 3/4 True # seed is model dependant self.assertEqual(records.mapped('active')[6:20], [ True, True, True, True, True, True, False, False, True, True, True, True, False, True ]) # pseudo random after iterate self.assertEqual(records.mapped('some_ref')[5:20], [ 1, 0, 2, 4, 4, 3, 4, 1, 2, 2, 2, 4, 4, 1, 2 ]) self.assertEqual(records.mapped('sequence')[:20], [6, 10, 1, 1, 1, 3, 8, 9, 1, 5, 9, 5, 7, 3, 5, 3, 6, 4, 9, 2]) # Test randint @mute_logger('odoo.cli.populate') def test_populate_inherit(self): """ Check that model with populate methods are correctly populated""" model = 'test.populate.inherit' populated = Populate.populate(self.env, 'small', [model]) records = self.check_test_populate_values(populated, model) # should be same values as base class # and additionnal_field has own values set # iterate then pseudo random self.assertEqual(records.mapped('additionnal_field')[:20], [ 'V1', 'V2', 'V3', # iterate 'V3', 'V1', 'V2', 'V1', 'V2', 'V1', 'V2', 'V2', 'V2', 'V1', 'V1', 'V3', 'V1', 'V2', 'V2', 'V3', 'V2' # pseudorandom ]) def check_test_populate_values(self, populated, model): new = populated[model] self.assertTrue(new) records = self.env[model].browse(new) # main cartesian product self.assertEqual(records.mapped('active')[:6], [ True, True, True, False, False, False, ]) self.assertEqual(records.mapped('state')[:6], [ False, 'a', 'b', False, 'a', 'b', ]) # custom name call self.assertEqual(records.mapped('name')[:6], [ 'active_corner_0', 'active_corner_1', 'active_corner_2', 'inactive_corner_3', 'inactive_corner_4', 'inactive_corner_5', ]) self.assertIn('filling', records.mapped('name')[6]) # filling when cartesian and iterate are done # iterate then pseudo random self.assertEqual(records.mapped('some_ref')[:5], [ 0, 1, 2, 3, 4 # iterate ]) # some custom multi field generator (as cartesian product in this example) self.assertEqual(records.mapped('dependant_field_1')[:6], [ 'd1_1', 'd1_1', 'd1_1', 'd1_2', 'd1_2', 'd1_2' ]) self.assertEqual(records.mapped('dependant_field_2')[:6], [ 'd2_1', 'd2_2', 'd2_3_0', 'd2_1', 'd2_2', 'd2_3_1' ]) used_category_ids = set(records.mapped('category_id').ids[:20]) self.assertEqual(len(used_category_ids), 6) # event if id may change, with given seed, the 6 category are used generated_category_ids = set(populated['test.populate.category']) self.assertFalse(used_category_ids-generated_category_ids) # all category are the generated one self.assertFalse(hasattr(self.env.registry, 'populated_models'), 'populated_models flag has been removed from registry') return records @common.tagged('-at_install', 'post_install') class TestPopulateValidation(common.TransactionCase): """ check that all fields in _populate_factories exists """ def setUp(self): super(TestPopulateValidation, self).setUp() self.env.registry.populated_models = collections.defaultdict(list) self.addCleanup(delattr, self.env.registry, 'populated_models') def test_populate_factories(self): for model in self.env.values(): factories = model._populate_factories() or [] factories_fields = set([field_name for field_name, factory in factories if not field_name.startswith('_')]) missing = factories_fields - model._fields.keys() self.assertFalse(missing, 'Fields %s not found in model %s' % (missing, model._name)) @common.tagged('-standard', '-at_install', 'post_install', 'missing_populate') class TestPopulateMissing(common.TransactionCase): """ check that all fields in _populate_factories exists """ def setUp(self): super(TestPopulateMissing, self).setUp() self.env.registry.populated_models = collections.defaultdict(list) self.addCleanup(delattr, self.env.registry, 'populated_models') def test_populate_missing_factories(self): no_factory_models = [] for model in self.env.values(): factories = model._populate_factories() if not factories: if model._transient or model._abstract: continue ir_model = self.env['ir.model'].search([('model', '=', model._name)]) if all(module.startswith('test_') for module in ir_model.modules.split(',')): continue no_factory_models.append(model._name) else: factories_fields = next(populate.chain_factories(factories, model._name)).keys() def is_electable(field): return not field.compute \ and field.store \ and field.name not in ('create_uid', 'write_uid', 'write_date', 'create_date', 'id') \ and field.type not in ('many2many', 'one2many') electable_fields = set([key for key, field in model._fields.items() if is_electable(field)]) no_factory_fields = set(electable_fields - factories_fields) if no_factory_fields: _logger.info('Model %s has some undefined field: %s', model._name, no_factory_fields) _logger.info('No populate factories defiend for %s', no_factory_models)
46.483871
7,205
580
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class ModelA(models.Model): _name = "test_rpc.model_a" _description = "Model A" name = fields.Char(required=True) field_b1 = fields.Many2one("test_rpc.model_b", string="required field", required=True) field_b2 = fields.Many2one("test_rpc.model_b", string="restricted field", ondelete="restrict") class ModelB(models.Model): _name = "test_rpc.model_b" _description = "Model B" name = fields.Char(required=True)
29
580
313
py
PYTHON
15.0
# -*- coding: utf-8 -*- { "name": "Test RPC", "version": "1.0", "category": "Hidden/Tests", "description": """A module to test the RPC requests.""", "depends": ["base", "web"], "installable": True, "auto_install": False, "data": ["ir.model.access.csv"], 'license': 'LGPL-3', }
26.083333
313
2,878
py
PYTHON
15.0
# -*- coding: utf-8 -*- from functools import partial from odoo.tests import common, tagged from odoo.tools.misc import mute_logger @tagged('-at_install', 'post_install') class TestError(common.HttpCase): def setUp(self): super(TestError, self).setUp() uid = self.ref("base.user_admin") self.rpc = partial(self.xmlrpc_object.execute, common.get_db_name(), uid, "admin") # Reset the admin's lang to avoid breaking tests due to admin not in English self.rpc("res.users", "write", [uid], {"lang": False}) def test_01_create(self): """ Create: mandatory field not provided """ self.rpc("test_rpc.model_b", "create", {"name": "B1"}) try: with mute_logger("odoo.sql_db"): self.rpc("test_rpc.model_b", "create", {}) raise except Exception as e: self.assertIn("The operation cannot be completed:", e.faultString) self.assertIn("Create/update: a mandatory field is not set.", e.faultString) self.assertIn( "Delete: another model requires the record being deleted. If possible, archive it instead.", e.faultString, ) self.assertIn("Model: Model B (test_rpc.model_b), Field: Name (name)", e.faultString) def test_02_delete(self): """ Delete: NOT NULL and ON DELETE RESTRICT constraints """ b1 = self.rpc("test_rpc.model_b", "create", {"name": "B1"}) b2 = self.rpc("test_rpc.model_b", "create", {"name": "B2"}) self.rpc("test_rpc.model_a", "create", {"name": "A1", "field_b1": b1, "field_b2": b2}) try: with mute_logger("odoo.sql_db"): self.rpc("test_rpc.model_b", "unlink", b1) raise except Exception as e: self.assertIn("The operation cannot be completed:", e.faultString) self.assertIn( "another model requires the record being deleted. If possible, archive it instead.", e.faultString, ) self.assertIn( "Model: Model A (test_rpc.model_a), Constraint: test_rpc_model_a_field_b1_fkey", e.faultString, ) # Unlink b2 => ON DELETE RESTRICT constraint raises try: with mute_logger("odoo.sql_db"): self.rpc("test_rpc.model_b", "unlink", b2) raise except Exception as e: self.assertIn("The operation cannot be completed:", e.faultString) self.assertIn( " another model requires the record being deleted. If possible, archive it instead.", e.faultString, ) self.assertIn( "Model: Model A (test_rpc.model_a), Constraint: test_rpc_model_a_field_b2_fkey", e.faultString, )
41.114286
2,878
225
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class PublishedFoo(models.Model): _name = 'test_new_api.foo' _inherit = ['test_new_api.foo', 'test_inherit.mixin']
28.125
225
388
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'test-inherit-depends', 'version': '1.0', 'category': 'Hidden/Tests', 'description': """A module to verify the inheritance using _inherit across modules.""", 'depends': ['test_inherit', 'test_new_api'], 'installable': True, 'auto_install': False, 'license': 'LGPL-3', }
32.333333
388
764
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common class TestInheritDepends(common.TransactionCase): def test_inherited_field_external_id(self): # Module A defines model M, module B defines a mixin (abstract model) X, # and module C extends M to inherit from X. The fields on M inherited # from X should have an external ID in module C. # # Here, M is 'test_new_api.foo' and X is 'test_inherit.mixin'. field = self.env['ir.model.fields']._get('test_new_api.foo', 'published') self.assertTrue(field) self.assertEqual(field._get_external_ids(), { field.id: ['test_inherit_depends.field_test_new_api_foo__published'], })
44.941176
764
2,468
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models, fields, api from odoo.exceptions import ValidationError # We just create a new model class Unit(models.Model): _name = 'test.unit' _description = 'Test Unit' name = fields.Char('Name', required=True, translate=True) state = fields.Selection([('a', 'A'), ('b', 'B')], string='State') surname = fields.Char(compute='_compute_surname') line_ids = fields.One2many('test.unit.line', 'unit_id') readonly_name = fields.Char('Readonly Name', readonly=True) size = fields.Integer() @api.depends('name') def _compute_surname(self): for unit in self: unit.surname = unit.name or '' class UnitLine(models.Model): _name = 'test.unit.line' _description = 'Test Unit Line' name = fields.Char('Name', required=True) unit_id = fields.Many2one('test.unit', required=True) # We want to _inherits from the parent model and we add some fields # in the child object class Box(models.Model): _name = 'test.box' _inherits = {'test.unit': 'unit_id'} _description = 'Test Box' unit_id = fields.Many2one('test.unit', 'Unit', required=True, ondelete='cascade') field_in_box = fields.Char('Field1') size = fields.Integer() # We add a third level of _inherits class Pallet(models.Model): _name = 'test.pallet' _inherits = {'test.box': 'box_id'} _description = 'Test Pallet' box_id = fields.Many2one('test.box', 'Box', required=True, ondelete='cascade') field_in_pallet = fields.Char('Field2') # Another model for another test suite class AnotherUnit(models.Model): _name = 'test.another_unit' _description = 'Another Test Unit' val1 = fields.Integer('Value 1', required=True) # We want to _inherits from the parent model, add a field and check # the new field is always equals to the first one class AnotherBox(models.Model): _name = 'test.another_box' _inherits = {'test.another_unit': 'another_unit_id'} _description = 'Another Test Box' another_unit_id = fields.Many2one('test.another_unit', 'Another Unit', required=True, ondelete='cascade') val2 = fields.Integer('Value 2', required=True) @api.constrains('val1', 'val2') def _check_values(self): if any(box.val1 != box.val2 for box in self): raise ValidationError("The two values must be equals")
31.641026
2,468
440
py
PYTHON
15.0
# -*- coding: utf-8 -*- { 'name': 'test-inherits', 'version': '0.1', 'category': 'Hidden/Tests', 'description': """A module to verify the inheritance using _inherits.""", 'author': 'Camptocamp', 'website': 'http://www.camptocamp.com', 'depends': ['base'], 'data': [ 'ir.model.access.csv', 'demo_data.xml', ], 'installable': True, 'auto_install': False, 'license': 'LGPL-3', }
25.882353
440
6,581
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.tests import common from odoo.exceptions import ValidationError from odoo import Command class test_inherits(common.TransactionCase): def test_create_3_levels_inherits(self): """ Check that we can create an inherits on 3 levels """ pallet = self.env['test.pallet'].create({ 'name': 'B', 'field_in_box': 'box', 'field_in_pallet': 'pallet', }) self.assertTrue(pallet) self.assertEqual(pallet.name, 'B') self.assertEqual(pallet.field_in_box, 'box') self.assertEqual(pallet.field_in_pallet, 'pallet') def test_create_3_levels_inherits_with_defaults(self): unit = self.env['test.unit'].create({ 'name': 'U', 'state': 'a', 'size': 1, }) ctx = { 'default_state': 'b', # 'state' is inherited from 'test.unit' 'default_size': 2, # 'size' is inherited from 'test.box' } pallet = self.env['test.pallet'].with_context(ctx).create({ 'name': 'P', 'unit_id': unit.id, # grand-parent field is set }) # default 'state' should be ignored, but default 'size' should not self.assertEqual(pallet.state, 'a') self.assertEqual(pallet.size, 2) def test_read_3_levels_inherits(self): """ Check that we can read an inherited field on 3 levels """ pallet = self.env.ref('test_inherits.pallet_a') self.assertEqual(pallet.read(['name']), [{'id': pallet.id, 'name': 'Unit A'}]) def test_write_3_levels_inherits(self): """ Check that we can create an inherits on 3 levels """ pallet = self.env.ref('test_inherits.pallet_a') pallet.write({'name': 'C'}) self.assertEqual(pallet.name, 'C') def test_write_4_one2many(self): """ Check that we can write on an inherited one2many field. """ box = self.env.ref('test_inherits.box_a') box.write({'line_ids': [Command.create({'name': 'Line 1'})]}) self.assertTrue(all(box.line_ids._ids)) self.assertEqual(box.line_ids.mapped('name'), ['Line 1']) self.assertEqual(box.line_ids, box.unit_id.line_ids) box.flush() box.invalidate_cache(['line_ids']) box.write({'line_ids': [Command.create({'name': 'Line 2'})]}) self.assertTrue(all(box.line_ids._ids)) self.assertEqual(box.line_ids.mapped('name'), ['Line 1', 'Line 2']) self.assertEqual(box.line_ids, box.unit_id.line_ids) box.flush() box.invalidate_cache(['line_ids']) box.write({'line_ids': [Command.update(box.line_ids[0].id, {'name': 'First line'})]}) self.assertTrue(all(box.line_ids._ids)) self.assertEqual(box.line_ids.mapped('name'), ['First line', 'Line 2']) self.assertEqual(box.line_ids, box.unit_id.line_ids) def test_write_5_field_readonly(self): """ Check that we can write on an inherited readonly field. """ self.assertTrue(self.env['test.box']._fields['readonly_name']) box = self.env.ref('test_inherits.box_a') box.write({'readonly_name': "Superuser's box"}) self.assertEqual(box.readonly_name, "Superuser's box") self.assertEqual(box.unit_id.readonly_name, "Superuser's box") def test_ir_model_data_inherits(self): """ Check the existence of the correct ir.model.data """ IrModelData = self.env['ir.model.data'] field = IrModelData.search([('name', '=', 'field_test_unit__name')]) self.assertEqual(len(field), 1) self.assertEqual(field.module, 'test_inherits') field = IrModelData.search([('name', '=', 'field_test_box__name')]) self.assertEqual(len(field), 1) self.assertEqual(field.module, 'test_inherits') def test_constraint_inherits(self): """Validate constraints on inherits when the parent is not updated""" Model = self.env['test.another_box'] with self.assertRaises(ValidationError): another_box = Model.create({'val1': 1, 'val2': 2}) another_box = Model.create({'val1': 1, 'val2': 1}) with self.assertRaises(ValidationError): another_box.write({'val2': 2}) another_box.write({'val1': 2, 'val2': 2}) def test_constraint_inherits_parent_change(self): """Validate constraints on inherits when parent is updated too""" UnitModel = self.env['test.another_unit'] BoxModel = self.env['test.another_box'] unit1 = UnitModel.create({'val1': 1}) box = BoxModel.create({'another_unit_id': unit1.id, 'val2': 1}) unit2 = UnitModel.create({'val1': 2}) box.write({'another_unit_id': unit2.id, 'val2': 2}) unit3 = UnitModel.create({'val1': 3}) box.write({'another_unit_id': unit3.id, 'val1': 4, 'val2': 4}) unit4 = UnitModel.create({'val1': 5}) with self.assertRaises(ValidationError): box.write({'another_unit_id': unit4.id, 'val2': 6}) unit5 = UnitModel.create({'val1': 7}) with self.assertRaises(ValidationError): box.write({'another_unit_id': unit5.id, 'val1': 8, 'val2': 7}) def test_display_name(self): """ Check the 'display_name' of an inherited translated 'name'. """ self.env['res.lang']._activate_lang('fr_FR') # concrete check pallet_en = self.env['test.pallet'].create({'name': 'Bread'}) pallet_fr = pallet_en.with_context(lang='fr_FR') pallet_fr.box_id.unit_id.name = 'Pain' self.assertEqual(pallet_en.display_name, 'Bread') self.assertEqual(pallet_fr.display_name, 'Pain') # check model Unit = type(self.env['test.unit']) Box = type(self.env['test.box']) Pallet = type(self.env['test.pallet']) self.assertTrue(Unit.name.translate) self.assertIn('lang', self.registry.field_depends_context[Unit.display_name]) self.assertIn('lang', self.registry.field_depends_context[Box.display_name]) self.assertIn('lang', self.registry.field_depends_context[Pallet.display_name]) def test_multi_write_m2o_inherits(self): """Verify that an inherits m2o field can be written to in batch""" unit_foo = self.env['test.unit'].create({'name': 'foo'}) boxes = self.env['test.box'].create([{'unit_id': unit_foo.id}] * 5) unit_bar = self.env['test.unit'].create({'name': 'bar'}) boxes.unit_id = unit_bar self.assertEqual(boxes.mapped('unit_id.name'), ['bar'])
43.582781
6,581
240
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Tests that custom auth works & is not impaired by CORS', 'category': 'Hidden', 'data': [], 'license': 'LGPL-3', }
30
240
2,065
py
PYTHON
15.0
from http import HTTPStatus import odoo.tools from odoo.tests import HttpCase, HOST class TestCustomAuth(HttpCase): # suppress "WARNING: Access Error" when auth fails on json endpoints @odoo.tools.mute_logger('odoo.http') def test_json(self): # straight request should fail r = self.url_open('/test_auth_custom/json', headers={'Content-Type': 'application/json'}, data="{}") e = r.json()['error'] self.assertEqual(e['data']['name'], 'odoo.exceptions.AccessDenied') # but preflight should work self.env['base'].flush() url = "http://%s:%s/test_auth_custom/json" % (HOST, odoo.tools.config['http_port']) r = self.opener.options(url, headers={ 'Origin': 'localhost', 'Access-Control-Request-Method': 'QUX', 'Access-Control-Request-Headers': 'XYZ', }) self.assertTrue(r.ok) self.assertEqual(r.headers['Access-Control-Allow-Origin'], '*') self.assertEqual(r.headers['Access-Control-Allow-Methods'], 'POST', "json is always POST") self.assertNotIn('XYZ', r.headers['Access-Control-Allow-Headers'], "headers are ignored") def test_http(self): # straight request should fail r = self.url_open('/test_auth_custom/http') self.assertEqual(r.status_code, HTTPStatus.FORBIDDEN) # but preflight should work self.env['base'].flush() url = "http://%s:%s/test_auth_custom/http" % (HOST, odoo.tools.config['http_port']) r = self.opener.options(url, headers={ 'Origin': 'localhost', 'Access-Control-Request-Method': 'QUX', 'Access-Control-Request-Headers': 'XYZ', }) self.assertTrue(r.ok, r.text) self.assertEqual(r.headers['Access-Control-Allow-Origin'], '*') self.assertEqual(r.headers['Access-Control-Allow-Methods'], 'GET, OPTIONS', "http is whatever's on the endpoint") self.assertNotIn('XYZ', r.headers['Access-Control-Allow-Headers'], "headers are ignored")
44.891304
2,065
3,359
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Base', 'version': '1.3', 'category': 'Hidden', 'description': """ The kernel of Odoo, needed for all installation. =================================================== """, 'depends': [], 'data': [ 'data/res_bank.xml', 'data/res.lang.csv', 'data/res_lang_data.xml', 'data/res_partner_data.xml', 'data/res_currency_data.xml', 'data/res_company_data.xml', 'data/res_users_data.xml', 'data/report_paperformat_data.xml', 'data/res_country_data.xml', 'data/ir_demo_data.xml', 'data/ir_config_parameter_data.xml', 'security/base_groups.xml', 'security/base_security.xml', 'views/base_menus.xml', 'views/decimal_precision_views.xml', 'views/res_config_views.xml', 'data/res.country.state.csv', 'views/ir_actions_views.xml', 'views/ir_asset_views.xml', 'views/ir_config_parameter_views.xml', 'views/ir_cron_views.xml', 'views/ir_cron_trigger_views.xml', 'views/ir_filters_views.xml', 'views/ir_mail_server_views.xml', 'views/ir_model_views.xml', 'views/ir_attachment_views.xml', 'views/ir_rule_views.xml', 'views/ir_sequence_views.xml', 'views/ir_translation_views.xml', 'views/ir_ui_menu_views.xml', 'views/ir_ui_view_views.xml', 'views/ir_default_views.xml', 'data/ir_cron_data.xml', 'report/ir_model_report.xml', 'report/ir_model_templates.xml', 'views/ir_logging_views.xml', 'views/ir_qweb_widget_templates.xml', 'views/ir_module_views.xml', 'data/ir_module_category_data.xml', 'data/ir_module_module.xml', 'report/ir_module_reports.xml', 'report/ir_module_report_templates.xml', 'wizard/base_module_update_views.xml', 'wizard/base_language_install_views.xml', 'wizard/base_import_language_views.xml', 'wizard/base_module_upgrade_views.xml', 'wizard/base_module_uninstall_views.xml', 'wizard/base_export_language_views.xml', 'wizard/base_update_translations_views.xml', 'wizard/base_partner_merge_views.xml', 'data/ir_actions_data.xml', 'data/ir_demo_failure_data.xml', 'views/ir_profile_views.xml', 'views/res_company_views.xml', 'views/res_lang_views.xml', 'views/res_partner_views.xml', 'views/res_bank_views.xml', 'views/res_country_views.xml', 'views/res_currency_views.xml', 'views/res_users_views.xml', 'views/ir_property_views.xml', 'views/res_config_settings_views.xml', 'views/report_paperformat_views.xml', 'views/onboarding_views.xml', 'security/ir.model.access.csv', ], 'demo': [ 'data/res_company_demo.xml', 'data/res_users_demo.xml', 'data/res_partner_bank_demo.xml', 'data/res_currency_rate_demo.xml', 'data/res_bank_demo.xml', 'data/res_partner_demo.xml', 'data/res_partner_image_demo.xml', ], 'test': [], 'installable': True, 'auto_install': True, 'post_init_hook': 'post_init', 'license': 'LGPL-3', }
35.357895
3,359
1,561
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import models from odoo.tools import populate _logger = logging.getLogger(__name__) class Users(models.Model): _inherit = "res.users" _populate_sizes = { 'small': 10, 'medium': 1000, 'large': 10000, } _populate_dependencies = ["res.partner"] def _populate_factories(self): def generate_partner_id(iterator, *args): partner_factories = self.env['res.partner']._populate_factories() partner_generator = populate.chain_factories(partner_factories, self._name) for dependant_values in partner_generator: values = next(iterator) yield {**dependant_values, **values, '__complete': values['__complete']} def get_company_ids(values, **kwargs): return [(6, 0, [values['company_id']])] return [ ('active', populate.cartesian([True, False], [0.9, 0.1])), ('partner_id', generate_partner_id), ('company_id', populate.randomize(self.env.registry.populated_models['res.company'])), ('company_ids', populate.compute(get_company_ids)), ('login', populate.constant('user_login_{counter}')), ('name', populate.constant('user_{counter}')), ] def _populate(self, size): self = self.with_context(no_reset_password=True) # avoid sending reset password email return super(Users, self)._populate(size)
35.477273
1,561
1,766
py
PYTHON
15.0
import collections import logging from odoo import models, Command from odoo.tools import populate _logger = logging.getLogger(__name__) class Partner(models.Model): _inherit = "res.company" _populate_sizes = { 'small': 5, 'medium': 10, 'large': 50, } def _populate_factories(self): # Activate currency to avoid fail iterator (self.env.ref('base.USD') | self.env.ref('base.EUR')).active = True # remaining: paperformat_id, parent_id, partner_id, favicon, font, report_header, external_report_layout_id, report_footer def get_name(values=None, counter=0, **kwargs): return 'company_%s_%s' % (counter, self.env['res.currency'].browse(values['currency_id']).name) active_currencies = self.env['res.currency'].search([('active', '=', True)]).ids return [ ('name', populate.constant('company_{counter}')), ('sequence', populate.randint(0, 100)), ('company_registry', populate.iterate([False, 'company_registry_{counter}'])), ('base_onboarding_company_state', populate.iterate( [False] + [e[0] for e in type(self).base_onboarding_company_state.selection])), ('primary_color', populate.iterate([False, '', '#ff7755'])), ('secondary_color', populate.iterate([False, '', '#ffff55'], seed='primary_color')), ('currency_id', populate.iterate(active_currencies)), ('name', populate.compute(get_name)), ] def _populate(self, size): records = super()._populate(size) self.env.ref('base.user_admin').write({'company_ids': [Command.link(rec.id) for rec in records]}) # add all created companies on user admin return records
41.069767
1,766
1,173
py
PYTHON
15.0
from dateutil.relativedelta import relativedelta from datetime import date from odoo import models, Command from odoo.tools import populate class ResCurrencyRate(models.Model): _inherit = "res.currency.rate" _populate_sizes = { 'small': 100, 'medium': 1000, 'large': 10000, } def _populate_factories(self): def get_rate(random, values, **kwargs): basis = sum( ord(c) for c in self.env['res.currency'].browse(values['currency_id']).name ) % 20 return basis + random.uniform(-1, 1) def get_date(random, values, **kwargs): return date(2020, 1, 1) - relativedelta(days=kwargs['counter']) company_ids = self.env['res.company'].search([ ('id', 'in', self.env.registry.populated_models['res.company']), ]) return [ ('currency_id', populate.randomize(self.env['res.currency'].search([('active', '=', True)]).ids)), ('company_id', populate.randomize(company_ids.ids)), ('name', populate.compute(get_date)), ('rate', populate.compute(get_rate)), ]
32.583333
1,173
8,505
py
PYTHON
15.0
import collections import logging from odoo import models from odoo.tools import populate _logger = logging.getLogger(__name__) class Partner(models.Model): _inherit = "res.partner" _populate_dependencies = ["res.company", "res.partner.industry"] _populate_sizes = { 'small': 100, 'medium': 2000, 'large': 100000, } def _populate_factories(self): # example of more complex generator composed of multiple sub generators # this define one subgenerator per "country" address_factories_groups = [ [ # Falsy, 2 records ('street', populate.iterate([False, ''])), ('street2', populate.iterate([False, ''])), ('city', populate.iterate([False, ''])), ('zip', populate.iterate([False, ''])), ('country_id', populate.iterate([False])), ], [ # BE, 1 record ('street', populate.iterate(['Boulevard Tintin {counter}'])), ('city', populate.iterate(['Brussels'])), ('zip', populate.iterate([1020])), ('country_id', populate.iterate([self.env.ref('base.be').id])), ], [ # US, 3 records ('street', populate.iterate(['Main street', '3th street {counter}', False])), ('street2', populate.iterate([False, '', 'Behind the tree {counter}'], [90, 5, 5])), ('city', populate.randomize(['Sans Fransisco', 'Los Angeles', '', False])), ('zip', populate.iterate([False, '', '50231'])), ('country_id', populate.iterate([self.env.ref('base.us').id])), ], [ # IN, 2 records ('street', populate.iterate(['Main Street', 'Some Street {counter}'])), ('city', populate.iterate(['ગાંધીનગર (Gandhinagar)'])), ('zip', populate.randomize(['382002', '382008'])), ('country_id', populate.randomize([self.env.ref('base.in').id])), ], [ # other corner cases, 4 records ('street', populate.iterate(['万泉寺村', 'საბჭოს სკვერი {counter}', '10th Street {counter}'])), ('city', populate.iterate(['北京市', 'თბილისი', 'دبي'])), ('zip', populate.iterate([False, 'UF47', '0', '10201'])), ('country_id', populate.randomize([False] + self.env['res.country'].search([]).ids)), ] ] def generate_address(iterator, *args): address_generators = [populate.chain_factories(address_factories, self._name) for address_factories in address_factories_groups] # first, exhaust all address_generators for adress_generator in address_generators: for adress_values in adress_generator: if adress_values['__complete']: break values = next(iterator) # only consume main iterator if usefull yield {**values, **adress_values} # then, go pseudorandom between generators r = populate.Random('res.partner+address_generator_selector') for values in iterator: adress_generator = r.choice(address_generators) adress_values = next(adress_generator) yield {**adress_values, **values} # state based on country states = self.env['res.country.state'].search([]) states_per_country = collections.defaultdict(list) for state in states: states_per_country[state.country_id.id].append(state.id) def get_state(values=None, random=None, **kwargs): country_id = values['country_id'] if not country_id: return False return random.choice([False] + states_per_country[country_id]) def get_name(values=None, counter=0, **kwargs): is_company = values['is_company'] complete = values['__complete'] return '%s_%s_%s' % ('company' if is_company else 'partner', int(complete), counter) industry_ids = self.env.registry.populated_models['res.partner.industry'] company_ids = self.env.registry.populated_models['res.company'] # not defined fields: vat, partner_longitude, date, partner_latitude, color, company_name, employee, lang, user_id return [ ('active', populate.cartesian([True, False], [0.9, 0.1])), ('employee', populate.cartesian([True, False], [0.1, 0.9])), ('email', populate.iterate( [False, '', 'email{counter}@example.com', '<contact 万> contact{counter}@anotherexample.com', 'invalid_email'])), ('type', populate.constant('contact')), # todo add more logic, manage 'invoice', 'delivery', 'other', 'private' ('is_company', populate.iterate([True, False], [0.05, 0.95])), ('_address', generate_address), ('state_id', populate.compute(get_state)), ('phone', populate.randomize([False, '', '+3212345678', '003212345678', '12345678'])), ('mobile', populate.randomize([False, '', '+32412345678', '0032412345678', '412345678'])), ('title', populate.randomize(self.env['res.partner.title'].search([]).ids)), ('function', populate.randomize( [False, '', 'President of Sales', 'Senior Consultant', 'Product owner', 'Functional Consultant', 'Chief Executive Officer'], [50, 10, 2, 20, 5, 10, 1])), ('tz', populate.randomize([tz for tz in self.env['res.partner']._fields['tz'].get_values(self.env)])), ('website', populate.randomize([False, '', 'http://www.example.com'])), ('credit_limit', populate.randomize( [False, 0, 500, 2500, 5000, 10000], [50, 30, 5, 5, 5, 5])), ('name', populate.compute(get_name)), # keep after is_company ('ref', populate.randomize([False, '', '{counter}', 'p-{counter}'], [10, 10, 30, 50])), ('industry_id', populate.randomize( [False] + industry_ids, [0.5] + ([0.5/(len(industry_ids) or 1)] * len(industry_ids)))), ('comment', populate.iterate([False, '', 'This is a partner {counter}'])), ('company_id', populate.iterate( [False, self.env.ref('base.main_company').id] + company_ids, [1, 1] + [1/(len(company_ids) or 1)]*len(company_ids))), ('parent_id', populate.constant(False)), # will be setted in _populate override ] def _populate(self, size): records = super()._populate(size) # set parent_ids self._populate_set_companies(records) return records def _populate_set_companies(self, records): _logger.info('Setting companies') r_company = populate.Random('res.partner+company_has_partners') r_partner = populate.Random('res.partner+partner_has_company') r_company_pick = populate.Random('res.partner+partner_company_pick=') companies = records.filtered(lambda p: p.is_company and r_company.getrandbits(1)) # 50% change to have partners partners = records.filtered(lambda p: not p.is_company and r_partner.getrandbits(1)) # 50% change to have a company companies_partners = collections.defaultdict(lambda: self.env['res.partner']) for partner in partners: companies_partners[r_company_pick.choice(companies)] |= partner # batching company write improves performances a lot (~40% faster for total partner creation). for count, (company, partners) in enumerate(companies_partners.items(), start=1): if count % 100 == 0: _logger.info('Setting company: %s/%s', count, len(companies)) partners.write({'parent_id': company.id}) partners._onchange_company_id() class ResPartnerIndustry(models.Model): _inherit = "res.partner.industry" _populate_sizes = { 'small': 15, 'medium': 60, 'large': 300, } def _populate_factories(self): return [ ('active', populate.cartesian([False, True], [0.1, 0.9])), ('name', populate.cartesian( [False, 'Industry name', 'Industry name {counter}'], [0.08, 0.01, 0.9])), ('full_name', populate.iterate([False, 'Industry full name %s'])) ]
50.190476
8,432
3,883
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import exceptions from odoo.tests.common import TransactionCase, tagged _logger = logging.getLogger(__name__) class TestResConfig(TransactionCase): def setUp(self): super(TestResConfig, self).setUp() self.ResConfig = self.env['res.config.settings'] # Define the test values self.menu_xml_id = 'base.menu_action_res_users' self.full_field_name = 'res.partner.lang' self.error_msg = "WarningRedirect test string: %(field:res.partner.lang)s - %(menu:base.menu_action_res_users)s." self.error_msg_wo_menu = "WarningRedirect test string: %(field:res.partner.lang)s." # Note: see the get_config_warning() doc for a better example # Fetch the expected values menu = self.env.ref(self.menu_xml_id) model_name, field_name = self.full_field_name.rsplit('.', 1) self.expected_path = menu.complete_name self.expected_action_id = menu.action.id self.expected_name = self.env[model_name].fields_get([field_name])[field_name]['string'] self.expected_final_error_msg = self.error_msg % { 'field:res.partner.lang': self.expected_name, 'menu:base.menu_action_res_users': self.expected_path } self.expected_final_error_msg_wo_menu = self.error_msg_wo_menu % { 'field:res.partner.lang': self.expected_name, } def test_00_get_option_path(self): """ The get_option_path() method should return a tuple containing a string and an integer """ res = self.ResConfig.get_option_path(self.menu_xml_id) # Check types self.assertIsInstance(res, tuple) self.assertEqual(len(res), 2, "The result should contain 2 elements") self.assertIsInstance(res[0], str) self.assertIsInstance(res[1], int) # Check returned values self.assertEqual(res[0], self.expected_path) self.assertEqual(res[1], self.expected_action_id) def test_10_get_option_name(self): """ The get_option_name() method should return a string """ res = self.ResConfig.get_option_name(self.full_field_name) # Check type self.assertIsInstance(res, str) # Check returned value self.assertEqual(res, self.expected_name) def test_20_get_config_warning(self): """ The get_config_warning() method should return a RedirectWarning """ res = self.ResConfig.get_config_warning(self.error_msg) # Check type self.assertIsInstance(res, exceptions.RedirectWarning) # Check returned value self.assertEqual(res.args[0], self.expected_final_error_msg) self.assertEqual(res.args[1], self.expected_action_id) def test_30_get_config_warning_wo_menu(self): """ The get_config_warning() method should return a Warning exception """ res = self.ResConfig.get_config_warning(self.error_msg_wo_menu) # Check type self.assertIsInstance(res, exceptions.UserError) # Check returned value self.assertEqual(res.args[0], self.expected_final_error_msg_wo_menu) @tagged('post_install', '-at_install') class TestResConfigExecute(TransactionCase): def test_01_execute_res_config(self): """ Try to create and execute all res_config models. Target settings that can't be loaded or saved and avoid remaining methods `get_default_foo` or `set_foo` that won't be executed is foo != `fields` """ all_config_settings = self.env['ir.model'].search([('name', 'like', 'config.settings')]) for config_settings in all_config_settings: _logger.info("Testing %s" % (config_settings.name)) self.env[config_settings.name].create({}).execute()
39.222222
3,883
14,117
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import base64 import binascii import hashlib import io import os from PIL import Image from odoo.exceptions import AccessError from odoo.tests.common import TransactionCase from odoo.tools import image_to_base64 HASH_SPLIT = 2 # FIXME: testing implementations detail is not a good idea class TestIrAttachment(TransactionCase): def setUp(self): super(TestIrAttachment, self).setUp() self.Attachment = self.env['ir.attachment'] self.filestore = self.Attachment._filestore() # Blob1 self.blob1 = b'blob1' self.blob1_b64 = base64.b64encode(self.blob1) self.blob1_hash = hashlib.sha1(self.blob1).hexdigest() self.blob1_fname = self.blob1_hash[:HASH_SPLIT] + '/' + self.blob1_hash # Blob2 self.blob2 = b'blob2' self.blob2_b64 = base64.b64encode(self.blob2) def assertApproximately(self, value, expectedSize, delta=1): # we don't used bin_size in context, because on write, the cached value is the data and not # the size, so we need on each write to invalidate cache if we really want to get the size. try: value = base64.b64decode(value.decode()) except UnicodeDecodeError: pass size = len(value) / 1024 # kb self.assertAlmostEqual(size, expectedSize, delta=delta) def test_01_store_in_db(self): # force storing in database self.env['ir.config_parameter'].set_param('ir_attachment.location', 'db') # 'ir_attachment.location' is undefined test database storage a1 = self.Attachment.create({'name': 'a1', 'raw': self.blob1}) self.assertEqual(a1.datas, self.blob1_b64) self.assertEqual(a1.db_datas, self.blob1) def test_02_store_on_disk(self): a2 = self.Attachment.create({'name': 'a2', 'raw': self.blob1}) self.assertEqual(a2.store_fname, self.blob1_fname) self.assertTrue(os.path.isfile(os.path.join(self.filestore, a2.store_fname))) def test_03_no_duplication(self): a2 = self.Attachment.create({'name': 'a2', 'raw': self.blob1}) a3 = self.Attachment.create({'name': 'a3', 'raw': self.blob1}) self.assertEqual(a3.store_fname, a2.store_fname) def test_04_keep_file(self): a2 = self.Attachment.create({'name': 'a2', 'raw': self.blob1}) a3 = self.Attachment.create({'name': 'a3', 'raw': self.blob1}) a2_fn = os.path.join(self.filestore, a2.store_fname) a3.unlink() self.assertTrue(os.path.isfile(a2_fn)) def test_05_change_data_change_file(self): a2 = self.Attachment.create({'name': 'a2', 'raw': self.blob1}) a2_store_fname1 = a2.store_fname a2_fn = os.path.join(self.filestore, a2_store_fname1) self.assertTrue(os.path.isfile(a2_fn)) a2.write({'raw': self.blob2}) a2_store_fname2 = a2.store_fname self.assertNotEqual(a2_store_fname1, a2_store_fname2) a2_fn = os.path.join(self.filestore, a2_store_fname2) self.assertTrue(os.path.isfile(a2_fn)) def test_07_write_mimetype(self): """ Tests the consistency of documents' mimetypes """ Attachment = self.Attachment.with_user(self.env.ref('base.user_demo').id) a2 = Attachment.create({'name': 'a2', 'datas': self.blob1_b64, 'mimetype': 'image/png'}) self.assertEqual(a2.mimetype, 'image/png', "the new mimetype should be the one given on write") a3 = Attachment.create({'name': 'a3', 'datas': self.blob1_b64, 'mimetype': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'}) self.assertEqual(a3.mimetype, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', "should preserve office mime type") def test_08_neuter_xml_mimetype(self): """ Tests that potentially harmful mimetypes (XML mimetypes that can lead to XSS attacks) are converted to text """ Attachment = self.Attachment.with_user(self.env.ref('base.user_demo').id) document = Attachment.create({'name': 'document', 'datas': self.blob1_b64}) document.write({'datas': self.blob1_b64, 'mimetype': 'text/xml'}) self.assertEqual(document.mimetype, 'text/plain', "XML mimetype should be forced to text") document.write({'datas': self.blob1_b64, 'mimetype': 'image/svg+xml'}) self.assertEqual(document.mimetype, 'text/plain', "SVG mimetype should be forced to text") document.write({'datas': self.blob1_b64, 'mimetype': 'text/html'}) self.assertEqual(document.mimetype, 'text/plain', "HTML mimetype should be forced to text") document.write({'datas': self.blob1_b64, 'mimetype': 'application/xhtml+xml'}) self.assertEqual(document.mimetype, 'text/plain', "XHTML mimetype should be forced to text") def test_09_dont_neuter_xml_mimetype_for_admin(self): """ Admin user does not have a mime type filter """ document = self.Attachment.create({'name': 'document', 'datas': self.blob1_b64}) document.write({'datas': self.blob1_b64, 'mimetype': 'text/xml'}) self.assertEqual(document.mimetype, 'text/xml', "XML mimetype should not be forced to text, for admin user") def test_10_image_autoresize(self): Attachment = self.env['ir.attachment'] img_bin = io.BytesIO() dir_path = os.path.dirname(os.path.realpath(__file__)) with Image.open(os.path.join(dir_path, 'odoo.jpg'), 'r') as logo: img = Image.new('RGB', (4000, 2000), '#4169E1') img.paste(logo) img.save(img_bin, 'JPEG') img_encoded = image_to_base64(img, 'JPEG') img_bin = img_bin.getvalue() fullsize = 124.99 #################################### ### test create/write on 'datas' #################################### attach = Attachment.with_context(image_no_postprocess=True).create({ 'name': 'image', 'datas': img_encoded, }) self.assertApproximately(attach.datas, fullsize) # no resize, no compression attach = attach.with_context(image_no_postprocess=False) attach.datas = img_encoded self.assertApproximately(attach.datas, 12.06) # default resize + default compression # resize + default quality (80) self.env['ir.config_parameter'].set_param('base.image_autoresize_max_px', '1024x768') attach.datas = img_encoded self.assertApproximately(attach.datas, 3.71) # resize + quality 50 self.env['ir.config_parameter'].set_param('base.image_autoresize_quality', '50') attach.datas = img_encoded self.assertApproximately(attach.datas, 3.57) # no resize + no quality implicit self.env['ir.config_parameter'].set_param('base.image_autoresize_max_px', '0') attach.datas = img_encoded self.assertApproximately(attach.datas, fullsize) # Check that we only compress quality when we resize. We avoid to compress again during a new write. # no resize + quality -> should have no effect self.env['ir.config_parameter'].set_param('base.image_autoresize_max_px', '10000x10000') self.env['ir.config_parameter'].set_param('base.image_autoresize_quality', '50') attach.datas = img_encoded self.assertApproximately(attach.datas, fullsize) #################################### ### test create/write on 'raw' #################################### # reset default ~ delete self.env['ir.config_parameter'].search([('key', 'ilike', 'base.image_autoresize%')]).unlink() attach = Attachment.with_context(image_no_postprocess=True).create({ 'name': 'image', 'raw': img_bin, }) self.assertApproximately(attach.raw, fullsize) # no resize, no compression attach = attach.with_context(image_no_postprocess=False) attach.raw = img_bin self.assertApproximately(attach.raw, 12.06) # default resize + default compression # resize + default quality (80) self.env['ir.config_parameter'].set_param('base.image_autoresize_max_px', '1024x768') attach.raw = img_bin self.assertApproximately(attach.raw, 3.71) # resize + no quality self.env['ir.config_parameter'].set_param('base.image_autoresize_quality', '0') attach.raw = img_bin self.assertApproximately(attach.raw, 4.09) # resize + quality 50 self.env['ir.config_parameter'].set_param('base.image_autoresize_quality', '50') attach.raw = img_bin self.assertApproximately(attach.raw, 3.57) # no resize + no quality implicit self.env['ir.config_parameter'].set_param('base.image_autoresize_max_px', '0') attach.raw = img_bin self.assertApproximately(attach.raw, fullsize) # no resize of gif self.env['ir.config_parameter'].set_param('base.image_autoresize_max_px', '0x0') gif_bin = b'GIF89a\x01\x00\x01\x00\x00\xff\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x00;' attach.raw = gif_bin self.assertEqual(attach.raw, gif_bin) def test_11_copy(self): """ Copying an attachment preserves the data """ document = self.Attachment.create({'name': 'document', 'datas': self.blob2_b64}) document2 = document.copy({'name': "document (copy)"}) self.assertEqual(document2.name, "document (copy)") self.assertEqual(document2.datas, document.datas) self.assertEqual(document2.db_datas, document.db_datas) self.assertEqual(document2.store_fname, document.store_fname) self.assertEqual(document2.checksum, document.checksum) document3 = document.copy({'datas': self.blob1_b64}) self.assertEqual(document3.datas, self.blob1_b64) self.assertEqual(document3.raw, self.blob1) self.assertTrue(self.filestore) # no data in db but has a store_fname self.assertEqual(document3.db_datas, False) self.assertEqual(document3.store_fname, self.blob1_fname) self.assertEqual(document3.checksum, self.blob1_hash) class TestPermissions(TransactionCase): def setUp(self): super().setUp() # replace self.env(uid=1) with an actual user environment so rules apply self.env = self.env(user=self.env.ref('base.user_demo')) self.Attachments = self.env['ir.attachment'] # create a record with an attachment and a rule allowing Read access # but preventing Create, Update, or Delete record = self.Attachments.create({'name': 'record1'}) self.vals = {'name': 'attach', 'res_id': record.id, 'res_model': record._name} a = self.attachment = self.Attachments.create(self.vals) # prevent create, write and unlink accesses on record self.rule = self.env['ir.rule'].sudo().create({ 'name': 'remove access to record %d' % record.id, 'model_id': self.env['ir.model']._get_id(record._name), 'domain_force': "[('id', '!=', %s)]" % record.id, 'perm_read': False }) a.flush() a.invalidate_cache(ids=a.ids) def test_no_read_permission(self): """If the record can't be read, the attachment can't be read either """ # check that the information can be read out of the box self.attachment.datas # prevent read access on record self.rule.perm_read = True self.attachment.invalidate_cache(ids=self.attachment.ids) with self.assertRaises(AccessError): self.attachment.datas def test_with_write_permissions(self): """With write permissions to the linked record, attachment can be created, updated, or deleted (or copied). """ # enable write permission on linked record self.rule.perm_write = False attachment = self.Attachments.create(self.vals) attachment.copy() attachment.write({'raw': b'test'}) attachment.unlink() def test_basic_modifications(self): """Lacking write access to the linked record means create, update, and delete on the attachment are forbidden """ with self.assertRaises(AccessError): self.Attachments.create(self.vals) with self.assertRaises(AccessError): self.attachment.write({'raw': b'yay'}) with self.assertRaises(AccessError): self.attachment.unlink() with self.assertRaises(AccessError): self.attachment.copy() def test_cross_record_copies(self): """Copying attachments between records (in the same model or not) adds wrinkles as the ACLs may diverge a lot more """ # create an other unwritable record in a different model unwritable = self.env['res.users.log'].create({}) with self.assertRaises(AccessError): unwritable.write({}) # checks unwritability # create a writable record in the same model writable = self.Attachments.create({'name': 'yes'}) writable.name = 'canwrite' # checks for writeability # can copy from a record with read permissions to one with write permissions copied = self.attachment.copy({'res_model': writable._name, 'res_id': writable.id}) # can copy to self given write permission copied.copy() # can not copy back to record without write permission with self.assertRaises(AccessError): copied.copy({'res_id': self.vals['res_id']}) # can not copy to a record without write permission with self.assertRaises(AccessError): self.attachment.copy({'res_model': unwritable._name, 'res_id': unwritable.id}) # even from a record with write permissions with self.assertRaises(AccessError): copied.copy({'res_model': unwritable._name, 'res_id': unwritable.id})
44.253918
14,117
2,405
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import TransactionCase, tagged, Form @tagged('-at_install', 'post_install') class TestFormCreate(TransactionCase): """ Test that the basic Odoo models records can be created on the interface. """ def test_create_res_partner(self): partner_form = Form(self.env['res.partner']) partner_form.name = 'a partner' # YTI: Clean that brol if hasattr(self.env['res.partner'], 'property_account_payable_id'): property_account_payable_id = self.env['account.account'].create({ 'name': 'Test Account', 'user_type_id': self.env.ref('account.data_account_type_payable').id, 'code': 'TestAccountPayable', 'reconcile': True }) property_account_receivable_id = self.env['account.account'].create({ 'name': 'Test Account', 'user_type_id': self.env.ref('account.data_account_type_receivable').id, 'code': 'TestAccountReceivable', 'reconcile': True }) partner_form.property_account_payable_id = property_account_payable_id partner_form.property_account_receivable_id = property_account_receivable_id partner_form.save() def test_create_res_users(self): user_form = Form(self.env['res.users']) user_form.login = 'a user login' user_form.name = 'a user name' user_form.save() def test_create_res_company(self): company_form = Form(self.env['res.company']) company_form.name = 'a company' company_form.save() def test_create_res_group(self): group_form = Form(self.env['res.groups']) group_form.name = 'a group' group_form.save() def test_create_res_bank(self): bank_form = Form(self.env['res.bank']) bank_form.name = 'a bank' bank_form.save() def test_create_res_country(self): country_form = Form(self.env['res.country']) country_form.name = 'a country' country_form.code = 'AA' country_form.save() def test_create_res_lang(self): lang_form = Form(self.env['res.lang']) lang_form.name = 'a lang name' lang_form.code = 'a lang code' lang_form.save()
36.439394
2,405