aboutsummaryrefslogtreecommitdiffstats
path: root/.github/scripts/tests/generate-summary.py
blob: 1dae6aba4b3ba7619abdcc5fe64dce062dc8d64f (plain) (blame)
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
174
#!/usr/bin/env python3
import argparse
import dataclasses
import os, sys
from enum import Enum
from itertools import groupby
from operator import attrgetter
from typing import List
from jinja2 import Environment, FileSystemLoader
from junit_utils import get_property_value, iter_xml_files


class TestStatus(Enum):
    PASS = 0
    FAIL = 1
    ERROR = 2
    SKIP = 3
    MUTE = 4

    def __lt__(self, other):
        return self.value < other.value


@dataclasses.dataclass
class TestResult:
    classname: str
    name: str
    status: TestStatus

    @property
    def status_display(self):
        return {
            TestStatus.PASS: "PASS",
            TestStatus.FAIL: "FAIL",
            TestStatus.ERROR: "ERROR",
            TestStatus.SKIP: "SKIP",
            TestStatus.MUTE: "MUTE",
        }[self.status]

    def __str__(self):
        return f"{self.full_name:<138} {self.status_display}"

    @property
    def full_name(self):
        return f"{self.classname}/{self.name}"


def render_pm(value, url, diff=None):
    if value:
        text = f"[{value}]({url})"
    else:
        text = str(value)

    if diff is not None and diff != 0:
        if diff == 0:
            sign = "±"
        elif diff < 0:
            sign = "-"
        else:
            sign = "+"

        text = f"{text} {sign}{abs(diff)}"

    return text


def render_testlist_html(rows, fn):
    TEMPLATES_PATH = os.path.join(os.path.dirname(__file__), "templates")

    env = Environment(loader=FileSystemLoader(TEMPLATES_PATH))

    rows.sort(key=attrgetter('full_name'))
    rows.sort(key=attrgetter('status'), reverse=True)

    rows = groupby(rows, key=attrgetter('status'))
    content = env.get_template("summary.html").render(test_results=rows)

    with open(fn, 'w') as fp:
        fp.write(content)


def write_summary(lines: List[str]):
    summary_fn = os.environ.get("GITHUB_STEP_SUMMARY")
    if summary_fn:
        fp = open(summary_fn, "at")
    else:
        fp = sys.stdout

    for line in lines:
        fp.write(f"{line}\n")
    fp.write("\n")

    if summary_fn:
        fp.close()


def gen_summary(summary_url_prefix, summary_out_folder, paths, ):
    summary = [
        "|      | TESTS | PASSED | ERRORS | FAILED | SKIPPED | MUTED[^1] |",
        "| :--- | ---:  | -----: | -----: | -----: | ------: | ----: |",
    ]
    for title, html_fn, path in paths:
        tests = failed = errors = muted = skipped = passed = 0

        test_results = []

        for fn, suite, case in iter_xml_files(path):
            tests += 1
            classname, name = case.get("classname"), case.get("name")
            if case.find("failure") is not None:
                failed += 1
                status = TestStatus.FAIL
            elif case.find("error") is not None:
                errors += 1
                status = TestStatus.ERROR
            elif get_property_value(case, "mute") is not None:
                muted += 1
                status = TestStatus.MUTE
            elif case.find("skipped") is not None:
                skipped += 1
                status = TestStatus.SKIP
            else:
                passed += 1
                status = TestStatus.PASS

            test_result = TestResult(classname=classname, name=name, status=status)
            test_results.append(test_result)

        report_url = f'{summary_url_prefix}{html_fn}'

        render_testlist_html(test_results, os.path.join(summary_out_folder, html_fn))

        summary.append(
            " | ".join(
                [
                    title,
                    render_pm(tests, f'{report_url}', 0),
                    render_pm(passed, f'{report_url}#PASS', 0),
                    render_pm(errors, f'{report_url}#ERROR', 0),
                    render_pm(failed, f'{report_url}#FAIL', 0),
                    render_pm(skipped, f'{report_url}#SKIP', 0),
                    render_pm(muted, f'{report_url}#MUTE', 0),
                ]
            )
        )

    github_srv = os.environ.get('GITHUB_SERVER_URL', 'https://github.com')
    repo = os.environ.get('GITHUB_REPOSITORY', 'ydb-platform/ydb')

    summary.append("\n")
    summary.append(f"[^1]: All mute rules are defined [here]({github_srv}/{repo}/tree/main/.github/config).")

    write_summary(lines=summary)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--summary-out-path", required=True)
    parser.add_argument("--summary-url-prefix", required=True)
    parser.add_argument("args", nargs="+", metavar="TITLE html_out path")
    args = parser.parse_args()

    if len(args.args) % 3 != 0:
        print("Invalid argument count")
        raise SystemExit(-1)

    paths = iter(args.args)
    title_path = list(zip(paths, paths, paths))

    gen_summary(args.summary_url_prefix, args.summary_out_path, title_path)


if __name__ == "__main__":
    main()