From a915b0524058396eeca87d391a6762e8f470e2e9 Mon Sep 17 00:00:00 2001 From: Mike Kinney Date: Sun, 2 Jan 2022 11:15:19 -0800 Subject: [PATCH] remove nested keys from nodes so we do not display garbage --- meshtastic/mesh_interface.py | 6 +++--- meshtastic/tests/test_util.py | 17 +++++++++++++++++ meshtastic/util.py | 16 +++++++++++----- 3 files changed, 31 insertions(+), 8 deletions(-) diff --git a/meshtastic/mesh_interface.py b/meshtastic/mesh_interface.py index 275eea2..a5ee3a3 100644 --- a/meshtastic/mesh_interface.py +++ b/meshtastic/mesh_interface.py @@ -83,10 +83,10 @@ class MeshInterface: nodes = "" if self.nodes: for n in self.nodes.values(): - # when the TBeam is first booted, it sometimes shows the 'raw' data + # when the TBeam is first booted, it sometimes shows the raw data # so, we will just remove any raw keys - n2 = remove_keys_from_dict('raw', n) - n2 = remove_keys_from_dict('decode', n2) + keys_to_remove = ('raw', 'decode', 'payload') + n2 = remove_keys_from_dict(keys_to_remove, n) # if we have 'macaddr', re-format it if 'macaddr' in n2['user']: diff --git a/meshtastic/tests/test_util.py b/meshtastic/tests/test_util.py index d05d8e0..bff028b 100644 --- a/meshtastic/tests/test_util.py +++ b/meshtastic/tests/test_util.py @@ -184,6 +184,23 @@ def test_remove_keys_from_dict(): assert remove_keys_from_dict(('b'), {'a':1, 'b':2}) == {'a':1} +@pytest.mark.unit +def test_remove_keys_from_dict_multiple_keys(): + """Test remove_keys_from_dict()""" + keys = ('a', 'b') + adict = {'a': 1, 'b': 2, 'c': 3} + assert remove_keys_from_dict(keys, adict) == {'c':3} + + +@pytest.mark.unit +def test_remove_keys_from_dict_nested(): + """Test remove_keys_from_dict()""" + keys = ('b') + adict = {'a': {'b': 1}, 'b': 2, 'c': 3} + exp = {'a': {}, 'c': 3} + assert remove_keys_from_dict(keys, adict) == exp + + @pytest.mark.unitslow def test_Timeout_not_found(): """Test Timeout()""" diff --git a/meshtastic/util.py b/meshtastic/util.py index e87f725..289603c 100644 --- a/meshtastic/util.py +++ b/meshtastic/util.py @@ -204,12 +204,18 @@ def support_info(): def remove_keys_from_dict(keys, adict): - """Return a dictionary without some keys in it.""" - newdict = adict + """Return a dictionary without some keys in it. + Will removed nested keys. + """ for key in keys: - if key in adict: - del newdict[key] - return newdict + try: + del adict[key] + except: + pass + for val in adict.values(): + if isinstance(val, dict): + remove_keys_from_dict(keys, val) + return adict def hexstr(barray):