From 3aa64377ca68fda6f137f5e68c933c53d2986d44 Mon Sep 17 00:00:00 2001
From: Anders Roxell <anders.roxell@linaro.org>
Date: Mon, 14 Apr 2025 15:35:46 +0200
Subject: [PATCH] results: parse: add log excerpt extraction for test cases

Store parsed log lines and extract a log excerpt for each test case
that includes both 'starttc' and 'endtc'. This allows a subset of
log messages to be attached to individual test results for better
context when reviewing failures.

Ensure at least one line is included even when starttc == endtc,
by applying '+1' to the calculated log length.

Fix the ordering of log excerpts to preserve chronological order
instead of printing logs in reverse.

Intermediate log lines are stored in self.__log_lines__ and
cleared after each excerpt is attached.

Signed-off-by: Anders Roxell <anders.roxell@linaro.org>
---
 tuxrun/results.py | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/tuxrun/results.py b/tuxrun/results.py
index 0c54e7057e86..cce6b2ac69ee 100644
--- a/tuxrun/results.py
+++ b/tuxrun/results.py
@@ -26,10 +26,12 @@ class Results:
         self.__post_processed = False
         self.__tests__ = ["lava"] + [t.name for t in tests]
         self.__ret__ = 0
+        self.__log_lines__ = []
 
     def parse(self, line):
         try:
             data = yaml_load(line)
+            self.__log_lines__.append(data)
         except yaml.YAMLError:
             LOG.debug(line)
             return
@@ -67,6 +69,15 @@ class Results:
                 )
         else:
             self.__data__.setdefault(definition, {})[case] = test
+            if "starttc" in test and "endtc" in test:
+                # If starttc and endtc are the same, then log_diff = 0 and no lines will be shown.
+                # To ensure at least one line is displayed, add '+1'.
+                log_diff = (test["endtc"] - test["starttc"]) + 1
+                self.__data__[definition][case]["log_excerpt"] = [
+                    f"[{entry['dt']}] {entry['msg']}"
+                    for entry in self.__log_lines__[-(log_diff + 1) : -1]
+                ]
+                self.__log_lines__.clear()
         if test["result"] == "fail":
             self.__ret__ = 1
 
-- 
2.47.2

