Debian Codegraph @

test/units/plugins/callback/test_callback.py

raw
1 # (c) 2012-2014, Chris Meyers <[email protected]>
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import annotations
19
20 import json
21 import re
22 import textwrap
23 import types
24
25 import unittest
26 from unittest.mock import MagicMock
27
28 from ansible._internal._task import UnifiedTaskResult
29 from ansible.executor.task_result import CallbackTaskResult
30 from ansible.inventory.host import Host
31 from ansible.plugins.callback import CallbackBase
32
33
34 mock_task = MagicMock()
35 mock_task.delegate_to = None
36
37
38 class TestCallback(unittest.TestCase):
39 # FIXME: This doesn't really test anything...
40 def test_init(self):
41 CallbackBase()
42
43 def test_display(self):
44 display_mock = MagicMock()
45 display_mock.verbosity = 0
46 cb = CallbackBase(display=display_mock)
47 self.assertIs(cb._display, display_mock)
48
49 def test_display_verbose(self):
50 display_mock = MagicMock()
51 display_mock.verbosity = 5
52 cb = CallbackBase(display=display_mock)
53 self.assertIs(cb._display, display_mock)
54
55 def test_host_label(self):
56 result = CallbackTaskResult(host=Host('host1'), task=mock_task, utr=UnifiedTaskResult(is_module=False))
57
58 self.assertEqual(CallbackBase.host_label(result), 'host1')
59
60 def test_host_label_delegated(self):
61 mock_task.delegate_to = 'host2'
62 utr = UnifiedTaskResult(is_module=False, delegated_host="host2", callback_delegated_vars_subset=dict(ansible_host='host2'))
63 result = CallbackTaskResult(
64 host=Host('host1'),
65 task=mock_task,
66 utr=utr,
67 )
68 self.assertEqual(CallbackBase.host_label(result), 'host1 -> host2')
69
70 # TODO: import callback module so we can patch callback.cli/callback.C
71
72
73 class TestCallbackResults(unittest.TestCase):
74
75 def test_get_item_label(self):
76 cb = CallbackBase()
77 results = {'item': 'some_item'}
78 res = cb._get_item_label(results)
79 self.assertEqual(res, 'some_item')
80
81 def test_get_item_label_no_log(self):
82 cb = CallbackBase()
83 results = {'item': 'some_item', '_ansible_no_log': True}
84 res = cb._get_item_label(results)
85 self.assertEqual(res, "(censored due to no_log)")
86
87 results = {'item': 'some_item', '_ansible_no_log': False}
88 res = cb._get_item_label(results)
89 self.assertEqual(res, "some_item")
90
91 def test_clean_results_debug_task(self):
92 cb = CallbackBase()
93 result = {'item': 'some_item',
94 'invocation': 'foo --bar whatever [some_json]',
95 'a': 'a single a in result note letter a is in invocation',
96 'b': 'a single b in result note letter b is not in invocation',
97 'changed': True}
98
99 cb._clean_results(result, 'debug')
100
101 # See https://github.com/ansible/ansible/issues/33723
102 self.assertTrue('a' in result)
103 self.assertTrue('b' in result)
104 self.assertFalse('invocation' in result)
105 self.assertFalse('changed' in result)
106
107 def test_clean_results_debug_task_no_invocation(self):
108 cb = CallbackBase()
109 result = {'item': 'some_item',
110 'a': 'a single a in result note letter a is in invocation',
111 'b': 'a single b in result note letter b is not in invocation',
112 'changed': True}
113
114 cb._clean_results(result, 'debug')
115 self.assertTrue('a' in result)
116 self.assertTrue('b' in result)
117 self.assertFalse('changed' in result)
118 self.assertFalse('invocation' in result)
119
120 def test_clean_results_debug_task_empty_results(self):
121 cb = CallbackBase()
122 result = {}
123 cb._clean_results(result, 'debug')
124 self.assertFalse('invocation' in result)
125 self.assertEqual(len(result), 0)
126
127 def test_clean_results(self):
128 cb = CallbackBase()
129 result = {'item': 'some_item',
130 'invocation': 'foo --bar whatever [some_json]',
131 'a': 'a single a in result note letter a is in invocation',
132 'b': 'a single b in result note letter b is not in invocation',
133 'changed': True}
134
135 expected_result = result.copy()
136 cb._clean_results(result, 'ebug')
137 self.assertEqual(result, expected_result)
138
139
140 class TestCallbackDumpResults(object):
141 def test_internal_keys(self):
142 cb = CallbackBase()
143 result = {'item': 'some_item',
144 '_ansible_some_var': 'SENTINEL',
145 'testing_ansible_out': 'should_be_left_in LEFTIN',
146 'invocation': 'foo --bar whatever [some_json]',
147 'some_dict_key': {'a_sub_dict_for_key': 'baz'},
148 'bad_dict_key': {'_ansible_internal_blah': 'SENTINEL'},
149 'changed': True}
150 json_out = cb._dump_results(result)
151 assert '"_ansible_' not in json_out
152 assert 'SENTINEL' not in json_out
153 assert 'LEFTIN' in json_out
154
155 def test_exception(self):
156 cb = CallbackBase()
157 result = {'item': 'some_item LEFTIN',
158 'exception': ['frame1', 'SENTINEL']}
159 json_out = cb._dump_results(result)
160 assert 'SENTINEL' not in json_out
161 assert 'exception' not in json_out
162 assert 'LEFTIN' in json_out
163
164 def test_verbose(self):
165 cb = CallbackBase()
166 result = {'item': 'some_item LEFTIN',
167 '_ansible_verbose_always': 'chicane'}
168 json_out = cb._dump_results(result)
169 assert 'SENTINEL' not in json_out
170 assert 'LEFTIN' in json_out
171
172 def test_diff(self):
173 cb = CallbackBase()
174 result = {'item': 'some_item LEFTIN',
175 'diff': ['remove stuff', 'added LEFTIN'],
176 '_ansible_verbose_always': 'chicane'}
177 json_out = cb._dump_results(result)
178 assert 'SENTINEL' not in json_out
179 assert 'LEFTIN' in json_out
180
181 def test_mixed_keys(self):
182 cb = CallbackBase()
183 result = {3: 'pi',
184 'tau': 6}
185 json_out = cb._dump_results(result)
186 round_trip_result = json.loads(json_out)
187 assert len(round_trip_result) == 2
188 assert '3' in round_trip_result
189 assert 'tau' in round_trip_result
190 assert round_trip_result['3'] == 'pi'
191 assert round_trip_result['tau'] == 6
192
193
194 class TestCallbackDiff(unittest.TestCase):
195
196 def setUp(self):
197 self.cb = CallbackBase()
198
199 def _strip_color(self, s):
200 return re.sub('\033\\[[^m]*m', '', s)
201
202 def test_difflist(self):
203 # TODO: split into smaller tests?
204 difflist = [{'before': u'preface\nThe Before String\npostscript',
205 'after': u'preface\nThe After String\npostscript',
206 'before_header': u'just before',
207 'after_header': u'just after'
208 },
209 {'before': u'preface\nThe Before String\npostscript',
210 'after': u'preface\nThe After String\npostscript',
211 },
212 {'src_binary': 'chicane'},
213 {'dst_binary': 'chicanery'},
214 {'dst_larger': 1},
215 {'src_larger': 2},
216 {'prepared': u'what does prepared do?'},
217 {'before_header': u'just before'},
218 {'after_header': u'just after'}]
219
220 res = self.cb._get_diff(difflist)
221
222 self.assertIn(u'Before String', res)
223 self.assertIn(u'After String', res)
224 self.assertIn(u'just before', res)
225 self.assertIn(u'just after', res)
226
227 def test_simple_diff(self):
228 self.assertMultiLineEqual(
229 self._strip_color(self.cb._get_diff({
230 'before_header': 'somefile.txt',
231 'after_header': 'generated from template somefile.j2',
232 'before': 'one\ntwo\nthree\n',
233 'after': 'one\nthree\nfour\n',
234 })),
235 textwrap.dedent("""\
236 --- before: somefile.txt
237 +++ after: generated from template somefile.j2
238 @@ -1,3 +1,3 @@
239 one
240 -two
241 three
242 +four
243
244 """))
245
246 def test_new_file(self):
247 self.assertMultiLineEqual(
248 self._strip_color(self.cb._get_diff({
249 'before_header': 'somefile.txt',
250 'after_header': 'generated from template somefile.j2',
251 'before': '',
252 'after': 'one\ntwo\nthree\n',
253 })),
254 textwrap.dedent("""\
255 --- before: somefile.txt
256 +++ after: generated from template somefile.j2
257 @@ -0,0 +1,3 @@
258 +one
259 +two
260 +three
261
262 """))
263
264 def test_clear_file(self):
265 self.assertMultiLineEqual(
266 self._strip_color(self.cb._get_diff({
267 'before_header': 'somefile.txt',
268 'after_header': 'generated from template somefile.j2',
269 'before': 'one\ntwo\nthree\n',
270 'after': '',
271 })),
272 textwrap.dedent("""\
273 --- before: somefile.txt
274 +++ after: generated from template somefile.j2
275 @@ -1,3 +0,0 @@
276 -one
277 -two
278 -three
279
280 """))
281
282 def test_no_trailing_newline_before(self):
283 self.assertMultiLineEqual(
284 self._strip_color(self.cb._get_diff({
285 'before_header': 'somefile.txt',
286 'after_header': 'generated from template somefile.j2',
287 'before': 'one\ntwo\nthree',
288 'after': 'one\ntwo\nthree\n',
289 })),
290 textwrap.dedent("""\
291 --- before: somefile.txt
292 +++ after: generated from template somefile.j2
293 @@ -1,3 +1,3 @@
294 one
295 two
296 -three
297 \\ No newline at end of file
298 +three
299
300 """))
301
302 def test_no_trailing_newline_after(self):
303 self.assertMultiLineEqual(
304 self._strip_color(self.cb._get_diff({
305 'before_header': 'somefile.txt',
306 'after_header': 'generated from template somefile.j2',
307 'before': 'one\ntwo\nthree\n',
308 'after': 'one\ntwo\nthree',
309 })),
310 textwrap.dedent("""\
311 --- before: somefile.txt
312 +++ after: generated from template somefile.j2
313 @@ -1,3 +1,3 @@
314 one
315 two
316 -three
317 +three
318 \\ No newline at end of file
319
320 """))
321
322 def test_no_trailing_newline_both(self):
323 self.assertMultiLineEqual(
324 self.cb._get_diff({
325 'before_header': 'somefile.txt',
326 'after_header': 'generated from template somefile.j2',
327 'before': 'one\ntwo\nthree',
328 'after': 'one\ntwo\nthree',
329 }),
330 '')
331
332 def test_no_trailing_newline_both_with_some_changes(self):
333 self.assertMultiLineEqual(
334 self._strip_color(self.cb._get_diff({
335 'before_header': 'somefile.txt',
336 'after_header': 'generated from template somefile.j2',
337 'before': 'one\ntwo\nthree',
338 'after': 'one\nfive\nthree',
339 })),
340 textwrap.dedent("""\
341 --- before: somefile.txt
342 +++ after: generated from template somefile.j2
343 @@ -1,3 +1,3 @@
344 one
345 -two
346 +five
347 three
348 \\ No newline at end of file
349
350 """))
351
352 def test_diff_dicts(self):
353 self.assertMultiLineEqual(
354 self._strip_color(self.cb._get_diff({
355 'before': dict(one=1, two=2, three=3),
356 'after': dict(one=1, three=3, four=4),
357 })),
358 textwrap.dedent("""\
359 --- before
360 +++ after
361 @@ -1,5 +1,5 @@
362 {
363 + "four": 4,
364 "one": 1,
365 - "three": 3,
366 - "two": 2
367 + "three": 3
368 }
369
370 """))
371
372 def test_diff_before_none(self):
373 self.assertMultiLineEqual(
374 self._strip_color(self.cb._get_diff({
375 'before': None,
376 'after': 'one line\n',
377 })),
378 textwrap.dedent("""\
379 --- before
380 +++ after
381 @@ -0,0 +1 @@
382 +one line
383
384 """))
385
386 def test_diff_after_none(self):
387 self.assertMultiLineEqual(
388 self._strip_color(self.cb._get_diff({
389 'before': 'one line\n',
390 'after': None,
391 })),
392 textwrap.dedent("""\
393 --- before
394 +++ after
395 @@ -1 +0,0 @@
396 -one line
397
398 """))
399
400
401 class TestCallbackOnMethods(unittest.TestCase):
402 def _find_on_methods(self, callback):
403 cb_dir = dir(callback)
404 method_names = [x for x in cb_dir if '_on_' in x]
405 methods = [getattr(callback, mn) for mn in method_names]
406 return methods
407
408 def test_are_methods(self):
409 cb = CallbackBase()
410 for method in self._find_on_methods(cb):
411 self.assertIsInstance(method, types.MethodType)
412
413 def test_on_any(self):
414 cb = CallbackBase()
415 cb.v2_on_any('whatever', some_keyword='blippy')
416 cb.on_any('whatever', some_keyword='blippy')
417
418
419 def test_v2_v1_method_map() -> None:
420 """Ensure that all v2 callback methods appear in the method map."""
421 expected_names = [name for name in dir(CallbackBase) if name.startswith('v2_')]
422 mapped_names = {method.__name__ for method in CallbackBase._v2_v1_method_map}
423
424 missing = [name for name in expected_names if name not in mapped_names]
425
426 assert not missing