twister: reporting: Add custom JSON encoder

Refactor Reporting to use custom ReportingJSONEncoder and encode
all pathlib.Path derived instances there which are possible
e.g. in 'environment.options' received from command line.

Fixes: #83823

Signed-off-by: Dmitrii Golovanov <dmitrii.golovanov@intel.com>
This commit is contained in:
Dmitrii Golovanov 2025-01-21 16:53:11 +01:00 committed by Benjamin Cabé
parent abb83b97e7
commit aa705089d3

View file

@ -11,7 +11,7 @@ import string
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
from datetime import datetime from datetime import datetime
from enum import Enum from enum import Enum
from pathlib import Path, PosixPath from pathlib import Path
from colorama import Fore from colorama import Fore
from twisterlib.statuses import TwisterStatus from twisterlib.statuses import TwisterStatus
@ -29,6 +29,13 @@ class ReportStatus(str, Enum):
SKIP = 'skipped' SKIP = 'skipped'
class ReportingJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Path):
return str(obj)
return super().default(obj)
class Reporting: class Reporting:
json_filters = { json_filters = {
@ -294,10 +301,6 @@ class Reporting:
else: else:
report_options = self.env.non_default_options() report_options = self.env.non_default_options()
# Resolve known JSON serialization problems.
for k,v in report_options.items():
report_options[k] = str(v) if type(v) in [PosixPath] else v
report = {} report = {}
report["environment"] = {"os": os.name, report["environment"] = {"os": os.name,
"zephyr_version": version, "zephyr_version": version,
@ -483,7 +486,7 @@ class Reporting:
report["testsuites"] = suites report["testsuites"] = suites
with open(filename, 'w') as json_file: with open(filename, 'w') as json_file:
json.dump(report, json_file, indent=4, separators=(',',':')) json.dump(report, json_file, indent=4, separators=(',',':'), cls=ReportingJSONEncoder)
def compare_metrics(self, filename): def compare_metrics(self, filename):