From 8d0c193b251051e459513614e6f7212ecf9f0922 Mon Sep 17 00:00:00 2001 From: Evgeni Golov Date: Fri, 20 Sep 2019 21:47:18 +0200 Subject: [PATCH] allow before/after diff to be NoneType (#62582) when creating or deleting an object (e.g. via an API), before/after can be `None` (or at least represented as such by the used library). to avoid modules havig to do diff={'before': before or '', 'after': after or ''} let's just convert `None` to an empty string that can be diffed properly --- ...582-allow_diff_before_after_to_be_None.yml | 4 +++ lib/ansible/plugins/callback/__init__.py | 2 ++ test/units/plugins/callback/test_callback.py | 28 +++++++++++++++++++ 3 files changed, 34 insertions(+) create mode 100644 changelogs/fragments/62582-allow_diff_before_after_to_be_None.yml diff --git a/changelogs/fragments/62582-allow_diff_before_after_to_be_None.yml b/changelogs/fragments/62582-allow_diff_before_after_to_be_None.yml new file mode 100644 index 00000000000..65d9c6b7e18 --- /dev/null +++ b/changelogs/fragments/62582-allow_diff_before_after_to_be_None.yml @@ -0,0 +1,4 @@ +minor_changes: + - callbacks - Allow modules to return `None` as before/after entries for diff. + This should make it easier for modules to report the "not existing" state of + the entity they touched. diff --git a/lib/ansible/plugins/callback/__init__.py b/lib/ansible/plugins/callback/__init__.py index ece3b1862ae..a4d1e30a08a 100644 --- a/lib/ansible/plugins/callback/__init__.py +++ b/lib/ansible/plugins/callback/__init__.py @@ -184,6 +184,8 @@ class CallbackBase(AnsiblePlugin): for x in ['before', 'after']: if isinstance(diff[x], MutableMapping): diff[x] = self._serialize_diff(diff[x]) + elif diff[x] is None: + diff[x] = '' if 'before_header' in diff: before_header = u"before: %s" % diff['before_header'] else: diff --git a/test/units/plugins/callback/test_callback.py b/test/units/plugins/callback/test_callback.py index 52233800f36..906f00040c8 100644 --- a/test/units/plugins/callback/test_callback.py +++ b/test/units/plugins/callback/test_callback.py @@ -365,6 +365,34 @@ class TestCallbackDiff(unittest.TestCase): ''')) + def test_diff_before_none(self): + self.assertMultiLineEqual( + self._strip_color(self.cb._get_diff({ + 'before': None, + 'after': 'one line\n', + })), + textwrap.dedent('''\ + --- before + +++ after + @@ -0,0 +1 @@ + +one line + + ''')) + + def test_diff_after_none(self): + self.assertMultiLineEqual( + self._strip_color(self.cb._get_diff({ + 'before': 'one line\n', + 'after': None, + })), + textwrap.dedent('''\ + --- before + +++ after + @@ -1 +0,0 @@ + -one line + + ''')) + class TestCallbackOnMethods(unittest.TestCase): def _find_on_methods(self, callback):