From 4a1f2c938b87f5527d48e180fe4711ff690be882 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Krier?= Date: Wed, 17 Jun 2020 00:30:53 +0200 Subject: [PATCH] Use different hash for records without id In order to have store them efficiently in dictionary, we generate a different hash for each unsaved record by using the instance id. issue9240 review295421002 --- trytond/model/model.py | 2 +- trytond/tests/test_model.py | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/trytond/model/model.py b/trytond/model/model.py index 993c296eb3..308c6b2720 100644 --- a/trytond/model/model.py +++ b/trytond/model/model.py @@ -316,7 +316,7 @@ class Model(URLMixin, PoolBase, metaclass=ModelMeta): return not self == other def __hash__(self): - return hash((self.__name__, self.id)) + return hash((self.__name__, id(self) if self.id is None else self.id)) def __bool__(self): return True diff --git a/trytond/tests/test_model.py b/trytond/tests/test_model.py index 1ecec11be9..09561fb8e2 100644 --- a/trytond/tests/test_model.py +++ b/trytond/tests/test_model.py @@ -30,6 +30,30 @@ class ModelTestCase(unittest.TestCase): self.assertEqual( repr(record), "Pool().get('test.model')(%s)" % record.id) + @with_transaction() + def test_hash_with_id(self): + "Test hash with id" + pool = Pool() + Model = pool.get('test.model') + + record1 = Model(id=1) + record1bis = Model(id=1) + record2 = Model(id=2) + + self.assertEqual(hash(record1), hash(record1bis)) + self.assertNotEqual(hash(record1), hash(record2)) + + @with_transaction() + def test_hash_without_id(self): + "Test hash without id" + pool = Pool() + Model = pool.get('test.model') + + record1 = Model() + record2 = Model() + + self.assertNotEqual(hash(record1), hash(record2)) + @with_transaction() def test_init_parent(self): "Test __init__ with _parent_"