Browse Source

Add function helpers.compare_dict

This function allows to compare two dicts, both keys and values.

Change-Id: I0a68d627c00dde49b60e1b47d24822315c16d471
Related-Bug: #1560963
tags/1.22.0
Rodolfo Alonso Hernandez 1 year ago
parent
commit
34910dc074
3 changed files with 42 additions and 0 deletions
  1. +13
    -0
      neutron_lib/tests/unit/utils/test_helpers.py
  2. +23
    -0
      neutron_lib/utils/helpers.py
  3. +6
    -0
      releasenotes/notes/add-compare-dict-315a66a65cbce6fd.yaml

+ 13
- 0
neutron_lib/tests/unit/utils/test_helpers.py View File

@@ -90,6 +90,19 @@ class TestCompareElements(base.BaseTestCase):
['juve', 'napoli']))


class TestCompare(base.BaseTestCase):

def test_compare(self):
self.assertTrue(helpers.compare_dict({'a': 2}, {'a': 2}))
self.assertFalse(helpers.compare_dict({'a': 2}, {'a': 3}))
self.assertTrue(helpers.compare_dict({'a': [1, 2]}, {'a': [2, 1]}))
self.assertFalse(helpers.compare_dict({'a': [1, 2]}, {'a': [1]}))
self.assertTrue(helpers.compare_dict({'a': 'value1'}, {'a': 'value1'}))
self.assertFalse(helpers.compare_dict({'a': 'value'}, {'a': 'value1'}))
self.assertFalse(helpers.compare_dict({'a': '1'},
{'a': '1', 'b': '2'}))


class TestDictUtils(base.BaseTestCase):

def test_dict2str(self):

+ 23
- 0
neutron_lib/utils/helpers.py View File

@@ -74,6 +74,29 @@ def compare_elements(a, b):
return set(a or []) == set(b or [])


def compare_dict(a, b):
"""Compare two dicts, including keys and values.

Useful because dict comparison was removed in Python 3.0.1.

:param a: The first dict to compare.
:param b: The second dict to compare.
:returns: True if a and b have the same keys and values, False otherwise.
"""
if sorted(list(a.keys())) != sorted(list(b.keys())):
return False
for key, value in a.items():
if not isinstance(value, type(b[key])):
return False
if isinstance(value, dict) and not compare_dict(value, b[key]):
return False
if isinstance(value, list) and not value.sort() == b[key].sort():
return False
elif value != b[key]:
return False
return True


def safe_sort_key(value):
"""Return value hash or build one for dictionaries.


+ 6
- 0
releasenotes/notes/add-compare-dict-315a66a65cbce6fd.yaml View File

@@ -0,0 +1,6 @@
---
features:
- |
Introduced ``compare_dict`` function in ``neutron_lib.utils.helpers``. It
allows you to compare two dictionaries, checking both the keys and the
values they contain.

Loading…
Cancel
Save