xref: /linux/tools/testing/selftests/net/lib/py/ksft.py (revision 99583b970b9073ea258235e6c794fd515df19c61)
1# SPDX-License-Identifier: GPL-2.0
2
3import builtins
4import inspect
5import traceback
6from .consts import KSFT_MAIN_NAME
7
8KSFT_RESULT = None
9
10
11class KsftSkipEx(Exception):
12    pass
13
14
15class KsftXfailEx(Exception):
16    pass
17
18
19def ksft_pr(*objs, **kwargs):
20    print("#", *objs, **kwargs)
21
22
23def _fail(*args):
24    global KSFT_RESULT
25    KSFT_RESULT = False
26
27    frame = inspect.stack()[2]
28    ksft_pr("At " + frame.filename + " line " + str(frame.lineno) + ":")
29    ksft_pr(*args)
30
31
32def ksft_eq(a, b, comment=""):
33    global KSFT_RESULT
34    if a != b:
35        _fail("Check failed", a, "!=", b, comment)
36
37
38def ksft_true(a, comment=""):
39    if not a:
40        _fail("Check failed", a, "does not eval to True", comment)
41
42
43def ksft_in(a, b, comment=""):
44    if a not in b:
45        _fail("Check failed", a, "not in", b, comment)
46
47
48def ksft_ge(a, b, comment=""):
49    if a < b:
50        _fail("Check failed", a, "<", b, comment)
51
52
53def ktap_result(ok, cnt=1, case="", comment=""):
54    res = ""
55    if not ok:
56        res += "not "
57    res += "ok "
58    res += str(cnt) + " "
59    res += KSFT_MAIN_NAME
60    if case:
61        res += "." + str(case.__name__)
62    if comment:
63        res += " # " + comment
64    print(res)
65
66
67def ksft_run(cases, args=()):
68    totals = {"pass": 0, "fail": 0, "skip": 0, "xfail": 0}
69
70    print("KTAP version 1")
71    print("1.." + str(len(cases)))
72
73    global KSFT_RESULT
74    cnt = 0
75    for case in cases:
76        KSFT_RESULT = True
77        cnt += 1
78        try:
79            case(*args)
80        except KsftSkipEx as e:
81            ktap_result(True, cnt, case, comment="SKIP " + str(e))
82            totals['skip'] += 1
83            continue
84        except KsftXfailEx as e:
85            ktap_result(True, cnt, case, comment="XFAIL " + str(e))
86            totals['xfail'] += 1
87            continue
88        except Exception as e:
89            tb = traceback.format_exc()
90            for line in tb.strip().split('\n'):
91                ksft_pr("Exception|", line)
92            ktap_result(False, cnt, case)
93            totals['fail'] += 1
94            continue
95
96        ktap_result(KSFT_RESULT, cnt, case)
97        totals['pass'] += 1
98
99    print(
100        f"# Totals: pass:{totals['pass']} fail:{totals['fail']} xfail:{totals['xfail']} xpass:0 skip:{totals['skip']} error:0"
101    )
102