102 lines · python
1import os2from pathlib import Path3 4from clang.cindex import Config, SourceLocation, SourceRange, TranslationUnit5 6if "CLANG_LIBRARY_PATH" in os.environ:7 Config.set_library_path(os.environ["CLANG_LIBRARY_PATH"])8 9import unittest10 11from .util import get_tu12 13INPUTS_DIR = Path(__file__).parent / "INPUTS"14 15 16def create_range(tu, line1, column1, line2, column2):17 return SourceRange.from_locations(18 SourceLocation.from_position(tu, tu.get_file(tu.spelling), line1, column1),19 SourceLocation.from_position(tu, tu.get_file(tu.spelling), line2, column2),20 )21 22 23class TestSourceRange(unittest.TestCase):24 def test_contains(self):25 tu = get_tu(26 """aaaaa27aaaaa28aaaaa29aaaaa"""30 )31 file = tu.get_file(tu.spelling)32 33 l13 = SourceLocation.from_position(tu, file, 1, 3)34 l21 = SourceLocation.from_position(tu, file, 2, 1)35 l22 = SourceLocation.from_position(tu, file, 2, 2)36 l23 = SourceLocation.from_position(tu, file, 2, 3)37 l24 = SourceLocation.from_position(tu, file, 2, 4)38 l25 = SourceLocation.from_position(tu, file, 2, 5)39 l33 = SourceLocation.from_position(tu, file, 3, 3)40 l31 = SourceLocation.from_position(tu, file, 3, 1)41 r22_24 = create_range(tu, 2, 2, 2, 4)42 r23_23 = create_range(tu, 2, 3, 2, 3)43 r24_32 = create_range(tu, 2, 4, 3, 2)44 r14_32 = create_range(tu, 1, 4, 3, 2)45 46 assert l13 not in r22_24 # Line before start47 assert l21 not in r22_24 # Column before start48 assert l22 in r22_24 # Colum on start49 assert l23 in r22_24 # Column in range50 assert l24 in r22_24 # Column on end51 assert l25 not in r22_24 # Column after end52 assert l33 not in r22_24 # Line after end53 54 assert l23 in r23_23 # In one-column range55 56 assert l23 not in r24_32 # Outside range in first line57 assert l33 not in r24_32 # Outside range in last line58 assert l25 in r24_32 # In range in first line59 assert l31 in r24_32 # In range in last line60 61 assert l21 in r14_32 # In range at start of center line62 assert l25 in r14_32 # In range at end of center line63 64 # In range within included file65 tu2 = TranslationUnit.from_source(66 "main.c",67 unsaved_files=[68 (69 "main.c",70 """int a[] = {71#include "numbers.inc"72};73""",74 ),75 (76 "./numbers.inc",77 """1,782,793,80481 """,82 ),83 ],84 )85 86 r_curly = create_range(tu2, 1, 11, 3, 1)87 l_f2 = SourceLocation.from_position(tu2, tu2.get_file("./numbers.inc"), 4, 1)88 assert l_f2 in r_curly89 90 def test_equality(self):91 path = INPUTS_DIR / "testfile.c"92 tu = TranslationUnit.from_source(path)93 94 r1 = create_range(tu, 1, 1, 2, 2)95 r2 = create_range(tu, 1, 2, 2, 2)96 r1_2 = create_range(tu, 1, 1, 2, 2)97 98 self.assertEqual(r1, r1)99 self.assertEqual(r1, r1_2)100 self.assertNotEqual(r1, r2)101 self.assertNotEqual(r1, "foo")102