xref: /linux/tools/unittests/test_cmatch.py (revision 9aaeb817ef4f794d1dbb8736332a64b5dae9521c)
1#!/usr/bin/env python3
2# SPDX-License-Identifier: GPL-2.0
3# Copyright(c) 2026: Mauro Carvalho Chehab <mchehab@kernel.org>.
4#
5# pylint: disable=C0413,R0904
6
7
8"""
9Unit tests for kernel-doc CMatch.
10"""
11
12import os
13import re
14import sys
15import unittest
16
17
18# Import Python modules
19
20SRC_DIR = os.path.dirname(os.path.realpath(__file__))
21sys.path.insert(0, os.path.join(SRC_DIR, "../lib/python"))
22
23from kdoc.c_lex import CMatch
24from kdoc.xforms_lists import CTransforms
25from unittest_helper import run_unittest
26
27#
28# Override unittest.TestCase to better compare diffs ignoring whitespaces
29#
30class TestCaseDiff(unittest.TestCase):
31    """
32    Disable maximum limit on diffs and add a method to better
33    handle diffs with whitespace differences.
34    """
35
36    @classmethod
37    def setUpClass(cls):
38        """Ensure that there won't be limit for diffs"""
39        cls.maxDiff = None
40
41
42#
43# Tests doing with different macros
44#
45
46class TestSearch(TestCaseDiff):
47    """
48    Test search mechanism
49    """
50
51    def test_search_acquires_simple(self):
52        line = "__acquires(ctx) foo();"
53        result = ", ".join(CMatch("__acquires").search(line))
54        self.assertEqual(result, "__acquires(ctx)")
55
56    def test_search_acquires_multiple(self):
57        line = "__acquires(ctx) __acquires(other) bar();"
58        result = ", ".join(CMatch("__acquires").search(line))
59        self.assertEqual(result, "__acquires(ctx), __acquires(other)")
60
61    def test_search_acquires_nested_paren(self):
62        line = "__acquires((ctx1, ctx2)) baz();"
63        result = ", ".join(CMatch("__acquires").search(line))
64        self.assertEqual(result, "__acquires((ctx1, ctx2))")
65
66    def test_search_must_hold(self):
67        line = "__must_hold(&lock) do_something();"
68        result = ", ".join(CMatch("__must_hold").search(line))
69        self.assertEqual(result, "__must_hold(&lock)")
70
71    def test_search_must_hold_shared(self):
72        line = "__must_hold_shared(RCU) other();"
73        result = ", ".join(CMatch("__must_hold_shared").search(line))
74        self.assertEqual(result, "__must_hold_shared(RCU)")
75
76    def test_search_no_false_positive(self):
77        line = "call__acquires(foo);  // should stay intact"
78        result = ", ".join(CMatch(r"\b__acquires").search(line))
79        self.assertEqual(result, "")
80
81    def test_search_no_macro_remains(self):
82        line = "do_something_else();"
83        result = ", ".join(CMatch("__acquires").search(line))
84        self.assertEqual(result, "")
85
86    def test_search_no_function(self):
87        line = "something"
88        result = ", ".join(CMatch(line).search(line))
89        self.assertEqual(result, "")
90
91#
92# Run all tests
93#
94if __name__ == "__main__":
95    run_unittest(__file__)
96