1
0
mirror of https://github.com/openSUSE/osc.git synced 2025-09-07 05:38:43 +02:00

Implement do_snapshot() and has_changed() methods to determine changes in BaseModel

This commit is contained in:
2024-02-13 09:40:53 +01:00
parent 00d2192bcd
commit ab36108871
3 changed files with 44 additions and 1 deletions

View File

@@ -385,8 +385,16 @@ class BaseModel(metaclass=ModelMeta):
for name, field in self.__fields__.items():
field.validate_type(getattr(self, name))
self._snapshot = {} # copy of ``self.dict()`` so we can determine if the object has changed later on
self.do_snapshot()
self._allow_new_attributes = False
def __eq__(self, other):
if type(self) != type(other):
return False
return self.dict() == other.dict()
def dict(self):
result = {}
for name, field in self.__fields__.items():
@@ -402,6 +410,18 @@ class BaseModel(metaclass=ModelMeta):
return result
def do_snapshot(self):
"""
Save ``self.dict()`` result as a new starting point for detecting changes in the object data.
"""
self._snapshot = self.dict()
def has_changed(self):
"""
Determine if the object data has changed since its creation or the last snapshot.
"""
return self.dict() != self._snapshot
class XmlModel(BaseModel):
XML_TAG = None

View File

@@ -517,7 +517,7 @@ class TestConf(unittest.TestCase):
conf1 = osc.conf.Options()
conf2 = osc.conf.Options()
self.assertNotEqual(conf1, conf2)
self.assertEqual(conf1, conf2) # models are compared by their contents now
self.assertNotEqual(id(conf1), id(conf2))
self.assertNotEqual(id(conf1.api_host_options), id(conf2.api_host_options))

View File

@@ -316,6 +316,29 @@ class Test(unittest.TestCase):
self.assertEqual(m.quiet, False)
self.assertEqual(m.verbose, True)
def test_has_changed(self):
class TestSubmodel(BaseModel):
text: str = Field(default="default")
class TestModel(BaseModel):
field: Optional[List[TestSubmodel]] = Field(default=[])
m = TestModel()
self.assertFalse(m.has_changed())
# a new instance of empty list
m.field = []
self.assertFalse(m.has_changed())
m.field = [{"text": "one"}, {"text": "two"}]
self.assertTrue(m.has_changed())
m.do_snapshot()
# a new instance of list with new instances of objects with the same data
m.field = [{"text": "one"}, {"text": "two"}]
self.assertFalse(m.has_changed())
if __name__ == "__main__":
unittest.main()