summaryrefslogtreecommitdiff
path: root/util/zephyr_to_resultdb.py
blob: 48bfe151e430670b0bbff23f46cb4fb986735133 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#!/usr/bin/env python3
# Copyright 2022 The ChromiumOS Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Upload twister results to ResultDB

    Usage:
    $ rdb stream -new -realm chromium:public -- ./util/zephyr_to_resultdb.py
      --results=twister-out/twister.json --upload=True
"""

import argparse
import base64
import json
import os

import requests  # pylint: disable=import-error


def translate_status(status):
    """Translates ZTEST status to ResultDB status"""
    ret_status = "SKIP"

    if status == "passed":
        ret_status = "PASS"
    elif status == "failed":
        ret_status = "FAIL"
    elif status in ["skipped", "filtered"]:
        ret_status = "SKIP"

    return ret_status


def translate_expected(status):
    """Translates ZTEST status to ResultDB expected"""
    flag = False

    if status in ["passed", "filtered"]:
        flag = True

    return flag


def translate_duration(testcase):
    """Translates ZTEST execution_time to ResultDB duration"""
    time = testcase.get("execution_time")
    if not time:
        return None

    return f"{time}ms"


def testcase_summary(testcase):
    """Translates ZTEST testcase to ResultDB summaryHtml"""
    html = "<p>None</p>"

    if (
        "log" in testcase
        or "reason" in testcase
        or translate_status(testcase["status"]) == "SKIP"
    ):
        html = (
            '<p><text-artifact artifact-id="artifact-content-in-request"></p>'
        )

    return html


def testcase_artifact(testcase):
    """Translates ZTEST testcase to ResultDB artifact"""
    artifact = "Unknown"

    if "log" in testcase and testcase["log"]:
        artifact = testcase["log"]
    elif "reason" in testcase and testcase["reason"]:
        artifact = testcase["reason"]
    elif testcase["status"] == "filtered":
        artifact = "filtered"
    elif testcase["status"] == "skipped":
        artifact = "skipped"

    return base64.b64encode(artifact.encode())


def testcase_to_result(testsuite, testcase):
    """Translates ZTEST testcase to ResultDB format"""
    result = {
        "testId": testcase["identifier"],
        "status": translate_status(testcase["status"]),
        "expected": translate_expected(testcase["status"]),
        "summaryHtml": testcase_summary(testcase),
        "artifacts": {
            "artifact-content-in-request": {
                "contents": testcase_artifact(testcase),
            }
        },
        # TODO(b/239952573) Add all test configs as tags
        "tags": [
            {"key": "category", "value": "ChromeOS/EC"},
            {"key": "platform", "value": testsuite["platform"]},
        ],
        "duration": translate_duration(testcase),
        "testMetadata": {"name": testcase["identifier"]},
    }

    return result


def json_to_resultdb(result_file):
    """Translates Twister json test report to ResultDB format"""
    with open(result_file) as file:
        data = json.load(file)
        results = []

        for testsuite in data["testsuites"]:
            for testcase in testsuite["testcases"]:
                if testcase["status"]:
                    results.append(testcase_to_result(testsuite, testcase))

        file.close()

    return results


class BytesEncoder(json.JSONEncoder):
    """Encoder for ResultDB format"""

    def default(self, obj):
        if isinstance(obj, bytes):
            return obj.decode("utf-8")
        return json.JSONEncoder.default(self, obj)


def upload_results(results):
    """Upload results to ResultDB"""
    with open(os.environ["LUCI_CONTEXT"]) as file:
        sink = json.load(file)["result_sink"]

    # Uploads all test results at once.
    res = requests.post(
        url="http://%s/prpc/luci.resultsink.v1.Sink/ReportTestResults"
        % sink["address"],
        headers={
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Authorization": "ResultSink %s" % sink["auth_token"],
        },
        data=json.dumps({"testResults": results}, cls=BytesEncoder),
    )
    res.raise_for_status()


def main():
    """main"""
    # Set up argument parser.
    parser = argparse.ArgumentParser(
        description=("Upload Zephyr Twister test results to ResultDB")
    )
    parser.add_argument("--results")
    parser.add_argument("--upload", default=False)
    args = parser.parse_args()

    if args.results:
        print("Converting:", args.results)
        rdb_results = json_to_resultdb(args.results)
        if args.upload:
            upload_results(rdb_results)
    else:
        raise Exception("Missing test result file for conversion")


if __name__ == "__main__":
    main()