| 1 | //===- unittest/Tooling/RewriterTest.cpp ----------------------------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "RewriterTestContext.h" |
| 10 | #include "clang/Tooling/Core/Replacement.h" |
| 11 | #include "gtest/gtest.h" |
| 12 | |
| 13 | namespace clang { |
| 14 | namespace tooling { |
| 15 | namespace { |
| 16 | |
| 17 | TEST(Rewriter, OverwritesChangedFiles) { |
| 18 | RewriterTestContext Context; |
| 19 | FileID ID = Context.createOnDiskFile(Name: "t.cpp" , Content: "line1\nline2\nline3\nline4" ); |
| 20 | Context.Rewrite.ReplaceText(Start: Context.getLocation(ID, Line: 2, Column: 1), OrigLength: 5, NewStr: "replaced" ); |
| 21 | EXPECT_FALSE(Context.Rewrite.overwriteChangedFiles()); |
| 22 | EXPECT_EQ("line1\nreplaced\nline3\nline4" , |
| 23 | Context.getFileContentFromDisk("t.cpp" )); |
| 24 | } |
| 25 | |
| 26 | TEST(Rewriter, ContinuesOverwritingFilesOnError) { |
| 27 | RewriterTestContext Context; |
| 28 | FileID FailingID = Context.createInMemoryFile(Name: "invalid/failing.cpp" , Content: "test" ); |
| 29 | Context.Rewrite.ReplaceText(Start: Context.getLocation(ID: FailingID, Line: 1, Column: 2), OrigLength: 1, NewStr: "other" ); |
| 30 | FileID WorkingID = Context.createOnDiskFile( |
| 31 | Name: "working.cpp" , Content: "line1\nline2\nline3\nline4" ); |
| 32 | Context.Rewrite.ReplaceText(Start: Context.getLocation(ID: WorkingID, Line: 2, Column: 1), OrigLength: 5, |
| 33 | NewStr: "replaced" ); |
| 34 | EXPECT_TRUE(Context.Rewrite.overwriteChangedFiles()); |
| 35 | EXPECT_EQ("line1\nreplaced\nline3\nline4" , |
| 36 | Context.getFileContentFromDisk("working.cpp" )); |
| 37 | } |
| 38 | |
| 39 | TEST(Rewriter, AdjacentInsertAndDelete) { |
| 40 | Replacements Replaces; |
| 41 | auto Err = Replaces.add(R: Replacement("<file>" , 6, 6, "" )); |
| 42 | EXPECT_TRUE(!Err); |
| 43 | Replaces = |
| 44 | Replaces.merge(Replaces: Replacements(Replacement("<file>" , 6, 0, "replaced\n" ))); |
| 45 | |
| 46 | auto Rewritten = applyAllReplacements(Code: "line1\nline2\nline3\nline4" , Replaces); |
| 47 | EXPECT_TRUE(static_cast<bool>(Rewritten)); |
| 48 | EXPECT_EQ("line1\nreplaced\nline3\nline4" , *Rewritten); |
| 49 | } |
| 50 | |
| 51 | } // end namespace |
| 52 | } // end namespace tooling |
| 53 | } // end namespace clang |
| 54 | |