From 653c7d6df1472e4f6bdde2272b0ee6ef047ee483 Mon Sep 17 00:00:00 2001 From: Lee Trager Date: Thu, 21 May 2020 12:18:26 -0700 Subject: [PATCH] Allow models to be iterable. (#396) Signed-off-by: Lee Trager Co-authored-by: Lee Trager --- pylxd/models/_model.py | 4 ++++ pylxd/tests/models/test_model.py | 8 ++++++++ 2 files changed, 12 insertions(+) diff --git a/pylxd/models/_model.py b/pylxd/models/_model.py index 8702f62c..ce8b7025 100644 --- a/pylxd/models/_model.py +++ b/pylxd/models/_model.py @@ -162,6 +162,10 @@ def __setattr__(self, name, value): self.__dirty__.add(name) return super(Model, self).__setattr__(name, value) + def __iter__(self): + for attr in self.__attributes__.keys(): + yield attr, getattr(self, attr) + @property def dirty(self): return len(self.__dirty__) > 0 diff --git a/pylxd/tests/models/test_model.py b/pylxd/tests/models/test_model.py index 24ecb147..f25cbc8d 100644 --- a/pylxd/tests/models/test_model.py +++ b/pylxd/tests/models/test_model.py @@ -150,6 +150,14 @@ def test_unset_attribute_sync(self): self.assertEqual(1000, item.age) + def test_iter(self): + """Test models can be iterated over.""" + item = Item(self.client, name='an-item') + + self.assertDictEqual( + {'name': 'an-item', 'age': 1000, 'data': {'key': 'val'}}, + dict(item)) + def test_sync(self): """A sync will update attributes from the server.""" item = Item(self.client, name='an-item')