Coverage for src/pytest_xray/xray_plugin.py: 96.5%
196 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-06 12:46 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-06 12:46 +0000
1# Modified in the parameter-details prototype; see NOTICE.
2import datetime as dt
3import json
4import os
5import re
6from pathlib import Path
7from typing import Any, Optional, Protocol, Union
9import pytest
10from _pytest.config import Config, ExitCode
11from _pytest.mark import Mark
12from _pytest.nodes import Item
13from _pytest.reports import TestReport
14from _pytest.terminal import TerminalReporter
16from pytest_xray.case_report import scalar_values
17from pytest_xray.comment_limits import bound_comments
18from pytest_xray.constant import (
19 JIRA_CLOUD,
20 XRAY_ADD_CAPTURES,
21 XRAY_ALLOW_DUPLICATE_IDS,
22 XRAY_EXECUTION_ID,
23 XRAY_MARKER_NAME,
24 XRAY_TEST_PLAN_ID,
25 XRAYPATH,
26)
27from pytest_xray.exceptions import XrayError
28from pytest_xray.file_publisher import FilePublisher
29from pytest_xray.helper import (
30 STATUS_STR_MAPPER_CLOUD,
31 STATUS_STR_MAPPER_JIRA,
32 Status,
33 TestCase,
34 TestExecution,
35)
38class Publisher(Protocol):
39 def publish(self, data: dict[str, Any]) -> str: ...
42class XrayPlugin:
43 """Collects results from pytest and exports to Jira Xray server."""
45 def __init__(self, config: pytest.Config, publisher: Publisher) -> None:
46 self.truncated_comments = 0
47 self.collection_failed = False
48 self.worker_failed = False
49 self.config = config
50 self.parameter_details = config.getoption('--xray-parameter-details', default=False)
51 self.publisher = publisher
52 self.test_execution_id: str = self.config.getoption(XRAY_EXECUTION_ID)
53 self.test_plan_id: str = self.config.getoption(XRAY_TEST_PLAN_ID)
54 self.is_cloud_server: str = self.config.getoption(JIRA_CLOUD)
55 self.allow_duplicate_ids: bool = self.config.getoption(XRAY_ALLOW_DUPLICATE_IDS)
56 logfile = self.config.getoption(XRAYPATH)
57 self.add_captures: bool = self.config.getoption(XRAY_ADD_CAPTURES)
58 self.logfile: Optional[str] = self._get_normalize_logfile(logfile) if logfile else None
59 self.issue_id: Union[str, None] = None # issue id returned by XRAY server
60 self.exception: Union[Exception, None] = None # keeps an exception if raised by XrayPublisher
61 self.test_execution: TestExecution = TestExecution(
62 test_execution_key=self.test_execution_id, test_plan_key=self.test_plan_id
63 )
64 # The plugin owns these aggregates until the final payload hook runs.
65 # Keep the public execution list for first-observed export ordering.
66 self._test_cases_by_key: dict[str, TestCase] = {}
67 self.status_str_mapper: dict[Status, str] = STATUS_STR_MAPPER_JIRA
68 if self.is_cloud_server:
69 self.status_str_mapper = STATUS_STR_MAPPER_CLOUD
71 @staticmethod
72 def _get_normalize_logfile(logfile: str) -> str:
73 logfile = os.path.expanduser(os.path.expandvars(logfile))
74 logfile = os.path.normpath(os.path.abspath(logfile))
75 return logfile
77 def _get_test_keys(self, item: Item) -> list[str]:
78 """Return JIRA ids associated with test item"""
79 test_keys: list[str] = []
80 marker = self._get_xray_marker(item)
82 if not marker:
83 return test_keys
85 if len(marker.args) == 0:
86 raise XrayError(
87 'pytest.mark.xray needs at least one argument, '
88 f'the test {item.nodeid} does not seem to be decorated in proper way.'
89 )
90 if isinstance(marker.args[0], str):
91 test_keys = list(marker.args)
92 elif isinstance(marker.args[0], list):
93 test_keys = marker.args[0]
94 else:
95 raise XrayError(f'xray marker can only accept strings or lists but got {type(marker.args[0])}')
96 if not test_keys or any(not isinstance(key, str) or not key.strip() for key in test_keys):
97 raise XrayError('xray marker requires nonempty string test keys')
98 # Repeating one key in one marker must not duplicate comments or evidence.
99 return list(dict.fromkeys(test_keys))
101 def _get_defects(self, item: Item) -> list[str]:
102 """Return JIRA ids for defects associated with test item"""
103 marker = self._get_xray_marker(item)
105 if not marker:
106 return []
108 defects = marker.kwargs.get('defects', [])
110 if not isinstance(defects, list) or any(not isinstance(value, str) or not value.strip() for value in defects):
111 raise XrayError('xray marker defects must be a list of nonempty strings (an empty list is allowed)')
112 return defects
114 def _verify_jira_ids_for_items(self, items: list[Item]) -> None:
115 """Verify duplicated jira ids."""
116 jira_ids: set[str] = set()
117 duplicated_jira_ids: list[str] = []
119 for item in items:
120 test_keys = self._get_test_keys(item)
121 if not test_keys:
122 continue
124 for test_key in test_keys:
125 if test_key in jira_ids:
126 duplicated_jira_ids.append(test_key)
127 else:
128 jira_ids.add(test_key)
130 if duplicated_jira_ids and not self.allow_duplicate_ids:
131 raise XrayError(f'Duplicated test case ids: {duplicated_jira_ids}')
133 @staticmethod
134 def _get_xray_marker(item: Item) -> Optional[Mark]:
135 return item.get_closest_marker(XRAY_MARKER_NAME)
137 def pytest_sessionstart(self, session):
138 self.test_execution.start_date = dt.datetime.now(tz=dt.timezone.utc)
140 @pytest.hookimpl(tryfirst=True, hookwrapper=True)
141 def pytest_runtest_makereport(self, item, call):
142 outcome = yield
143 report = outcome.get_result()
144 if self.parameter_details and hasattr(item, 'callspec'):
145 # Snapshot only scalar values; never call arbitrary user __repr__.
146 report.xray_parameters = scalar_values(item.callspec.params)
148 if not hasattr(report, 'test_keys'): 148 ↛ 150line 148 didn't jump to line 150 because the condition on line 148 was always true
149 report.test_keys = {}
150 test_keys = self._get_test_keys(item)
151 if test_keys and item.nodeid not in report.test_keys:
152 report.test_keys[item.nodeid] = test_keys
154 if not hasattr(report, 'defects'): 154 ↛ 156line 154 didn't jump to line 156 because the condition on line 154 was always true
155 report.defects = {}
156 defects = self._get_defects(item)
157 if defects and item.nodeid not in report.defects:
158 report.defects[item.nodeid] = defects
160 def pytest_runtest_logreport(self, report: TestReport):
161 status = self._get_status_from_report(report)
162 if status is None:
163 return
165 test_keys = getattr(report, 'test_keys', {}).get(report.nodeid)
166 if test_keys is None:
167 return
169 defects = getattr(report, 'defects', {}).get(report.nodeid)
170 evidences = getattr(report, 'evidences', [])
172 # pytest renders an xdist worker header even when there is no diagnostic.
173 comment = report.longreprtext if report.longrepr is not None else ''
174 if self.add_captures:
175 if comment != '': 175 ↛ 176line 175 didn't jump to line 176 because the condition on line 175 was never true
176 comment += '\n'
177 if report.capstdout: 177 ↛ 179line 177 didn't jump to line 179 because the condition on line 177 was always true
178 comment += f'{"-" * 29} Captured stdout call {"-" * 29}\n{report.capstdout}'
179 if report.capstderr: 179 ↛ 181line 179 didn't jump to line 181 because the condition on line 179 was always true
180 comment += f'{"-" * 29} Captured stderr call {"-" * 29}\n{report.capstderr}'
181 if report.caplog: 181 ↛ 186line 181 didn't jump to line 186 because the condition on line 181 was always true
182 # Remove the ncurses escape chars used to color log level
183 logt = re.subn('\x1b.*?m', '', report.caplog)
184 comment += f'{"-" * 30} Captured log call {"-" * 31}\n{logt[0]}'
186 if self.parameter_details and hasattr(report, 'xray_parameters'):
187 details = json.dumps(
188 {
189 'nodeid': report.nodeid,
190 'parameters': report.xray_parameters,
191 'phase': report.when,
192 'pytest_outcome': report.outcome,
193 'xray_status': self.status_str_mapper[status],
194 },
195 ensure_ascii=True,
196 sort_keys=True,
197 )
198 comment = f'pytest parameter case: {details}\n{comment}'
200 for test_key in test_keys:
201 new_test_case = TestCase(
202 test_key=test_key,
203 status=status,
204 comment=comment,
205 status_str_mapper=self.status_str_mapper,
206 evidences=evidences,
207 defects=defects,
208 )
209 try:
210 test_case = self._test_cases_by_key[test_key]
211 except KeyError:
212 self.test_execution.append(new_test_case)
213 self._test_cases_by_key[test_key] = new_test_case
214 else:
215 test_case.merge(new_test_case)
217 def _get_status_from_report(self, report) -> Optional[Status]:
218 if report.outcome == 'rerun':
219 return Status.FAIL
220 if report.failed:
221 if report.when != 'call':
222 return Status.FAIL
223 if hasattr(report, 'wasxfail'): 223 ↛ 224line 223 didn't jump to line 224 because the condition on line 223 was never true
224 return Status.PASS
225 return Status.FAIL
226 if report.skipped:
227 if hasattr(report, 'wasxfail'):
228 return Status.FAIL
229 return Status.ABORTED
230 if report.passed and report.when == 'call':
231 return Status.PASS
233 return None
235 @pytest.hookimpl(trylast=True)
236 def pytest_collection_modifyitems(self, config: Config, items: list[Item]) -> None:
237 # Validate selected tests after pytest -k/-m filtering, before fixtures run.
238 try:
239 for item in items:
240 self._get_defects(item)
241 self._get_test_keys(item)
242 self._verify_jira_ids_for_items(items)
243 except XrayError as exc:
244 # A collect report reaches the xdist controller; UsageError here
245 # can let workers announce runnable items before exiting.
246 config.hook.pytest_deselected(items=items[:])
247 items.clear()
248 config.hook.pytest_collectreport(
249 report=pytest.CollectReport(
250 nodeid='xray marker configuration',
251 outcome='failed',
252 longrepr=exc.message,
253 result=[],
254 )
255 )
257 def pytest_collectreport(self, report):
258 if report.failed:
259 self.collection_failed = True
261 @pytest.hookimpl(optionalhook=True)
262 def pytest_testnodedown(self, node, error):
263 if error:
264 self.worker_failed = True
266 def pytest_sessionfinish(self, session: pytest.Session) -> None:
267 if hasattr(self.config, 'workerinput'): # skipping on xdist
268 return
269 self.test_execution.finish_date = dt.datetime.now(tz=dt.timezone.utc)
270 results = self.test_execution.as_dict()
271 session.config.pluginmanager.hook.pytest_xray_results(results=results, session=session)
272 try:
273 results, self.truncated_comments = bound_comments(
274 results, self.config.getoption('--xray-comment-limit'), self.config.getoption('--xray-full-report')
275 )
276 if not isinstance(self.publisher, FilePublisher) and (
277 self.worker_failed
278 or self.collection_failed
279 or session.shouldfail
280 or session.shouldstop
281 or session.exitstatus not in (ExitCode.OK, ExitCode.TESTS_FAILED)
282 or not results['tests']
283 ):
284 raise XrayError('Upload withheld: session incomplete, worker crashed, or no marked results')
285 self.issue_id = self.publisher.publish(results)
286 except XrayError as exc:
287 self.exception = exc
288 if session.exitstatus == ExitCode.OK:
289 session.exitstatus = ExitCode.INTERNAL_ERROR
291 def pytest_terminal_summary(self, terminalreporter: TerminalReporter, exitstatus: ExitCode, config: Config) -> None:
292 if self.truncated_comments:
293 terminalreporter.write_line(
294 f'XRAY: truncated {self.truncated_comments} comment(s) to '
295 f'{self.config.getoption("--xray-comment-limit")} UTF-8 bytes; complete payload saved to '
296 f'{self.config.getoption("--xray-full-report")}',
297 yellow=True,
298 )
299 if self.exception:
300 terminalreporter.ensure_newline()
301 terminalreporter.section('Jira XRAY', sep='-', red=True, bold=True)
302 terminalreporter.write_line('Could not publish results to Jira XRAY!')
303 if self.exception.message: # type: ignore[attr-defined] 303 ↛ exitline 303 didn't return from function 'pytest_terminal_summary' because the condition on line 303 was always true
304 terminalreporter.write_line(self.exception.message) # type: ignore[attr-defined]
305 else:
306 if self.issue_id and self.logfile:
307 terminalreporter.write_sep(
308 '-', f'Generated XRAY execution report file: {Path(self.logfile).absolute()}'
309 )
310 elif self.issue_id:
311 terminalreporter.write_sep('-', f'Uploaded results to JIRA XRAY. Test Execution Id: {self.issue_id}')