Files
clang-p2996/clang/test/bindings/python/tests/cindex/test_tokens.py
Jannick Kremer a75587d271 [clang][python][test] Move python binding tests to lit framework (#146486)
As discussed in PR #142353, the current testsuite of the `clang` Python
bindings has several issues:

- It `libclang.so` cannot be loaded into `python` to run the testsuite,
the whole `ninja check-all` aborts.
- The result of running the testsuite isn't report like the `lit`-based
tests, rendering them almost invisible.
- The testsuite is disabled in a non-obvious way (`RUN_PYTHON_TESTS`) in
`tests/CMakeLists.txt`, which again doesn't show up in the test results.

All these issues can be avoided by integrating the Python bindings tests
with `lit`, which is what this patch does:

- The actual test lives in `clang/test/bindings/python/bindings.sh` and
is run by `lit`.
- The current `clang/bindings/python/tests` directory (minus the
now-subperfluous `CMakeLists.txt`) is moved into the same directory.
- The check if `libclang` is loadable (originally from PR #142353) is
now handled via a new `lit` feature, `libclang-loadable`.
- The various ways to disable the tests have been turned into `XFAIL`s
as appropriate. This isn't complete and not completely tested yet.

Tested on `sparc-sun-solaris2.11`, `sparcv9-sun-solaris2.11`,
`i386-pc-solaris2.11`, `amd64-pc-solaris2.11`, `i686-pc-linux-gnu`, and
`x86_64-pc-linux-gnu`.

Co-authored-by: Rainer Orth <ro@gcc.gnu.org>
2025-07-02 10:11:48 +02:00

56 lines
1.7 KiB
Python

import os
from clang.cindex import Config, CursorKind, SourceLocation, SourceRange, TokenKind
if "CLANG_LIBRARY_PATH" in os.environ:
Config.set_library_path(os.environ["CLANG_LIBRARY_PATH"])
import unittest
from .util import get_tu
class TestTokens(unittest.TestCase):
def test_token_to_cursor(self):
"""Ensure we can obtain a Cursor from a Token instance."""
tu = get_tu("int i = 5;")
r = tu.get_extent("t.c", (0, 9))
tokens = list(tu.get_tokens(extent=r))
self.assertEqual(len(tokens), 4)
self.assertEqual(tokens[1].spelling, "i")
self.assertEqual(tokens[1].kind, TokenKind.IDENTIFIER)
cursor = tokens[1].cursor
self.assertEqual(cursor.kind, CursorKind.VAR_DECL)
self.assertEqual(tokens[1].cursor, tokens[2].cursor)
def test_token_location(self):
"""Ensure Token.location works."""
tu = get_tu("int foo = 10;")
r = tu.get_extent("t.c", (0, 11))
tokens = list(tu.get_tokens(extent=r))
self.assertEqual(len(tokens), 4)
loc = tokens[1].location
self.assertIsInstance(loc, SourceLocation)
self.assertEqual(loc.line, 1)
self.assertEqual(loc.column, 5)
self.assertEqual(loc.offset, 4)
def test_token_extent(self):
"""Ensure Token.extent works."""
tu = get_tu("int foo = 10;")
r = tu.get_extent("t.c", (0, 11))
tokens = list(tu.get_tokens(extent=r))
self.assertEqual(len(tokens), 4)
extent = tokens[1].extent
self.assertIsInstance(extent, SourceRange)
self.assertEqual(extent.start.offset, 4)
self.assertEqual(extent.end.offset, 7)