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 Test, TestResult, TestStatus
15from typing import Any, Dict, Optional
16
17JsonObj = Dict[str, Any]
18
19def _get_group_json(test: Test, def_config: str,
20		build_dir: Optional[str]) -> JsonObj:
21	sub_groups = []  # List[JsonObj]
22	test_cases = []  # List[JsonObj]
23
24	for subtest in test.subtests:
25		if len(subtest.subtests):
26			sub_group = _get_group_json(subtest, def_config,
27				build_dir)
28			sub_groups.append(sub_group)
29		else:
30			test_case = {"name": subtest.name, "status": "FAIL"}
31			if subtest.status == TestStatus.SUCCESS:
32				test_case["status"] = "PASS"
33			elif subtest.status == TestStatus.TEST_CRASHED:
34				test_case["status"] = "ERROR"
35			test_cases.append(test_case)
36
37	test_group = {
38		"name": test.name,
39		"arch": "UM",
40		"defconfig": def_config,
41		"build_environment": build_dir,
42		"sub_groups": sub_groups,
43		"test_cases": test_cases,
44		"lab_name": None,
45		"kernel": None,
46		"job": None,
47		"git_branch": "kselftest",
48	}
49	return test_group
50
51def get_json_result(test_result: TestResult, def_config: str,
52		build_dir: Optional[str], json_path: str) -> str:
53	test_group = _get_group_json(test_result.test, def_config, build_dir)
54	test_group["name"] = "KUnit Test Group"
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