Skip to content

Commit 1b53e15

Browse files
committed
Add get (by path) method for complex objects.
1 parent 20abb82 commit 1b53e15

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

c8y_api/model/_base.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,30 @@ def __iadd__(self, other):
400400
def __contains__(self, name):
401401
return name in self.fragments
402402

403+
def get(self, path: str, default=None):
404+
"""Get a fragment/value by path.
405+
406+
Args:
407+
path (str): A fragment/value path in dot notation, e.g.
408+
"c8y_Firmware.version"
409+
default: Sensible default if the path is not defined.
410+
411+
Returns:
412+
The fragment/value specified via the path or the default value
413+
if the path is not defined.
414+
"""
415+
segments = path.split('.')
416+
value = self
417+
for segment in segments:
418+
if segment in value:
419+
value = value[segment]
420+
continue
421+
if hasattr(value, segment):
422+
return value.__getattribute__(segment)
423+
else:
424+
return default
425+
return value
426+
403427
@deprecated
404428
def set_attribute(self, name, value):
405429
# pylint: disable=missing-function-docstring

tests/model/test_base.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,23 @@ def test_complexobject_instantiation_and_formatting():
232232
assert obj._to_json(only_updated=True) == expected_diff_json
233233

234234

235+
def test_complexobject_get():
236+
237+
obj = ComplexTestObject(
238+
field='field value',
239+
fixed_field=123,
240+
c8y_simple=True,
241+
c8y_complex={'a': 'valueA', 'b': 'valueB'},
242+
additionalField=True,
243+
additionalFragment={'value1': "A", 'value2': "B"}
244+
)
245+
246+
assert obj.get('field') == obj.field
247+
assert obj.get('c8y_complex.a') == obj.c8y_complex.a
248+
assert obj.get('not') is None
249+
assert obj.get('not', 'default') == 'default'
250+
251+
235252
@pytest.mark.parametrize('page_size, num_all, limit, expected', [
236253
(10, 100, 100, 100), # exact
237254
(10, 200, 100, 100), # limit hit

0 commit comments

Comments
 (0)