robotcode-runner 2.9.0.dev124__py3-none-any.whl → 2.9.0.dev180__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,8 +15,10 @@ All subcommands respect the global `-f/--format` option:
15
15
 
16
16
  import re
17
17
  import shutil
18
+ from enum import IntFlag
18
19
  from pathlib import Path
19
20
  from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Iterator, List, Optional, Set, Tuple
21
+ from xml.etree import ElementTree
20
22
 
21
23
  import click
22
24
  from robot.api import SuiteVisitor
@@ -47,6 +49,7 @@ from robot.utils import normalize
47
49
  from robotcode.modifiers import ByLongName, ByTestMetadata, ExcludedByLongName, ExcludedByTestMetadata
48
50
  from robotcode.modifiers.metadata_modifiers import MetadataPattern
49
51
  from robotcode.plugin import Application, OutputFormat, pass_application
52
+ from robotcode.plugin.click_helper.exit_codes import errors_exit_with_128
50
53
  from robotcode.plugin.click_helper.types import add_options
51
54
  from robotcode.robot.config.loader import load_robot_config_from_path
52
55
  from robotcode.robot.config.model import RobotBaseProfile
@@ -72,9 +75,28 @@ from .._search import (
72
75
  make_search_matcher,
73
76
  named_metadata,
74
77
  )
