| 1 |
"""Classes for storing and processing test results.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import collections.abc as c |
| 6 |
import datetime |
| 7 |
import typing as t |
| 8 |
|
| 9 |
from .util import ( |
| 10 |
display, |
| 11 |
) |
| 12 |
|
| 13 |
from .util_common import ( |
| 14 |
get_docs_url, |
| 15 |
write_text_test_results, |
| 16 |
write_json_test_results, |
| 17 |
ResultType, |
| 18 |
) |
| 19 |
|
| 20 |
from .metadata import ( |
| 21 |
Metadata, |
| 22 |
) |
| 23 |
|
| 24 |
from .config import ( |
| 25 |
TestConfig, |
| 26 |
) |
| 27 |
|
| 28 |
from . import junit_xml |
| 29 |
|
| 30 |
|
| 31 |
def calculate_best_confidence(choices: tuple[tuple[str, int], ...], metadata: Metadata) -> int: |
| 32 |
"""Return the best confidence value available from the given choices and metadata.""" |
| 33 |
best_confidence = 0 |
| 34 |
|
| 35 |
for path, line in choices: |
| 36 |
confidence = calculate_confidence(path, line, metadata) |
| 37 |
best_confidence = max(confidence, best_confidence) |
| 38 |
|
| 39 |
return best_confidence |
| 40 |
|
| 41 |
|
| 42 |
def calculate_confidence(path: str, line: int, metadata: Metadata) -> int: |
| 43 |
"""Return the confidence level for a test result associated with the given file path and line number.""" |
| 44 |
ranges = metadata.changes.get(path) |
| 45 |
|
| 46 |
# no changes were made to the file |
| 47 |
if not ranges: |
| 48 |
return 0 |
| 49 |
|
| 50 |
# changes were made to the same file and line |
| 51 |
if any(r[0] <= line <= r[1] for r in ranges): |
| 52 |
return 100 |
| 53 |
|
| 54 |
# changes were made to the same file and the line number is unknown |
| 55 |
if line == 0: |
| 56 |
return 75 |
| 57 |
|
| 58 |
# changes were made to the same file and the line number is different |
| 59 |
return 50 |
| 60 |
|
| 61 |
|
| 62 |
class TestResult: |
| 63 |
"""Base class for test results.""" |
| 64 |
|
| 65 |
def __init__(self, command: str, test: str, python_version: t.Optional[str] = None) -> None: |
| 66 |
self.command = command |
| 67 |
self.test = test |
| 68 |
self.python_version = python_version |
| 69 |
self.name = self.test or self.command |
| 70 |
|
| 71 |
if self.python_version: |
| 72 |
self.name += '-python-%s' % self.python_version |
| 73 |
|
| 74 |
def write(self, args: TestConfig) -> None: |
| 75 |
"""Write the test results to various locations.""" |
| 76 |
self.write_console() |
| 77 |
self.write_bot(args) |
| 78 |
|
| 79 |
if args.lint: |
| 80 |
self.write_lint() |
| 81 |
|
| 82 |
if args.junit: |
| 83 |
self.write_junit(args) |
| 84 |
|
| 85 |
def write_console(self) -> None: |
| 86 |
"""Write results to console.""" |
| 87 |
|
| 88 |
def write_lint(self) -> None: |
| 89 |
"""Write lint results to stdout.""" |
| 90 |
|
| 91 |
def write_bot(self, args: TestConfig) -> None: |
| 92 |
"""Write results to a file for ansibullbot to consume.""" |
| 93 |
|
| 94 |
def write_junit(self, args: TestConfig) -> None: |
| 95 |
"""Write results to a junit XML file.""" |
| 96 |
|
| 97 |
def create_result_name(self, extension: str) -> str: |
| 98 |
"""Return the name of the result file using the given extension.""" |
| 99 |
name = 'ansible-test-%s' % self.command |
| 100 |
|
| 101 |
if self.test: |
| 102 |
name += '-%s' % self.test |
| 103 |
|
| 104 |
if self.python_version: |
| 105 |
name += '-python-%s' % self.python_version |
| 106 |
|
| 107 |
name += extension |
| 108 |
|
| 109 |
return name |
| 110 |
|
| 111 |
def save_junit(self, args: TestConfig, test_case: junit_xml.TestCase) -> None: |
| 112 |
"""Save the given test case results to disk as JUnit XML.""" |
| 113 |
suites = junit_xml.TestSuites( |
| 114 |
suites=[ |
| 115 |
junit_xml.TestSuite( |
| 116 |
name='ansible-test', |
| 117 |
cases=[test_case], |
| 118 |
timestamp=datetime.datetime.now(tz=datetime.timezone.utc), |
| 119 |
), |
| 120 |
], |
| 121 |
) |
| 122 |
|
| 123 |
report = suites.to_pretty_xml() |
| 124 |
|
| 125 |
if args.explain: |
| 126 |
return |
| 127 |
|
| 128 |
write_text_test_results(ResultType.JUNIT, self.create_result_name('.xml'), report) |
| 129 |
|
| 130 |
|
| 131 |
class TestTimeout(TestResult): |
| 132 |
"""Test timeout.""" |
| 133 |
|
| 134 |
def __init__(self, timeout_duration: int | float) -> None: |
| 135 |
super().__init__(command='timeout', test='') |
| 136 |
|
| 137 |
self.timeout_duration = timeout_duration |
| 138 |
|
| 139 |
def write(self, args: TestConfig) -> None: |
| 140 |
"""Write the test results to various locations.""" |
| 141 |
message = 'Tests were aborted after exceeding the %d minute time limit.' % self.timeout_duration |
| 142 |
|
| 143 |
# Include a leading newline to improve readability on Shippable "Tests" tab. |
| 144 |
# Without this, the first line becomes indented. |
| 145 |
output = """ |
| 146 |
One or more of the following situations may be responsible: |
| 147 |
|
| 148 |
- Code changes have resulted in tests that hang or run for an excessive amount of time. |
| 149 |
- Tests have been added which exceed the time limit when combined with existing tests. |
| 150 |
- Test infrastructure and/or external dependencies are operating slower than normal.""" |
| 151 |
|
| 152 |
if args.coverage: |
| 153 |
output += '\n- Additional overhead from collecting code coverage has resulted in tests exceeding the time limit.' |
| 154 |
|
| 155 |
output += '\n\nConsult the console log for additional details on where the timeout occurred.' |
| 156 |
|
| 157 |
suites = junit_xml.TestSuites( |
| 158 |
suites=[ |
| 159 |
junit_xml.TestSuite( |
| 160 |
name='ansible-test', |
| 161 |
timestamp=datetime.datetime.now(tz=datetime.timezone.utc), |
| 162 |
cases=[ |
| 163 |
junit_xml.TestCase( |
| 164 |
name='timeout', |
| 165 |
classname='timeout', |
| 166 |
errors=[ |
| 167 |
junit_xml.TestError( |
| 168 |
message=message, |
| 169 |
), |
| 170 |
], |
| 171 |
), |
| 172 |
], |
| 173 |
) |
| 174 |
], |
| 175 |
) |
| 176 |
|
| 177 |
report = suites.to_pretty_xml() |
| 178 |
|
| 179 |
write_text_test_results(ResultType.JUNIT, self.create_result_name('.xml'), report) |
| 180 |
|
| 181 |
|
| 182 |
class TestSuccess(TestResult): |
| 183 |
"""Test success.""" |
| 184 |
|
| 185 |
def write_junit(self, args: TestConfig) -> None: |
| 186 |
"""Write results to a junit XML file.""" |
| 187 |
test_case = junit_xml.TestCase(classname=self.command, name=self.name) |
| 188 |
|
| 189 |
self.save_junit(args, test_case) |
| 190 |
|
| 191 |
|
| 192 |
class TestSkipped(TestResult): |
| 193 |
"""Test skipped.""" |
| 194 |
|
| 195 |
def __init__(self, command: str, test: str, python_version: t.Optional[str] = None) -> None: |
| 196 |
super().__init__(command, test, python_version) |
| 197 |
|
| 198 |
self.reason: t.Optional[str] = None |
| 199 |
|
| 200 |
def write_console(self) -> None: |
| 201 |
"""Write results to console.""" |
| 202 |
if self.reason: |
| 203 |
display.warning(self.reason) |
| 204 |
else: |
| 205 |
display.info('No tests applicable.', verbosity=1) |
| 206 |
|
| 207 |
def write_junit(self, args: TestConfig) -> None: |
| 208 |
"""Write results to a junit XML file.""" |
| 209 |
test_case = junit_xml.TestCase( |
| 210 |
classname=self.command, |
| 211 |
name=self.name, |
| 212 |
skipped=self.reason or 'No tests applicable.', |
| 213 |
) |
| 214 |
|
| 215 |
self.save_junit(args, test_case) |
| 216 |
|
| 217 |
|
| 218 |
class TestFailure(TestResult): |
| 219 |
"""Test failure.""" |
| 220 |
|
| 221 |
def __init__( |
| 222 |
self, |
| 223 |
command: str, |
| 224 |
test: str, |
| 225 |
python_version: t.Optional[str] = None, |
| 226 |
messages: t.Optional[c.Sequence[TestMessage]] = None, |
| 227 |
summary: t.Optional[str] = None, |
| 228 |
): |
| 229 |
super().__init__(command, test, python_version) |
| 230 |
|
| 231 |
if messages: |
| 232 |
messages = sorted(messages) |
| 233 |
else: |
| 234 |
messages = [] |
| 235 |
|
| 236 |
self.messages = messages |
| 237 |
self.summary = summary |
| 238 |
|
| 239 |
def write(self, args: TestConfig) -> None: |
| 240 |
"""Write the test results to various locations.""" |
| 241 |
if args.metadata.changes: |
| 242 |
self.populate_confidence(args.metadata) |
| 243 |
|
| 244 |
super().write(args) |
| 245 |
|
| 246 |
def write_console(self) -> None: |
| 247 |
"""Write results to console.""" |
| 248 |
if self.summary: |
| 249 |
display.error(self.summary) |
| 250 |
else: |
| 251 |
if self.python_version: |
| 252 |
specifier = ' on python %s' % self.python_version |
| 253 |
else: |
| 254 |
specifier = '' |
| 255 |
|
| 256 |
display.error('Found %d %s issue(s)%s which need to be resolved:' % (len(self.messages), self.test or self.command, specifier)) |
| 257 |
|
| 258 |
for message in self.messages: |
| 259 |
display.error(message.format(show_confidence=True)) |
| 260 |
|
| 261 |
doc_url = self.find_docs() |
| 262 |
if doc_url: |
| 263 |
display.info('See documentation for help: %s' % doc_url) |
| 264 |
|
| 265 |
def write_lint(self) -> None: |
| 266 |
"""Write lint results to stdout.""" |
| 267 |
if self.summary: |
| 268 |
command = self.format_command() |
| 269 |
message = 'The test `%s` failed. See stderr output for details.' % command |
| 270 |
path = '' |
| 271 |
message = TestMessage(message, path) |
| 272 |
print(message) # display goes to stderr, this should be on stdout |
| 273 |
else: |
| 274 |
for message in self.messages: |
| 275 |
print(message) # display goes to stderr, this should be on stdout |
| 276 |
|
| 277 |
def write_junit(self, args: TestConfig) -> None: |
| 278 |
"""Write results to a junit XML file.""" |
| 279 |
title = self.format_title() |
| 280 |
output = self.format_block() |
| 281 |
|
| 282 |
test_case = junit_xml.TestCase( |
| 283 |
classname=self.command, |
| 284 |
name=self.name, |
| 285 |
failures=[ |
| 286 |
junit_xml.TestFailure( |
| 287 |
message=title, |
| 288 |
output=output, |
| 289 |
), |
| 290 |
], |
| 291 |
) |
| 292 |
|
| 293 |
self.save_junit(args, test_case) |
| 294 |
|
| 295 |
def write_bot(self, args: TestConfig) -> None: |
| 296 |
"""Write results to a file for ansibullbot to consume.""" |
| 297 |
docs = self.find_docs() |
| 298 |
message = self.format_title(help_link=docs) |
| 299 |
output = self.format_block() |
| 300 |
|
| 301 |
if self.messages: |
| 302 |
verified = all((m.confidence or 0) >= 50 for m in self.messages) |
| 303 |
else: |
| 304 |
verified = False |
| 305 |
|
| 306 |
bot_data = dict( |
| 307 |
verified=verified, |
| 308 |
docs=docs, |
| 309 |
results=[ |
| 310 |
dict( |
| 311 |
message=message, |
| 312 |
output=output, |
| 313 |
), |
| 314 |
], |
| 315 |
) |
| 316 |
|
| 317 |
if args.explain: |
| 318 |
return |
| 319 |
|
| 320 |
write_json_test_results(ResultType.BOT, self.create_result_name('.json'), bot_data) |
| 321 |
|
| 322 |
def populate_confidence(self, metadata: Metadata) -> None: |
| 323 |
"""Populate test result confidence using the provided metadata.""" |
| 324 |
for message in self.messages: |
| 325 |
if message.confidence is None: |
| 326 |
message.confidence = calculate_confidence(message.path, message.line, metadata) |
| 327 |
|
| 328 |
def format_command(self) -> str: |
| 329 |
"""Return a string representing the CLI command associated with the test failure.""" |
| 330 |
command = 'ansible-test %s' % self.command |
| 331 |
|
| 332 |
if self.test: |
| 333 |
command += ' --test %s' % self.test |
| 334 |
|
| 335 |
if self.python_version: |
| 336 |
command += ' --python %s' % self.python_version |
| 337 |
|
| 338 |
return command |
| 339 |
|
| 340 |
def find_docs(self) -> t.Optional[str]: |
| 341 |
"""Return the docs URL for this test or None if there is no docs URL.""" |
| 342 |
if self.command != 'sanity': |
| 343 |
return None # only sanity tests have docs links |
| 344 |
|
| 345 |
filename = f'{self.test}.html' if self.test else '' |
| 346 |
url = get_docs_url(f'https://docs.ansible.com/ansible-core/devel/dev_guide/testing/{self.command}/{filename}') |
| 347 |
|
| 348 |
return url |
| 349 |
|
| 350 |
def format_title(self, help_link: t.Optional[str] = None) -> str: |
| 351 |
"""Return a string containing a title/heading for this test failure, including an optional help link to explain the test.""" |
| 352 |
command = self.format_command() |
| 353 |
|
| 354 |
if self.summary: |
| 355 |
reason = 'the error' |
| 356 |
else: |
| 357 |
reason = '1 error' if len(self.messages) == 1 else '%d errors' % len(self.messages) |
| 358 |
|
| 359 |
if help_link: |
| 360 |
help_link_markup = ' [[explain](%s)]' % help_link |
| 361 |
else: |
| 362 |
help_link_markup = '' |
| 363 |
|
| 364 |
title = 'The test `%s`%s failed with %s:' % (command, help_link_markup, reason) |
| 365 |
|
| 366 |
return title |
| 367 |
|
| 368 |
def format_block(self) -> str: |
| 369 |
"""Format the test summary or messages as a block of text and return the result.""" |
| 370 |
if self.summary: |
| 371 |
block = self.summary |
| 372 |
else: |
| 373 |
block = '\n'.join(m.format() for m in self.messages) |
| 374 |
|
| 375 |
message = block.strip() |
| 376 |
|
| 377 |
# Hack to remove ANSI color reset code from SubprocessError messages. |
| 378 |
message = message.replace(display.clear, '') |
| 379 |
|
| 380 |
return message |
| 381 |
|
| 382 |
|
| 383 |
class TestMessage: |
| 384 |
"""Single test message for one file.""" |
| 385 |
|
| 386 |
def __init__( |
| 387 |
self, |
| 388 |
message: str, |
| 389 |
path: str, |
| 390 |
line: int = 0, |
| 391 |
column: int = 0, |
| 392 |
level: str = 'error', |
| 393 |
code: t.Optional[str] = None, |
| 394 |
confidence: t.Optional[int] = None, |
| 395 |
): |
| 396 |
self.__path = path |
| 397 |
self.__line = line |
| 398 |
self.__column = column |
| 399 |
self.__level = level |
| 400 |
self.__code = code |
| 401 |
self.__message = message |
| 402 |
|
| 403 |
self.confidence = confidence |
| 404 |
|
| 405 |
@property |
| 406 |
def path(self) -> str: |
| 407 |
"""Return the path.""" |
| 408 |
return self.__path |
| 409 |
|
| 410 |
@property |
| 411 |
def line(self) -> int: |
| 412 |
"""Return the line number, or 0 if none is available.""" |
| 413 |
return self.__line |
| 414 |
|
| 415 |
@property |
| 416 |
def column(self) -> int: |
| 417 |
"""Return the column number, or 0 if none is available.""" |
| 418 |
return self.__column |
| 419 |
|
| 420 |
@property |
| 421 |
def level(self) -> str: |
| 422 |
"""Return the level.""" |
| 423 |
return self.__level |
| 424 |
|
| 425 |
@property |
| 426 |
def code(self) -> t.Optional[str]: |
| 427 |
"""Return the code, if any.""" |
| 428 |
return self.__code |
| 429 |
|
| 430 |
@property |
| 431 |
def message(self) -> str: |
| 432 |
"""Return the message.""" |
| 433 |
return self.__message |
| 434 |
|
| 435 |
@property |
| 436 |
def tuple(self) -> tuple[str, int, int, str, t.Optional[str], str]: |
| 437 |
"""Return a tuple with all the immutable values of this test message.""" |
| 438 |
return self.__path, self.__line, self.__column, self.__level, self.__code, self.__message |
| 439 |
|
| 440 |
def __lt__(self, other): |
| 441 |
return self.tuple < other.tuple |
| 442 |
|
| 443 |
def __le__(self, other): |
| 444 |
return self.tuple <= other.tuple |
| 445 |
|
| 446 |
def __eq__(self, other): |
| 447 |
return self.tuple == other.tuple |
| 448 |
|
| 449 |
def __ne__(self, other): |
| 450 |
return self.tuple != other.tuple |
| 451 |
|
| 452 |
def __gt__(self, other): |
| 453 |
return self.tuple > other.tuple |
| 454 |
|
| 455 |
def __ge__(self, other): |
| 456 |
return self.tuple >= other.tuple |
| 457 |
|
| 458 |
def __hash__(self): |
| 459 |
return hash(self.tuple) |
| 460 |
|
| 461 |
def __str__(self): |
| 462 |
return self.format() |
| 463 |
|
| 464 |
def format(self, show_confidence: bool = False) -> str: |
| 465 |
"""Return a string representation of this message, optionally including the confidence level.""" |
| 466 |
if self.__code: |
| 467 |
msg = '%s: %s' % (self.__code, self.__message) |
| 468 |
else: |
| 469 |
msg = self.__message |
| 470 |
|
| 471 |
if show_confidence and self.confidence is not None: |
| 472 |
msg += ' (%d%%)' % self.confidence |
| 473 |
|
| 474 |
return '%s:%s:%s: %s' % (self.__path, self.__line, self.__column, msg) |