From 59db302deb345e61551814f91b114ec640339889 Mon Sep 17 00:00:00 2001 From: Alexei Znamensky <103110+russoz@users.noreply.github.com> Date: Wed, 31 May 2023 17:58:54 +1200 Subject: [PATCH] VarDict module utils: add `as_dict()` method (#6602) * VarDict module utils: add `as_dict()` method * add changelog frag --- changelogs/fragments/6602-vardict-as-dict.yml | 2 ++ plugins/module_utils/vardict.py | 3 +++ tests/unit/plugins/module_utils/test_vardict.py | 9 +++++++++ 3 files changed, 14 insertions(+) create mode 100644 changelogs/fragments/6602-vardict-as-dict.yml diff --git a/changelogs/fragments/6602-vardict-as-dict.yml b/changelogs/fragments/6602-vardict-as-dict.yml new file mode 100644 index 0000000000..d21952b00b --- /dev/null +++ b/changelogs/fragments/6602-vardict-as-dict.yml @@ -0,0 +1,2 @@ +minor_changes: + - VarDict module utils - add method ``VarDict.as_dict()`` to convert to a plain ``dict`` object (https://github.com/ansible-collections/community.general/pull/6602). diff --git a/plugins/module_utils/vardict.py b/plugins/module_utils/vardict.py index e5754425fc..c94ef669af 100644 --- a/plugins/module_utils/vardict.py +++ b/plugins/module_utils/vardict.py @@ -173,3 +173,6 @@ class VarDict(object): @property def has_changed(self): return any(True for var in self.__vars__.values() if var.has_changed) + + def as_dict(self): + return dict((name, var.value) for name, var in self.__vars__.items()) diff --git a/tests/unit/plugins/module_utils/test_vardict.py b/tests/unit/plugins/module_utils/test_vardict.py index 8b6f16226d..27a5be1a99 100644 --- a/tests/unit/plugins/module_utils/test_vardict.py +++ b/tests/unit/plugins/module_utils/test_vardict.py @@ -122,3 +122,12 @@ def test_vardict_change(): assert vd.has_changed is False vd.xx = 12345 assert vd.has_changed is True + + +def test_vardict_dict(): + vd = VarDict() + vd.set("xx", 123) + vd.set("yy", 456) + vd.set("zz", 789) + + assert vd.as_dict() == {"xx": 123, "yy": 456, "zz": 789}