75
- from . import _html, _render
78
+ from . import _compare, _html, _render
76
79
  from ._models import (
77
80
  ArtifactRef,
81
+ CompareCell,
82
+ CompareElapsed,
83
+ CompareEnvironment,
84
+ CompareFailure,
85
+ CompareFailureGroup,
86
+ CompareFailures,
87
+ CompareGroup,
88
+ CompareGrowth,
89
+ CompareLevelCount,
90
+ CompareMessage,
91
+ CompareMessageGroup,
92
+ CompareMessages,
93
+ CompareResult,
94
+ CompareRun,
95
+ CompareStatsGroup,
96
+ CompareStatsSection,
97
+ CompareTest,
98
+ CompareTestGroup,
99
+ CompareTests,
78
100
  Counts,
79
101
  DiffChange,
80
102
  DiffResult,
@@ -243,7 +265,7 @@ SEARCH_OPTIONS = [
243
265
  default=None,
244
266
  help=(
245
267
  "Only include tests with at least one match against PATTERN "
246
- "(Python regular expression, case-sensitive — prefix with `(?i)` "
268
+ "(Python regular expression, case-sensitive; prefix with `(?i)` "
247
269
  "for case-insensitive). Same target fields as `--search`. "
248
270
  "Mutually exclusive with `--search`."
249
271
  ),
@@ -262,7 +284,7 @@ OUTPUT_OPTION = click.option(
262
284
  "Path to output.xml/output.json (Robot's `--output`). If omitted, "
263
285
  "auto-discovered from the active profile's `output_dir` + `output` "
264
286
  "settings (with timestamp glob fallback and ./output.xml as last "
265
- "resort). A directory may also be passed — then auto-discovery "
287
+ "resort). A directory may also be passed; auto-discovery then "
266
288
  "happens inside it."
267
289
  ),
268
290
  )
@@ -276,10 +298,11 @@ FULL_PATHS_OPTION = click.option(
276
298
  )
277
299
 
278
300
 
301
+ @errors_exit_with_128
279
302
  @click.group(invoke_without_command=False)
280
303
  def results() -> None:
281
304
  """\
282
- Inspect a finished run's `output.xml` / `output.json` — counts,
305
+ Inspect a finished run's `output.xml` / `output.json`: counts,
283
306
  failures, and per-test execution tree, without re-running.
284
307
 
285
308
  The result file is auto-discovered from the active profile's
@@ -468,7 +491,7 @@ def summary(
468
491
  metavar="FIELD",
469
492
  help=(
470
493
  "Sort tests before display. `name`/`suite` = lexicographic full-name/suite. "
471
- "`status` = FAIL → SKIP → PASS → NOT RUN. `elapsed` = duration (longest first). "
494
+ "`status` = FAIL -> SKIP -> PASS -> NOT RUN. `elapsed` = duration (longest first). "
472
495
  "`start` = start time. Default: execution order from the output file."
473
496
  ),
474
497
  )
@@ -740,7 +763,7 @@ def log(
740
763
  """\
741
764
  Show the execution log of each test: keywords, control flow and messages.
742
765
 
743
- Filter the same way as `show` — by status, tag, suite, or test name.
766
+ Filter the same way as `show`: by status, tag, suite, or test name.
744
767
  Without filters, all tests are included. Use `--max-depth` to collapse
745
768
  deeply nested keyword calls.
746
769
 
@@ -997,6 +1020,27 @@ def stats(
997
1020
 
998
1021
 
999
1022
  def _build_stats_section(dimension: str, tests: List[TestCase], group_sort: str, top_n: int) -> StatsSection:
1023
+ groups = list(_stats_buckets(dimension, tests).values())
1024
+
1025
+ group_key_map: Dict[str, Tuple[Callable[[StatsGroup], Any], bool]] = {
1026
+ "name": (lambda g: g.name.lower(), False),
1027
+ "total": (lambda g: g.counts.total, True),
1028
+ "elapsed": (lambda g: g.elapsed_seconds or 0.0, True),
1029
+ "failed": (lambda g: g.counts.failed, True),
1030
+ }
1031
+ sort_key, reverse = group_key_map.get(group_sort, group_key_map["failed"])
1032
+ groups.sort(key=sort_key, reverse=reverse)
1033
+
1034
+ truncated = 0
1035
+ if top_n > 0 and len(groups) > top_n:
1036
+ truncated = len(groups) - top_n
1037
+ groups = groups[:top_n]
1038
+
1039
+ return StatsSection(dimension=dimension, groups=groups, truncated=truncated)
1040
+
1041
+
1042
+ def _stats_buckets(dimension: str, tests: Iterable[TestCase]) -> Dict[str, StatsGroup]:
1043
+ """Group name -> counts and elapsed time of the tests in it, in the order the groups first appear."""
1000
1044
  buckets: Dict[str, Counts] = {}
1001
1045
  elapsed: Dict[str, float] = {}
1002
1046
 
@@ -1024,29 +1068,66 @@ def _build_stats_section(dimension: str, tests: List[TestCase], group_sort: str,
1024
1068
  for tag in tags:
1025
1069
  _bump(normalize(str(tag), ignore="_"), t.status, secs)
1026
1070
 
1027
- groups = [
1028
- StatsGroup(name=name, counts=counts, elapsed_seconds=elapsed.get(name) or None)
1071
+ return {
1072
+ name: StatsGroup(name=name, counts=counts, elapsed_seconds=elapsed.get(name) or None)
1029
1073
  for name, counts in buckets.items()
1030
- ]
1031
-
1032
- group_key_map: Dict[str, Tuple[Callable[[StatsGroup], Any], bool]] = {
1033
- "name": (lambda g: g.name.lower(), False),
1034
- "total": (lambda g: g.counts.total, True),
1035
- "elapsed": (lambda g: g.elapsed_seconds or 0.0, True),
1036
- "failed": (lambda g: g.counts.failed, True),
1037
1074
  }
1038
- sort_key, reverse = group_key_map.get(group_sort, group_key_map["failed"])
1039
- groups.sort(key=sort_key, reverse=reverse)
1040
1075
 
1041
- truncated = 0
1042
- if top_n > 0 and len(groups) > top_n:
1043
- truncated = len(groups) - top_n
1044
- groups = groups[:top_n]
1045
1076
 
1046
- return StatsSection(dimension=dimension, groups=groups, truncated=truncated)
1077
+ _DIFF_CATEGORIES = ("new-failures", "new-passes", "status-changes", "added", "removed")
1047
1078
 
1048
1079
 
1049
- _DIFF_CATEGORIES = ("new-failures", "new-passes", "status-changes", "added", "removed")
1080
+ class DiffExitCode(IntFlag):
1081
+ """Exit code of `results diff --exit-code`: one bit per category that has entries.
1082
+
1083
+ 128 is the code of an error, so later categories can take 32 and 64 only.
1084
+ """
1085
+
1086
+ NONE = 0
1087
+ NEW_FAILURES = 1
1088
+ NEW_PASSES = 2
1089
+ STATUS_CHANGES = 4
1090
+ ADDED = 8
1091
+ REMOVED = 16
1092
+ ALL = NEW_FAILURES | NEW_PASSES | STATUS_CHANGES | ADDED | REMOVED
1093
+
1094
+
1095
+ def _parse_diff_exit_code_mask(
1096
+ ctx: click.Context, param: click.Parameter, value: Tuple[str, ...]
1097
+ ) -> Optional[DiffExitCode]:
1098
+ """Parse `--exit-code-mask`: `None` when it isn't given, which keeps the exit code off."""
1099
+ if not value:
1100
+ return None
1101
+ mask = DiffExitCode.NONE
1102
+ for entry in value:
1103
+ for part in entry.split(","):
1104
+ name = part.strip().lower()
1105
+ if not name:
1106
+ continue
1107
+ if name != "all" and name not in _DIFF_CATEGORIES:
1108
+ raise click.BadParameter(
1109
+ f"{part.strip()!r} is not one of " + ", ".join(repr(c) for c in (*_DIFF_CATEGORIES, "all")) + "."
1110
+ )
1111
+ mask |= DiffExitCode[name.replace("-", "_").upper()]
1112
+ return mask
1113
+
1114
+
1115
+ def _diff_exit_code(data: DiffResult, mask: DiffExitCode) -> DiffExitCode:
1116
+ """The categories of `data` that have entries, without those in `mask`.
1117
+
1118
+ A category that `--only` left out is `None` in `data`, so it never counts.
1119
+ """
1120
+ code = DiffExitCode.NONE
1121
+ for entries, flag in (
1122
+ (data.new_failures, DiffExitCode.NEW_FAILURES),
1123
+ (data.new_passes, DiffExitCode.NEW_PASSES),
1124
+ (data.status_changes, DiffExitCode.STATUS_CHANGES),
1125
+ (data.added, DiffExitCode.ADDED),
1126
+ (data.removed, DiffExitCode.REMOVED),
1127
+ ):
1128
+ if entries:
1129
+ code |= flag
1130
+ return DiffExitCode(int(code) & ~int(mask))
1050
1131
 
1051
1132
 
1052
1133
  @results.command()
@@ -1076,6 +1157,19 @@ _DIFF_CATEGORIES = ("new-failures", "new-passes", "status-changes", "added", "re
1076
1157
  default=(),
1077
1158
  help="Restrict output to these categories. Default: all.",
1078
1159
  )
1160
+ @click.option(
1161
+ "--exit-code",
1162
+ is_flag=True,
1163
+ default=False,
1164
+ help="Exit with a code that tells which categories have entries, 0 when the diff is empty. See Exit codes.",
1165
+ )
1166
+ @click.option(
1167
+ "--exit-code-mask",
1168
+ multiple=True,
1169
+ callback=_parse_diff_exit_code_mask,
1170
+ metavar="[" + "|".join(_DIFF_CATEGORIES) + "|all]",
1171
+ help="Categories that don't change the exit code, though they are still shown. Turns on `--exit-code`.",
1172
+ )
1079
1173
  @pass_application
1080
1174
  def diff(
1081
1175
  app: Application,
@@ -1095,6 +1189,8 @@ def diff(
1095
1189
  full_paths: bool,
1096
1190
  message_chars: int,
1097
1191
  only_categories: Tuple[str, ...],
1192
+ exit_code: bool,
1193
+ exit_code_mask: Optional[DiffExitCode],
1098
1194
  ) -> None:
1099
1195
  """\
1100
1196
  Compare two output files: status changes plus added/removed tests.
@@ -1102,12 +1198,32 @@ def diff(
1102
1198
  If `CURRENT` is omitted, it is auto-discovered from the active profile
1103
1199
  so you can diff a saved baseline against the latest run.
1104
1200
 
1201
+ Without `--exit-code`, the exit code is 0 whatever the diff found. With
1202
+ it, the exit code is the sum of the categories that have entries.
1203
+
1204
+ \b
1205
+ Exit codes:
1206
+ ```
1207
+ 0 the diff is empty
1208
+ 1 new failures
1209
+ 2 new passes
1210
+ 4 status changes
1211
+ 8 added tests
1212
+ 16 removed tests
1213
+ 128 an error stopped the command, also without --exit-code
1214
+ ```
1215
+
1216
+ New failures and removed tests, for example, give 17. `--only` and the
1217
+ filters decide what counts, and `--exit-code-mask` leaves categories
1218
+ out of the exit code but not out of the output.
1219
+
1105
1220
  \b
1106
1221
  Examples:
1107
1222
  ```
1108
1223
  robotcode results diff baseline.xml
1109
1224
  robotcode results diff prev/output.xml curr/output.xml
1110
1225
  robotcode results diff baseline.xml --only new-failures
1226
+ robotcode results diff baseline.xml --only new-failures --exit-code
1111
1227
  robotcode results diff baseline.xml -i smoke
1112
1228
  robotcode results diff baseline.xml --search TimeoutError
1113
1229
  robotcode --format json results diff baseline.xml
@@ -1214,6 +1330,9 @@ def diff(
1214
1330
  else:
1215
1331
  app.print_data(data, remove_defaults=True)
1216
1332
 
1333
+ if exit_code or exit_code_mask is not None:
1334
+ app.exit(int(_diff_exit_code(data, exit_code_mask or DiffExitCode.NONE)))
1335
+
1217
1336
 
1218
1337
  def _make_diff_change(
1219
1338
  full_name: str,
@@ -1242,10 +1361,491 @@ def _truncate(text: Optional[str], limit: int) -> Optional[str]:
1242
1361
  return None
1243
1362
  first_line = text.splitlines()[0]
1244
1363
  if limit and len(first_line) > limit:
1245
- return first_line[:limit].rstrip() + "…"
1364
+ return first_line[:limit].rstrip() + "..."
1246
1365
  return first_line
1247
1366
 
1248
1367
 
1368
+ _COMPARE_VIEWS = ("tests", "failures", "elapsed", "messages", "environment")
1369
+
1370
+
1371
+ def _parse_compare_runs(
1372
+ ctx: click.Context, param: click.Parameter, value: Tuple[str, ...]
1373
+ ) -> List[_compare.RunArgument]:
1374
+ """Turn `PATH` and `NAME=PATH` into runs with absolute paths, resolved against the working directory."""
1375
+ runs = [_compare.split_run_argument(v) for v in value]
1376
+ if len(runs) < 2:
1377
+ raise click.UsageError("compare needs at least two runs.", ctx=ctx)
1378
+ names: Set[str] = set()
1379
+ for text, run in zip(value, runs):
1380
+ if run.name is not None:
1381
+ if not run.name:
1382
+ raise click.BadParameter(f"'{text}' has an empty name.", ctx=ctx, param=param)
1383
+ if run.name in names:
1384
+ raise click.BadParameter(f"the name '{run.name}' is given twice.", ctx=ctx, param=param)
1385
+ names.add(run.name)
1386
+ if not run.path.is_file():
1387
+ raise click.BadParameter(f"File '{run.path}' does not exist.", ctx=ctx, param=param)
1388
+ return [_compare.RunArgument(run.path.resolve(), run.name) for run in runs]
1389
+
1390
+
1391
+ def _unique_lower(values: Iterable[str]) -> List[str]:
1392
+ out: List[str] = []
1393
+ for v in values:
1394
+ if v.lower() not in out:
1395
+ out.append(v.lower())
1396
+ return out
1397
+
1398
+
1399
+ @results.command()
1400
+ @click.argument("runs", nargs=-1, metavar="RUN RUN [RUN]...", callback=_parse_compare_runs)
1401
+ @add_options(*RESULT_FILTER_OPTIONS, *SEARCH_OPTIONS)
1402
+ @FULL_PATHS_OPTION
1403
+ @click.option(
1404
+ "--by",
1405
+ "group_by",
1406
+ type=click.Choice(["tag", "suite"], case_sensitive=False),
1407
+ multiple=True,
1408
+ help="Add the counts per tag or suite, one column per run. Repeatable.",
1409
+ )
1410
+ @click.option(
1411
+ "--sort",
1412
+ "group_sort",
1413
+ type=click.Choice(["name", "total", "failed", "elapsed"], case_sensitive=False),
1414
+ default="failed",
1415
+ show_default=True,
1416
+ help="Sort the rows of `--by` by this value in the last run.",
1417
+ )
1418
+ @click.option(
1419
+ "--top",
1420
+ "top_n",
1421
+ type=click.IntRange(min=0),
1422
+ default=0,
1423
+ show_default=True,
1424
+ help="Show at most N rows per table of `--by` and per view (0 = all).",
1425
+ )
1426
+ @click.option(
1427
+ "--show",
1428
+ "views",
1429
+ type=click.Choice(_COMPARE_VIEWS, case_sensitive=False),
1430
+ multiple=True,
1431
+ help="Add this view after the overview. Repeatable.",
1432
+ )
1433
+ @click.option(
1434
+ "--run-order",
1435
+ type=click.Choice(["arguments", "start-time"], case_sensitive=False),
1436
+ default="arguments",
1437
+ show_default=True,
1438
+ help="Order the runs as the arguments are, or by the start time of their top suite.",
1439
+ )
1440
+ @click.option(
1441
+ "--last",
1442
+ "last_n",
1443
+ type=click.IntRange(min=1),
1444
+ default=None,
1445
+ help="Compare only the last N runs, of each group with `--group-by-metadata`.",
1446
+ )
1447
+ @click.option(
1448
+ "--group-by-metadata",
1449
+ "group_metadata",
1450
+ metavar="NAME",
1451
+ default=None,
1452
+ help="Group the runs by the value of this metadata of their top suite.",
1453
+ )
1454
+ @click.option(
1455
+ "--message-chars",
1456
+ type=click.IntRange(min=0),
1457
+ default=120,
1458
+ show_default=True,
1459
+ help="Cut messages and metadata values to N characters (0 = no cut).",
1460
+ )
1461
+ @pass_application
1462
+ def compare(
1463
+ app: Application,
1464
+ runs: List[_compare.RunArgument],
1465
+ status_filters: Tuple[str, ...],
1466
+ include_tags: Tuple[str, ...],
1467
+ exclude_tags: Tuple[str, ...],
1468
+ suite_globs: Tuple[str, ...],
1469
+ test_globs: Tuple[str, ...],
1470
+ by_longname: Tuple[str, ...],
1471
+ exclude_by_longname: Tuple[str, ...],
1472
+ by_test_metadata: Tuple[str, ...],
1473
+ exclude_by_test_metadata: Tuple[str, ...],
1474
+ search_substring: Optional[str],
1475
+ search_regex: Optional[str],
1476
+ full_paths: bool,
1477
+ group_by: Tuple[str, ...],
1478
+ group_sort: str,
1479
+ top_n: int,
1480
+ views: Tuple[str, ...],
1481
+ run_order: str,
1482
+ last_n: Optional[int],
1483
+ group_metadata: Optional[str],
1484
+ message_chars: int,
1485
+ ) -> None:
1486
+ """\
1487
+ Put two or more runs side by side.
1488
+
1489
+ A run is the path of a result file, or `NAME=PATH` to give it a name.
1490
+ The overview, one row per run, always comes first and numbers the runs
1491
+ `#1`, `#2`, ...; `--by` and `--show` add tables and views below it.
1492
+ Tests are matched by their full name, so the runs need the same top
1493
+ suite name (`robot --name`).
1494
+
1495
+ \b
1496
+ Views of `--show`:
1497
+ ```
1498
+ tests status of each test that failed in a run, flaky tests,
1499
+ failing since
1500
+ failures the same failure message over tests and runs
1501
+ elapsed tests and suites that got slower in the last run
1502
+ messages errors and warnings of the runs, new and gone ones
1503
+ environment Robot Framework, Python, platform and metadata
1504
+ ```
1505
+
1506
+ Everything that depends on the order of the runs - failing since,
1507
+ growth, first, new and gone - is computed per group with
1508
+ `--group-by-metadata`. The exit code is 0 whatever the runs show.
1509
+
1510
+ \b
1511
+ Examples:
1512
+ ```
1513
+ robotcode results compare run1/output.xml run2/output.xml run3/output.xml
1514
+ robotcode results compare results/output-*.xml --show tests --last 10
1515
+ robotcode results compare linux=out/linux.xml windows=out/win.xml --by tag
1516
+ robotcode results compare nightly/*.xml --group-by-metadata Platform --show tests
1517
+ robotcode results compare a.xml b.xml c.xml --show failures --show elapsed
1518
+ robotcode --format json results compare a.xml b.xml --show tests
1519
+ ```
1520
+ """
1521
+ # before the result files are read, so an invalid pattern fails at once
1522
+ matcher = make_search_matcher(search_substring, search_regex)
1523
+ dimensions = _unique_lower(group_by)
1524
+ shown = _unique_lower(views)
1525
+
1526
+ def apply_filters(suite: TestSuite) -> None:
1527
+ _apply_tree_filters(
1528
+ suite,
1529
+ include_tags,
1530
+ exclude_tags,
1531
+ suite_globs,
1532
+ test_globs,
1533
+ by_longname,
1534
+ exclude_by_longname,
1535
+ status_filters,
1536
+ matcher,
1537
+ by_test_metadata=by_test_metadata,
1538
+ exclude_by_test_metadata=exclude_by_test_metadata,
1539
+ )
1540
+
1541
+ snapshots = [_compare_snapshot(run, apply_filters, dimensions) for run in runs]
1542
+ groups = _compare.arrange_runs(
1543
+ snapshots,
1544
+ by_start_time=run_order.lower() == "start-time",
1545
+ group_metadata=group_metadata,
1546
+ last=last_n,
1547
+ )
1548
+
1549
+ filters_active = bool(
1550
+ status_filters
1551
+ or include_tags
1552
+ or exclude_tags
1553
+ or suite_globs
1554
+ or test_globs
1555
+ or by_longname
1556
+ or exclude_by_longname
1557
+ or by_test_metadata
1558
+ or exclude_by_test_metadata
1559
+ or search_substring
1560
+ or search_regex
1561
+ )
1562
+ data = _compare_result(
1563
+ groups,
1564
+ grouped=group_metadata is not None,
1565
+ dimensions=dimensions,
1566
+ views=shown,
1567
+ group_sort=group_sort.lower(),
1568
+ top_n=top_n,
1569
+ message_chars=message_chars,
1570
+ )
1571
+ data.group_by_metadata = group_metadata
1572
+ if filters_active:
1573
+ data.filters_applied = _filters_dict(
1574
+ status_filters,
1575
+ include_tags,
1576
+ exclude_tags,
1577
+ suite_globs,
1578
+ test_globs,
1579
+ by_longname,
1580
+ exclude_by_longname,
1581
+ search_substring,
1582
+ search_regex,
1583
+ by_test_metadata=by_test_metadata,
1584
+ exclude_by_test_metadata=exclude_by_test_metadata,
1585
+ )
1586
+
1587
+ if app.config.output_format in (None, OutputFormat.TEXT):
1588
+ app.echo_as_markdown(_render.render_compare(data, views=shown, full_paths=full_paths))
1589
+ else:
1590
+ app.print_data(data, remove_defaults=True)
1591
+
1592
+
1593
+ def _iter_all_suites(suite: TestSuite) -> Iterator[TestSuite]:
1594
+ yield suite
1595
+ for child in suite.suites:
1596
+ yield from _iter_all_suites(child)
1597
+
1598
+
1599
+ def _start_iso(suite: TestSuite) -> Optional[str]:
1600
+ value = _iso(_start_time(suite))
1601
+ # Robot Framework before 7 writes `N/A` for a time it doesn't know
1602
+ return None if value in (None, "", "N/A") else value
1603
+
1604
+
1605
+ def _compare_snapshot(
1606
+ run: _compare.RunArgument,
1607
+ apply_filters: Callable[[TestSuite], None],
1608
+ dimensions: List[str],
1609
+ ) -> _compare.RunSnapshot:
1610
+ execution = _load_execution_result(run.path)
1611
+ suite = execution.suite
1612
+
1613
+ # Before the filters, which move messages and leave suites out.
1614
+ messages = [
1615
+ _compare.ExecutionMessage(str(m.level), str(m.message))
1616
+ for m in (execution.errors.messages if execution.errors is not None else [])
1617
+ ]
1618
+ start_time = _start_iso(suite)
1619
+ # A file that rebot merged from several outputs has no start of its own; its suites have.
1620
+ order_time = start_time or min(
1621
+ (t for t in (_start_iso(child) for child in suite.suites) if t is not None), default=None
1622
+ )
1623
+
1624
+ generator, generation_time = _file_generator(execution, run.path)
1625
+
1626
+ apply_filters(suite)
1627
+ tests = list(_iter_all_tests(suite))
1628
+ return _compare.RunSnapshot(
1629
+ argument=run,
1630
+ status=suite.status,
1631
+ counts=_collect_counts(suite),
1632
+ elapsed_seconds=_elapsed_seconds(suite),
1633
+ start_time=start_time,
1634
+ order_time=order_time,
1635
+ generator=generator,
1636
+ generation_time=generation_time,
1637
+ metadata={str(k): str(v) for k, v in suite.metadata.items()},
1638
+ tests={
1639
+ _get_full_name(t): _compare.RunTest(
1640
+ full_name=_get_full_name(t),
1641
+ status=t.status,
1642
+ elapsed_seconds=_elapsed_seconds(t),
1643
+ message=t.message or "",
1644
+ source=str(t.source) if t.source else None,
1645
+ lineno=t.lineno or None,
1646
+ )
1647
+ for t in tests
1648
+ },
1649
+ suite_elapsed={_get_full_name(s): _elapsed_seconds(s) for s in _iter_all_suites(suite)},
1650
+ messages=messages,
1651
+ buckets={d: _stats_buckets(d, tests) for d in dimensions},
1652
+ )
1653
+
1654
+
1655
+ def _top(items: List[Any], top_n: int) -> Tuple[List[Any], int]:
1656
+ if top_n > 0 and len(items) > top_n:
1657
+ return items[:top_n], len(items) - top_n
1658
+ return items, 0
1659
+
1660
+
1661
+ def _compare_result(
1662
+ groups: List[_compare.RunGroup],
1663
+ *,
1664
+ grouped: bool,
1665
+ dimensions: List[str],
1666
+ views: List[str],
1667
+ group_sort: str,
1668
+ top_n: int,
1669
+ message_chars: int,
1670
+ ) -> CompareResult:
1671
+ runs = _compare.all_runs(groups)
1672
+
1673
+ def file_info(snapshot: _compare.RunSnapshot) -> ResultFileInfo:
1674
+ info = _make_file_info(snapshot.argument.path)
1675
+ info.generator = snapshot.generator
1676
+ info.generation_time = snapshot.generation_time
1677
+ return info
1678
+
1679
+ data = CompareResult(
1680
+ runs=[
1681
+ CompareRun(
1682
+ number=run.number,
1683
+ file=file_info(run.snapshot),
1684
+ status=run.snapshot.status,
1685
+ counts=run.snapshot.counts,
1686
+ name=run.name,
1687
+ group=group.name if grouped else None,
1688
+ start_time=run.snapshot.start_time,
1689
+ elapsed_seconds=run.snapshot.elapsed_seconds,
1690
+ )
1691
+ for group in groups
1692
+ for run in group.runs
1693
+ ]
1694
+ )
1695
+ if grouped:
1696
+ data.groups = [
1697
+ CompareGroup(
1698
+ name=group.name,
1699
+ runs=[run.number for run in group.runs],
1700
+ counts=_compare.sum_counts(run.snapshot.counts for run in group.runs),
1701
+ elapsed_seconds=_compare.sum_elapsed(run.snapshot.elapsed_seconds for run in group.runs),
1702
+ )
1703
+ for group in groups
1704
+ ]
1705
+
1706
+ if dimensions:
1707
+ data.sections = [_compare_stats_section(d, runs, group_sort, top_n) for d in dimensions]
1708
+
1709
+ for view in views:
1710
+ if view == "tests":
1711
+ rows, truncated = _top(_compare.status_rows(groups), top_n)
1712
+ data.tests = CompareTests(
1713
+ tests=[
1714
+ CompareTest(
1715
+ full_name=row.full_name,
1716
+ statuses=row.statuses,
1717
+ per_group=[
1718
+ CompareTestGroup(
1719
+ group=h.group,
1720
+ failed=h.failed,
1721
+ runs=h.runs,
1722
+ flaky=h.flaky,
1723
+ failing_since=h.failing_since,
1724
+ )
1725
+ for h in row.histories
1726
+ ],
1727
+ source=row.test.source,
1728
+ rel_source=_rel_to_cwd(row.test.source),
1729
+ lineno=row.test.lineno,
1730
+ )
1731
+ for row in rows
1732
+ ],
1733
+ truncated=truncated,
1734
+ )
1735
+ elif view == "failures":
1736
+ failures, truncated = _top(_compare.failure_rows(groups), top_n)
1737
+ data.failures = CompareFailures(
1738
+ failures=[
1739
+ CompareFailure(
1740
+ message=_truncate(f.message, message_chars) or "",
1741
+ tests=f.tests,
1742
+ runs=f.per_run,
1743
+ per_group=[
1744
+ CompareFailureGroup(group=group.name, first_run=first)
1745
+ for group, first in zip(groups, f.first_runs)
1746
+ ],
1747
+ )
1748
+ for f in failures
1749
+ ],
1750
+ truncated=truncated,
1751
+ )
1752
+ elif view == "elapsed":
1753
+ suites, suites_truncated = _top(_compare.suite_growth(groups), top_n)
1754
+ tests, tests_truncated = _top(_compare.tests_growth(groups), top_n)
1755
+ data.elapsed = CompareElapsed(
1756
+ suites=[_compare_growth(g) for g in suites],
1757
+ tests=[_compare_growth(g) for g in tests],
1758
+ suites_truncated=suites_truncated,
1759
+ tests_truncated=tests_truncated,
1760
+ )
1761
+ elif view == "messages":
1762
+ messages, truncated = _top(_compare.message_rows(groups), top_n)
1763
+ data.messages = CompareMessages(
1764
+ counts=[CompareLevelCount(level, counts) for level, counts in _compare.level_counts(groups).items()],
1765
+ messages=[
1766
+ CompareMessage(
1767
+ level=m.level,
1768
+ message=_truncate(m.message, message_chars) or "",
1769
+ runs=m.per_run,
1770
+ per_group=[
1771
+ CompareMessageGroup(
1772
+ group=i.group, first_run=i.first_run, last_run=i.last_run, new=i.new, gone=i.gone
1773
+ )
1774
+ for i in m.per_group
1775
+ ],
1776
+ )
1777
+ for m in messages
1778
+ ],
1779
+ truncated=truncated,
1780
+ )
1781
+ elif view == "environment":
1782
+ data.environment = [_compare_environment(run, message_chars) for run in runs]
1783
+ return data
1784
+
1785
+
1786
+ def _compare_stats_section(
1787
+ dimension: str, runs: List[_compare.ComparedRun], group_sort: str, top_n: int
1788
+ ) -> CompareStatsSection:
1789
+ names: List[str] = []
1790
+ for run in runs:
1791
+ for name in run.snapshot.buckets.get(dimension, {}):
1792
+ if name not in names:
1793
+ names.append(name)
1794
+ groups = [
1795
+ CompareStatsGroup(
1796
+ name=name,
1797
+ runs=[
1798
+ CompareCell(counts=g.counts, elapsed_seconds=g.elapsed_seconds)
1799
+ if (g := run.snapshot.buckets.get(dimension, {}).get(name)) is not None
1800
+ else None
1801
+ for run in runs
1802
+ ],
1803
+ )
1804
+ for name in names
1805
+ ]
1806
+
1807
+ def last(g: CompareStatsGroup) -> Optional[CompareCell]:
1808
+ return g.runs[-1] if g.runs else None
1809
+
1810
+ sort_keys: Dict[str, Tuple[Callable[[CompareStatsGroup], Any], bool]] = {
1811
+ "name": (lambda g: g.name.lower(), False),
1812
+ "total": (lambda g: c.counts.total if (c := last(g)) else 0, True),
1813
+ "failed": (lambda g: c.counts.failed if (c := last(g)) else 0, True),
1814
+ "elapsed": (lambda g: (c.elapsed_seconds or 0.0) if (c := last(g)) else 0.0, True),
1815
+ }
1816
+ key, reverse = sort_keys.get(group_sort, sort_keys["failed"])
1817
+ groups.sort(key=key, reverse=reverse)
1818
+ groups, truncated = _top(groups, top_n)
1819
+ return CompareStatsSection(dimension=dimension, groups=groups, truncated=truncated)
1820
+
1821
+
1822
+ def _compare_growth(g: _compare.Growth) -> CompareGrowth:
1823
+ return CompareGrowth(
1824
+ full_name=g.full_name,
1825
+ group=g.group,
1826
+ median_seconds=g.median_seconds,
1827
+ last_seconds=g.last_seconds,
1828
+ growth_seconds=g.growth_seconds,
1829
+ growth_percent=g.growth_percent,
1830
+ )
1831
+
1832
+
1833
+ def _compare_environment(run: _compare.ComparedRun, message_chars: int) -> CompareEnvironment:
1834
+ snapshot = run.snapshot
1835
+ env = CompareEnvironment(
1836
+ run=run.number,
1837
+ metadata={k: _truncate(v, message_chars) or "" for k, v in snapshot.metadata.items()} or None,
1838
+ )
1839
+ if snapshot.generator:
1840
+ generator = _compare.parse_generator(snapshot.generator)
1841
+ env.generator = generator.text
1842
+ env.tool = generator.tool
1843
+ env.version = generator.version
1844
+ env.python = generator.python
1845
+ env.platform = generator.platform
1846
+ return env
1847
+
1848
+
1249
1849
  def _resolve_profile(app: Application) -> Tuple[RobotBaseProfile, Optional[Path]]:
1250
1850
  config_files, root_folder, _ = get_config_files(
1251
1851
  None,
@@ -1287,7 +1887,7 @@ def _auto_discover(app: Application, profile: RobotBaseProfile, search_root: Pat
1287
1887
  raw_output = str(profile.output) if profile.output is not None else None
1288
1888
  if raw_output is not None and raw_output.upper() == "NONE":
1289
1889
  raise click.UsageError(
1290
- "Profile sets `output = NONE` — no result file to inspect. Pass `--output PATH` explicitly."
1890
+ "Profile sets `output = NONE`, so there is no result file to inspect. Pass `--output PATH` explicitly."
1291
1891
  )
1292
1892
 
1293
1893
  out_dir_raw = str(profile.output_dir) if profile.output_dir is not None else "."
@@ -1373,6 +1973,40 @@ def _load_execution_result(path: Path) -> Result:
1373
1973
  raise click.ClickException(f"failed to parse {path}: {e}") from e
1374
1974
 
1375
1975
 
1976
+ def _read_root_generator(path: Path) -> Tuple[Optional[str], Optional[str]]:
1977
+ """`(generator, generated)` from the root element of an `output.xml`, without reading the rest of it.
1978
+
1979
+ An `output.json` that Robot Framework before 7.2 can read was written by its `rebot` and holds only the suite,
1980
+ without these fields.
1981
+ """
1982
+ if path.suffix.lower() == ".json":
1983
+ return None, None
1984
+ try:
1985
+ with path.open("rb") as f:
1986
+ for _event, elem in ElementTree.iterparse(f, events=("start",)):
1987
+ return elem.get("generator"), _iso(elem.get("generated"))
1988
+ except (OSError, ElementTree.ParseError):
1989
+ pass
1990
+ return None, None
1991
+
1992
+
1993
+ if RF_VERSION >= (7, 2):
1994
+
1995
+ def _file_generator(execution: Result, path: Path) -> Tuple[Optional[str], Optional[str]]:
1996
+ """`(generator, generated)` that the result file records."""
1997
+ generator = execution.generator # type: ignore[attr-defined,unused-ignore]
1998
+ generated = execution.generation_time # type: ignore[attr-defined,unused-ignore]
1999
+ return (str(generator) if generator and generator != "unknown" else None), _iso(generated)
2000
+
2001
+ else:
2002
+
2003
+ def _file_generator(execution: Result, path: Path) -> Tuple[Optional[str], Optional[str]]:
2004
+ """`(generator, generated)` that the result file records.
2005
+
2006
+ Robot Framework before 7.2 keeps only whether Robot or Rebot wrote the file, so it is read from the file.
2007
+ """
2008
+ return _read_root_generator(path)
2009
+
1376
2010
  # Each helper below is bound to one of two implementations at import time —
1377
2011
  # the differences between Robot Framework versions are confined to this block.
1378
2012