1# SPDX-License-Identifier: GPL-2.0
2#
3# Generates JSON from KUnit results according to
4# KernelCI spec: https://github.com/kernelci/kernelci-doc/wiki/Test-API
5#
6# Copyright (C) 2020, Google LLC.
7# Author: Heidi Fahim <heidifahim@google.com>
8
9import json
10import os
11
12import kunit_parser
13
14from kunit_parser import TestStatus
15
16def get_json_result(test_result, def_config, build_dir, json_path) -> str:
17	sub_groups = []
18
19	# Each test suite is mapped to a KernelCI sub_group
20	for test_suite in test_result.suites:
21		sub_group = {
22			"name": test_suite.name,
23			"arch": "UM",
24			"defconfig": def_config,
25			"build_environment": build_dir,
26			"test_cases": [],
27			"lab_name": None,
28			"kernel": None,
29			"job": None,
30			"git_branch": "kselftest",
31		}
32		test_cases = []
33		# TODO: Add attachments attribute in test_case with detailed
34		#  failure message, see https://api.kernelci.org/schema-test-case.html#get
35		for case in test_suite.cases:
36			test_case = {"name": case.name, "status": "FAIL"}
37			if case.status == TestStatus.SUCCESS:
38				test_case["status"] = "PASS"
39			elif case.status == TestStatus.TEST_CRASHED:
40				test_case["status"] = "ERROR"
41			test_cases.append(test_case)
42		sub_group["test_cases"] = test_cases
43		sub_groups.append(sub_group)
44	test_group = {
45		"name": "KUnit Test Group",
46		"arch": "UM",
47		"defconfig": def_config,
48		"build_environment": build_dir,
49		"sub_groups": sub_groups,
50		"lab_name": None,
51		"kernel": None,
52		"job": None,
53		"git_branch": "kselftest",
54	}
55	json_obj = json.dumps(test_group, indent=4)
56	if json_path != 'stdout':
57		with open(json_path, 'w') as result_path:
58			result_path.write(json_obj)
59		root = __file__.split('tools/testing/kunit/')[0]
60		kunit_parser.print_with_timestamp(
61			"Test results stored in %s" %
62			os.path.join(root, result_path.name))
63	return json_obj
64