xref: /linux/tools/testing/selftests/net/lib/py/ksft.py (revision ab93e0dd72c37d378dd936f031ffb83ff2bd87ce)
1# SPDX-License-Identifier: GPL-2.0
2
3import builtins
4import functools
5import inspect
6import signal
7import sys
8import time
9import traceback
10from .consts import KSFT_MAIN_NAME
11from .utils import global_defer_queue
12
13KSFT_RESULT = None
14KSFT_RESULT_ALL = True
15KSFT_DISRUPTIVE = True
16
17
18class KsftFailEx(Exception):
19    pass
20
21
22class KsftSkipEx(Exception):
23    pass
24
25
26class KsftXfailEx(Exception):
27    pass
28
29
30class KsftTerminate(KeyboardInterrupt):
31    pass
32
33
34def ksft_pr(*objs, **kwargs):
35    kwargs["flush"] = True
36    print("#", *objs, **kwargs)
37
38
39def _fail(*args):
40    global KSFT_RESULT
41    KSFT_RESULT = False
42
43    stack = inspect.stack()
44    started = False
45    for frame in reversed(stack[2:]):
46        # Start printing from the test case function
47        if not started:
48            if frame.function == 'ksft_run':
49                started = True
50            continue
51
52        ksft_pr("Check| At " + frame.filename + ", line " + str(frame.lineno) +
53                ", in " + frame.function + ":")
54        ksft_pr("Check|     " + frame.code_context[0].strip())
55    ksft_pr(*args)
56
57
58def ksft_eq(a, b, comment=""):
59    global KSFT_RESULT
60    if a != b:
61        _fail("Check failed", a, "!=", b, comment)
62
63
64def ksft_ne(a, b, comment=""):
65    global KSFT_RESULT
66    if a == b:
67        _fail("Check failed", a, "==", b, comment)
68
69
70def ksft_true(a, comment=""):
71    if not a:
72        _fail("Check failed", a, "does not eval to True", comment)
73
74
75def ksft_in(a, b, comment=""):
76    if a not in b:
77        _fail("Check failed", a, "not in", b, comment)
78
79
80def ksft_not_in(a, b, comment=""):
81    if a in b:
82        _fail("Check failed", a, "in", b, comment)
83
84
85def ksft_is(a, b, comment=""):
86    if a is not b:
87        _fail("Check failed", a, "is not", b, comment)
88
89
90def ksft_ge(a, b, comment=""):
91    if a < b:
92        _fail("Check failed", a, "<", b, comment)
93
94
95def ksft_lt(a, b, comment=""):
96    if a >= b:
97        _fail("Check failed", a, ">=", b, comment)
98
99
100class ksft_raises:
101    def __init__(self, expected_type):
102        self.exception = None
103        self.expected_type = expected_type
104
105    def __enter__(self):
106        return self
107
108    def __exit__(self, exc_type, exc_val, exc_tb):
109        if exc_type is None:
110            _fail(f"Expected exception {str(self.expected_type.__name__)}, none raised")
111        elif self.expected_type != exc_type:
112            _fail(f"Expected exception {str(self.expected_type.__name__)}, raised {str(exc_type.__name__)}")
113        self.exception = exc_val
114        # Suppress the exception if its the expected one
115        return self.expected_type == exc_type
116
117
118def ksft_busy_wait(cond, sleep=0.005, deadline=1, comment=""):
119    end = time.monotonic() + deadline
120    while True:
121        if cond():
122            return
123        if time.monotonic() > end:
124            _fail("Waiting for condition timed out", comment)
125            return
126        time.sleep(sleep)
127
128
129def ktap_result(ok, cnt=1, case="", comment=""):
130    global KSFT_RESULT_ALL
131    KSFT_RESULT_ALL = KSFT_RESULT_ALL and ok
132
133    res = ""
134    if not ok:
135        res += "not "
136    res += "ok "
137    res += str(cnt) + " "
138    res += KSFT_MAIN_NAME
139    if case:
140        res += "." + str(case.__name__)
141    if comment:
142        res += " # " + comment
143    print(res, flush=True)
144
145
146def ksft_flush_defer():
147    global KSFT_RESULT
148
149    i = 0
150    qlen_start = len(global_defer_queue)
151    while global_defer_queue:
152        i += 1
153        entry = global_defer_queue.pop()
154        try:
155            entry.exec_only()
156        except:
157            ksft_pr(f"Exception while handling defer / cleanup (callback {i} of {qlen_start})!")
158            tb = traceback.format_exc()
159            for line in tb.strip().split('\n'):
160                ksft_pr("Defer Exception|", line)
161            KSFT_RESULT = False
162
163
164def ksft_disruptive(func):
165    """
166    Decorator that marks the test as disruptive (e.g. the test
167    that can down the interface). Disruptive tests can be skipped
168    by passing DISRUPTIVE=False environment variable.
169    """
170
171    @functools.wraps(func)
172    def wrapper(*args, **kwargs):
173        if not KSFT_DISRUPTIVE:
174            raise KsftSkipEx(f"marked as disruptive")
175        return func(*args, **kwargs)
176    return wrapper
177
178
179def ksft_setup(env):
180    """
181    Setup test framework global state from the environment.
182    """
183
184    def get_bool(env, name):
185        value = env.get(name, "").lower()
186        if value in ["yes", "true"]:
187            return True
188        if value in ["no", "false"]:
189            return False
190        try:
191            return bool(int(value))
192        except:
193            raise Exception(f"failed to parse {name}")
194
195    if "DISRUPTIVE" in env:
196        global KSFT_DISRUPTIVE
197        KSFT_DISRUPTIVE = get_bool(env, "DISRUPTIVE")
198
199    return env
200
201
202def _ksft_intr(signum, frame):
203    # ksft runner.sh sends 2 SIGTERMs in a row on a timeout
204    # if we don't ignore the second one it will stop us from handling cleanup
205    global term_cnt
206    term_cnt += 1
207    if term_cnt == 1:
208        raise KsftTerminate()
209    else:
210        ksft_pr(f"Ignoring SIGTERM (cnt: {term_cnt}), already exiting...")
211
212
213def ksft_run(cases=None, globs=None, case_pfx=None, args=()):
214    cases = cases or []
215
216    if globs and case_pfx:
217        for key, value in globs.items():
218            if not callable(value):
219                continue
220            for prefix in case_pfx:
221                if key.startswith(prefix):
222                    cases.append(value)
223                    break
224
225    global term_cnt
226    term_cnt = 0
227    prev_sigterm = signal.signal(signal.SIGTERM, _ksft_intr)
228
229    totals = {"pass": 0, "fail": 0, "skip": 0, "xfail": 0}
230
231    print("TAP version 13", flush=True)
232    print("1.." + str(len(cases)), flush=True)
233
234    global KSFT_RESULT
235    cnt = 0
236    stop = False
237    for case in cases:
238        KSFT_RESULT = True
239        cnt += 1
240        comment = ""
241        cnt_key = ""
242
243        try:
244            case(*args)
245        except KsftSkipEx as e:
246            comment = "SKIP " + str(e)
247            cnt_key = 'skip'
248        except KsftXfailEx as e:
249            comment = "XFAIL " + str(e)
250            cnt_key = 'xfail'
251        except BaseException as e:
252            stop |= isinstance(e, KeyboardInterrupt)
253            tb = traceback.format_exc()
254            for line in tb.strip().split('\n'):
255                ksft_pr("Exception|", line)
256            if stop:
257                ksft_pr(f"Stopping tests due to {type(e).__name__}.")
258            KSFT_RESULT = False
259            cnt_key = 'fail'
260
261        ksft_flush_defer()
262
263        if not cnt_key:
264            cnt_key = 'pass' if KSFT_RESULT else 'fail'
265
266        ktap_result(KSFT_RESULT, cnt, case, comment=comment)
267        totals[cnt_key] += 1
268
269        if stop:
270            break
271
272    signal.signal(signal.SIGTERM, prev_sigterm)
273
274    print(
275        f"# Totals: pass:{totals['pass']} fail:{totals['fail']} xfail:{totals['xfail']} xpass:0 skip:{totals['skip']} error:0"
276    )
277
278
279def ksft_exit():
280    global KSFT_RESULT_ALL
281    sys.exit(0 if KSFT_RESULT_ALL else 1)
282