Debian Codegraph @

lib/ansible/plugins/callback/junit.py

raw
1 # (c) 2016 Matt Clay <[email protected]>
2 # (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import annotations
6
7 DOCUMENTATION = """
8 name: junit
9 type: aggregate
10 short_description: write playbook output to a JUnit file.
11 version_added: historical
12 description:
13 - This callback writes playbook output to a JUnit formatted XML file.
14 - "Tasks show up in the report as follows:
15 'ok': pass
16 'failed' with 'EXPECTED FAILURE' in the task name: pass
17 'failed' with 'TOGGLE RESULT' in the task name: pass
18 'ok' with 'TOGGLE RESULT' in the task name: failure
19 'failed' due to an exception: error
20 'failed' for other reasons: failure
21 'skipped': skipped"
22 options:
23 output_dir:
24 name: JUnit output dir
25 default: ~/.ansible.log
26 description: Directory to write XML files to.
27 env:
28 - name: JUNIT_OUTPUT_DIR
29 task_class:
30 name: JUnit Task class
31 default: False
32 description: Configure the output to be one class per yaml file
33 env:
34 - name: JUNIT_TASK_CLASS
35 task_relative_path:
36 name: JUnit Task relative path
37 default: none
38 description: Configure the output to use relative paths to given directory
39 version_added: "2.8"
40 env:
41 - name: JUNIT_TASK_RELATIVE_PATH
42 replace_out_of_tree_path:
43 name: Replace out of tree path
44 default: none
45 description: Replace the directory portion of an out-of-tree relative task path with the given placeholder
46 version_added: "2.12.3"
47 env:
48 - name: JUNIT_REPLACE_OUT_OF_TREE_PATH
49 fail_on_change:
50 name: JUnit fail on change
51 default: False
52 description: Consider any tasks reporting "changed" as a junit test failure
53 env:
54 - name: JUNIT_FAIL_ON_CHANGE
55 fail_on_ignore:
56 name: JUnit fail on ignore
57 default: False
58 description: Consider failed tasks as a junit test failure even if ignore_on_error is set
59 env:
60 - name: JUNIT_FAIL_ON_IGNORE
61 include_setup_tasks_in_report:
62 name: JUnit include setup tasks in report
63 default: True
64 description: Should the setup tasks be included in the final report
65 env:
66 - name: JUNIT_INCLUDE_SETUP_TASKS_IN_REPORT
67 hide_task_arguments:
68 name: Hide the arguments for a task
69 default: False
70 description: Hide the arguments for a task
71 version_added: "2.8"
72 env:
73 - name: JUNIT_HIDE_TASK_ARGUMENTS
74 test_case_prefix:
75 name: Prefix to find actual test cases
76 default: <empty>
77 description: Consider a task only as test case if it has this value as prefix. Additionally failing tasks are recorded as failed test cases.
78 version_added: "2.8"
79 env:
80 - name: JUNIT_TEST_CASE_PREFIX
81 requirements:
82 - enable in configuration
83 """
84
85 import decimal
86 import os
87 import time
88 import re
89 import typing as t
90
91 from ansible import constants
92 from ansible.module_utils.common.text.converters import to_bytes, to_text
93 from ansible.module_utils._internal import _event_utils
94 from ansible.module_utils.secrets import mask_secrets
95 from ansible._internal import _event_formatting
96 from ansible.playbook.task import Task
97 from ansible.plugins.callback import CallbackBase
98 from ansible.executor.task_result import CallbackTaskResult
99 from ansible.playbook.included_file import IncludedFile
100 from ansible.utils._junit_xml import (
101 TestCase,
102 TestError,
103 TestFailure,
104 TestSuite,
105 TestSuites,
106 )
107
108
109 class CallbackModule(CallbackBase):
110 """
111 This callback writes playbook output to a JUnit formatted XML file.
112
113 Tasks show up in the report as follows:
114 'ok': pass
115 'failed' with 'EXPECTED FAILURE' in the task name: pass
116 'failed' with 'TOGGLE RESULT' in the task name: pass
117 'ok' with 'TOGGLE RESULT' in the task name: failure
118 'failed' due to an exception: error
119 'failed' for other reasons: failure
120 'skipped': skipped
121
122 This plugin makes use of the following environment variables:
123 JUNIT_OUTPUT_DIR (optional): Directory to write XML files to.
124 Default: ~/.ansible.log
125 JUNIT_TASK_CLASS (optional): Configure the output to be one class per yaml file
126 Default: False
127 JUNIT_TASK_RELATIVE_PATH (optional): Configure the output to use relative paths to given directory
128 Default: none
129 JUNIT_FAIL_ON_CHANGE (optional): Consider any tasks reporting "changed" as a junit test failure
130 Default: False
131 JUNIT_FAIL_ON_IGNORE (optional): Consider failed tasks as a junit test failure even if ignore_on_error is set
132 Default: False
133 JUNIT_INCLUDE_SETUP_TASKS_IN_REPORT (optional): Should the setup tasks be included in the final report
134 Default: True
135 JUNIT_HIDE_TASK_ARGUMENTS (optional): Hide the arguments for a task
136 Default: False
137 JUNIT_TEST_CASE_PREFIX (optional): Consider a task only as test case if it has this value as prefix. Additionally, failing tasks are recorded as failed
138 test cases.
139 Default: <empty>
140 """
141
142 CALLBACK_VERSION = 2.0
143 CALLBACK_TYPE = 'aggregate'
144 CALLBACK_NAME = 'junit'
145 CALLBACK_NEEDS_ENABLED = True
146
147 ANSIBLE_SUPPORTS_MASKING = True
148
149 def __init__(self) -> None:
150 super(CallbackModule, self).__init__()
151
152 self._output_dir = os.getenv('JUNIT_OUTPUT_DIR', os.path.expanduser('~/.ansible.log'))
153 self._task_class = os.getenv('JUNIT_TASK_CLASS', 'False').lower()
154 self._task_relative_path = os.getenv('JUNIT_TASK_RELATIVE_PATH', '')
155 self._fail_on_change = os.getenv('JUNIT_FAIL_ON_CHANGE', 'False').lower()
156 self._fail_on_ignore = os.getenv('JUNIT_FAIL_ON_IGNORE', 'False').lower()
157 self._include_setup_tasks_in_report = os.getenv('JUNIT_INCLUDE_SETUP_TASKS_IN_REPORT', 'True').lower()
158 self._hide_task_arguments = os.getenv('JUNIT_HIDE_TASK_ARGUMENTS', 'False').lower()
159 self._test_case_prefix = os.getenv('JUNIT_TEST_CASE_PREFIX', '')
160 self._replace_out_of_tree_path = os.getenv('JUNIT_REPLACE_OUT_OF_TREE_PATH', None)
161 self._playbook_path = None
162 self._playbook_name = None
163 self._play_name: str | None = None
164 self._task_data: dict[str, TaskData] = {}
165
166 self.disabled = False
167
168 if self._replace_out_of_tree_path is not None:
169 self._replace_out_of_tree_path = to_text(self._replace_out_of_tree_path)
170
171 if not os.path.exists(self._output_dir):
172 os.makedirs(self._output_dir)
173
174 def _start_task(self, task: Task) -> None:
175 """ record the start of a task for one or more hosts """
176
177 uuid = task._uuid
178
179 if uuid in self._task_data:
180 return
181
182 play = self._play_name
183 name = task.get_name().strip()
184 path = task.get_path()
185 action = task.action
186
187 if not task.no_log and self._hide_task_arguments == 'false':
188 args = ', '.join(('%s=%s' % a for a in task.args.items()))
189 if args:
190 name += ' ' + args
191
192 # This callback opts in to receiving unmasked results, so any secrets must be redacted before they reach the report.
193 self._task_data[uuid] = TaskData(uuid, mask_secrets(name), path, play, action)
194
195 def _finish_task(self, status: str, result: IncludedFile | CallbackTaskResult) -> None:
196 """ record the results of a task for a single host """
197
198 if isinstance(result, CallbackTaskResult):
199 task_uuid = result.task._uuid
200 host_uuid = result.host._uuid
201 host_name = result.host.name
202
203 if self._fail_on_change == 'true' and status == 'ok' and result.result.get('changed', False):
204 status = 'failed'
205 else:
206 task_uuid = result._task._uuid
207 host_uuid = 'include'
208 host_name = 'include'
209
210 task_data = self._task_data[task_uuid]
211
212 # ignore failure if expected and toggle result if asked for
213 if status == 'failed' and 'EXPECTED FAILURE' in task_data.name:
214 status = 'ok'
215 elif 'TOGGLE RESULT' in task_data.name:
216 if status == 'failed':
217 status = 'ok'
218 elif status == 'ok':
219 status = 'failed'
220
221 if task_data.name.startswith(self._test_case_prefix) or status == 'failed':
222 task_data.add_host(HostData(host_uuid, host_name, status, result))
223
224 def _build_test_case(self, task_data: TaskData, host_data: HostData) -> TestCase:
225 """ build a TestCase from the given TaskData and HostData """
226
227 name = mask_secrets('[%s] %s: %s' % (host_data.name, task_data.play, task_data.name))
228 duration = decimal.Decimal(host_data.finish - task_data.start)
229
230 if self._task_relative_path and task_data.path:
231 junit_classname = to_text(os.path.relpath(to_bytes(task_data.path), to_bytes(self._task_relative_path)))
232 else:
233 junit_classname = task_data.path
234
235 if self._replace_out_of_tree_path is not None and junit_classname.startswith('../'):
236 junit_classname = self._replace_out_of_tree_path + to_text(os.path.basename(to_bytes(junit_classname)))
237
238 if self._task_class == 'true':
239 junit_classname = re.sub(r'\.yml:[0-9]+$', '', junit_classname)
240
241 if host_data.status == 'included':
242 return TestCase(name=name, classname=junit_classname, time=duration, system_out=mask_secrets(str(host_data.result)))
243
244 task_result = t.cast(CallbackTaskResult, host_data.result)
245 res = task_result.result
246 rc = res.get('rc', 0)
247 dump = self._cleanse_string(mask_secrets(self._dump_results(res, indent=0)))
248
249 if host_data.status == 'ok':
250 return TestCase(name=name, classname=junit_classname, time=duration, system_out=dump)
251
252 test_case = TestCase(name=name, classname=junit_classname, time=duration)
253
254 if host_data.status == 'failed':
255 if error_summary := task_result.exception:
256 message = mask_secrets(_event_utils.format_event_brief_message(error_summary.event))
257 output = mask_secrets(_event_formatting.format_event_traceback(error_summary.event))
258 test_case.errors.append(TestError(message=message, output=output))
259 elif 'msg' in res:
260 message = mask_secrets(str(res['msg']))
261 test_case.failures.append(TestFailure(message=message, output=dump))
262 else:
263 test_case.failures.append(TestFailure(message='rc=%s' % rc, output=dump))
264 elif host_data.status == 'skipped':
265 if 'skip_reason' in res:
266 message = mask_secrets(str(res['skip_reason']))
267 else:
268 message = 'skipped'
269 test_case.skipped = message
270
271 return test_case
272
273 @staticmethod
274 def _cleanse_string(value):
275 """ convert surrogate escapes to the unicode replacement character to avoid XML encoding errors """
276 return to_text(to_bytes(value, errors='surrogateescape'), errors='replace')
277
278 def _generate_report(self):
279 """ generate a TestSuite report from the collected TaskData and HostData """
280
281 test_cases = []
282
283 for task_uuid, task_data in self._task_data.items():
284 if task_data.action in constants._ACTION_SETUP and self._include_setup_tasks_in_report == 'false':
285 continue
286
287 for host_uuid, host_data in task_data.host_data.items():
288 test_cases.append(self._build_test_case(task_data, host_data))
289
290 test_suite = TestSuite(name=self._playbook_name, cases=test_cases)
291 test_suites = TestSuites(suites=[test_suite])
292 report = test_suites.to_pretty_xml()
293
294 output_file = os.path.join(self._output_dir, '%s-%s.xml' % (self._playbook_name, time.time()))
295
296 with open(output_file, 'wb') as xml:
297 xml.write(to_bytes(report, errors='surrogate_or_strict'))
298
299 def v2_playbook_on_start(self, playbook):
300 self._playbook_path = playbook._file_name
301 self._playbook_name = os.path.splitext(os.path.basename(self._playbook_path))[0]
302
303 def v2_playbook_on_play_start(self, play):
304 self._play_name = play.get_name()
305
306 def v2_playbook_on_task_start(self, task: Task, is_conditional: bool) -> None:
307 self._start_task(task)
308
309 def v2_playbook_on_handler_task_start(self, task: Task) -> None:
310 self._start_task(task)
311
312 def v2_runner_on_failed(self, result: CallbackTaskResult, ignore_errors=False) -> None:
313 if ignore_errors and self._fail_on_ignore != 'true':
314 self._finish_task('ok', result)
315 else:
316 self._finish_task('failed', result)
317
318 def v2_runner_on_ok(self, result: CallbackTaskResult) -> None:
319 self._finish_task('ok', result)
320
321 def v2_runner_on_skipped(self, result: CallbackTaskResult) -> None:
322 self._finish_task('skipped', result)
323
324 def v2_playbook_on_include(self, included_file: IncludedFile) -> None:
325 self._finish_task('included', included_file)
326
327 def v2_playbook_on_stats(self, stats):
328 self._generate_report()
329
330
331 class TaskData:
332 """
333 Data about an individual task.
334 """
335
336 def __init__(self, uuid: str, name: str, path: str, play: str, action: str) -> None:
337 self.uuid = uuid
338 self.name = name
339 self.path = path
340 self.play = play
341 self.start = None
342 self.host_data: dict[str, HostData] = {}
343 self.start = time.time()
344 self.action = action
345
346 def add_host(self, host: HostData) -> None:
347 if host.uuid in self.host_data:
348 if host.status == 'included':
349 # concatenate task include output from multiple items
350 host.result = f'{self.host_data[host.uuid].result}\n{host.result}'
351 else:
352 raise Exception('%s: %s: %s: duplicate host callback: %s' % (self.path, self.play, self.name, host.name))
353
354 self.host_data[host.uuid] = host
355
356
357 class HostData:
358 """
359 Data about an individual host.
360 """
361
362 def __init__(self, uuid: str, name: str, status: str, result: IncludedFile | CallbackTaskResult | str) -> None:
363 self.uuid = uuid
364 self.name = name
365 self.status = status
366 self.result = result
367 self.finish = time.time()