summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--python/vyos/util.py15
-rw-r--r--src/tests/test_dict_search.py10
2 files changed, 18 insertions, 7 deletions
diff --git a/python/vyos/util.py b/python/vyos/util.py
index e4de56cdb..e2f4b8fc4 100644
--- a/python/vyos/util.py
+++ b/python/vyos/util.py
@@ -630,18 +630,21 @@ def find_device_file(device):
return None
-def dict_search(path, dict):
- """ Traverse Python dictionary (dict) delimited by dot (.).
+def dict_search(path, my_dict):
+ """ Traverse Python dictionary (my_dict) delimited by dot (.).
Return value of key if found, None otherwise.
- This is faster implementation then jmespath.search('foo.bar', dict)"""
+ This is faster implementation then jmespath.search('foo.bar', my_dict)"""
+ if not isinstance(my_dict, dict) or not path:
+ return None
+
parts = path.split('.')
inside = parts[:-1]
if not inside:
- if path not in dict:
+ if path not in my_dict:
return None
- return dict[path]
- c = dict
+ return my_dict[path]
+ c = my_dict
for p in parts[:-1]:
c = c.get(p, {})
return c.get(parts[-1], None)
diff --git a/src/tests/test_dict_search.py b/src/tests/test_dict_search.py
index 6a0fc74ad..991722f0f 100644
--- a/src/tests/test_dict_search.py
+++ b/src/tests/test_dict_search.py
@@ -20,6 +20,7 @@ from vyos.util import dict_search
data = {
'string': 'fooo',
'nested': {'string': 'bar', 'empty': '', 'list': ['foo', 'bar']},
+ 'non': {},
'list': ['bar', 'baz'],
'dict': {'key_1': {}, 'key_2': 'vyos'}
}
@@ -30,7 +31,8 @@ class TestDictSearch(TestCase):
def test_non_existing_keys(self):
# TestDictSearch: Return False when querying for non-existent key
- self.assertFalse(dict_search('non_existing', data))
+ self.assertEqual(dict_search('non_existing', data), None)
+ self.assertEqual(dict_search('non.existing.fancy.key', data), None)
def test_string(self):
# TestDictSearch: Return value when querying string
@@ -50,8 +52,14 @@ class TestDictSearch(TestCase):
def test_nested_dict_key_empty(self):
# TestDictSearch: Return False when querying for a nested string whose last key is empty
+ self.assertEqual(dict_search('nested.empty', data), '')
self.assertFalse(dict_search('nested.empty', data))
def test_nested_list(self):
# TestDictSearch: Return list items when querying nested list
self.assertEqual(dict_search('nested.list', data), data['nested']['list'])
+
+ def test_invalid_input(self):
+ # TestDictSearch: Return list items when querying nested list
+ self.assertEqual(dict_search('nested.list', None), None)
+ self.assertEqual(dict_search(None, data), None)