66 lines · python
1import tempfile2import unittest3 4from clang.cindex import File, Rewriter, SourceLocation, SourceRange, TranslationUnit5 6 7class TestRewrite(unittest.TestCase):8 code = """int main() { return 0; }"""9 10 def setUp(self):11 self.tmp = tempfile.NamedTemporaryFile(suffix=".cpp", buffering=0)12 self.tmp.write(TestRewrite.code.encode("utf-8"))13 self.tmp.flush()14 self.tu = TranslationUnit.from_source(self.tmp.name)15 self.rew = Rewriter.create(self.tu)16 self.file = File.from_name(self.tu, self.tmp.name)17 18 def tearDown(self):19 self.tmp.close()20 21 def get_content(self) -> str:22 with open(self.tmp.name, "r", encoding="utf-8") as f:23 return f.read()24 25 def test_replace(self):26 rng = SourceRange.from_locations(27 SourceLocation.from_position(self.tu, self.file, 1, 5),28 SourceLocation.from_position(self.tu, self.file, 1, 9),29 )30 self.rew.replace_text(rng, "MAIN")31 self.rew.overwrite_changed_files()32 self.assertEqual(self.get_content(), "int MAIN() { return 0; }")33 34 def test_replace_shorter(self):35 rng = SourceRange.from_locations(36 SourceLocation.from_position(self.tu, self.file, 1, 5),37 SourceLocation.from_position(self.tu, self.file, 1, 9),38 )39 self.rew.replace_text(rng, "foo")40 self.rew.overwrite_changed_files()41 self.assertEqual(self.get_content(), "int foo() { return 0; }")42 43 def test_replace_longer(self):44 rng = SourceRange.from_locations(45 SourceLocation.from_position(self.tu, self.file, 1, 5),46 SourceLocation.from_position(self.tu, self.file, 1, 9),47 )48 self.rew.replace_text(rng, "patatino")49 self.rew.overwrite_changed_files()50 self.assertEqual(self.get_content(), "int patatino() { return 0; }")51 52 def test_insert(self):53 pos = SourceLocation.from_position(self.tu, self.file, 1, 5)54 self.rew.insert_text_before(pos, "ro")55 self.rew.overwrite_changed_files()56 self.assertEqual(self.get_content(), "int romain() { return 0; }")57 58 def test_remove(self):59 rng = SourceRange.from_locations(60 SourceLocation.from_position(self.tu, self.file, 1, 5),61 SourceLocation.from_position(self.tu, self.file, 1, 9),62 )63 self.rew.remove_text(rng)64 self.rew.overwrite_changed_files()65 self.assertEqual(self.get_content(), "int () { return 0; }")66