Skip to content

Commit

Permalink
Adding support of passing empty strings in second
Browse files Browse the repository at this point in the history
level of dictionaries(environment variables, labels).

Signed-off-by: Ivan Halomi <[email protected]>
Co-authored-by: Martin Hiner <[email protected]>
  • Loading branch information
Sevin556 and Martin Hiner committed Sep 29, 2022
1 parent 2a27e6a commit 671a2b9
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
15 changes: 11 additions & 4 deletions podman/api/http_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,26 +66,33 @@ def prepare_body(body: Mapping[str, Any]) -> str:
return json.dumps(body, sort_keys=True)


def _filter_values(mapping: Mapping[str, Any]) -> Dict[str, Any]:
def _filter_values(mapping: Mapping[str, Any], recursion=False) -> Dict[str, Any]:
"""Returns a canonical dictionary with values == None or empty Iterables removed.
Dictionary is walked using recursion.
"""
canonical = {}

for key, value in mapping.items():
# quick filter if possible...
if value is None or (isinstance(value, collections.abc.Sized) and len(value) <= 0):
if (
value is None
or (isinstance(value, collections.abc.Sized) and len(value) <= 0)
and not recursion
):
continue

# depending on type we need details...
if isinstance(value, collections.abc.Mapping):
proposal = _filter_values(value)
proposal = _filter_values(value, recursion=True)
elif isinstance(value, collections.abc.Iterable) and not isinstance(value, str):
proposal = [i for i in value if i is not None]
else:
proposal = value

if proposal not in (None, str(), [], {}):
if not recursion and proposal not in (None, str(), [], {}):
canonical[key] = proposal
elif recursion and proposal not in (None, [], {}):
canonical[key] = proposal

return canonical
Expand Down
10 changes: 10 additions & 0 deletions podman/tests/unit/test_api_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,16 @@ def test_prepare_body_embedded(self):
self.assertDictEqual(actual_dict["Dictionary"], payload["Dictionary"])
self.assertEqual(set(actual_dict["Set1"]), {"item1", "item2"})

def test_prepare_body_dict_empty_string(self):
payload = {"Dictionary": {"key1": "", "key2": {"key3": ""}, "key4": [], "key5": {}}}

actual = api.prepare_body(payload)
actual_dict = json.loads(actual)
payload["Dictionary"].pop("key4")
payload["Dictionary"].pop("key5")

self.assertDictEqual(payload, actual_dict)


if __name__ == '__main__':
unittest.main()

0 comments on commit 671a2b9

Please sign in to comment.