matcher_test_base.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_MIGRATE_CPP_CPP_REFACTORING_MATCHER_TEST_BASE_H_
  5. #define CARBON_MIGRATE_CPP_CPP_REFACTORING_MATCHER_TEST_BASE_H_
  6. #include <gmock/gmock.h>
  7. #include <gtest/gtest.h>
  8. #include "clang/ASTMatchers/ASTMatchFinder.h"
  9. #include "clang/Tooling/Core/Replacement.h"
  10. #include "clang/Tooling/Tooling.h"
  11. #include "migrate_cpp/cpp_refactoring/matcher_manager.h"
  12. namespace Carbon::Testing {
  13. // Matcher test framework.
  14. template <typename MatcherFactoryType>
  15. class MatcherTestBase : public ::testing::Test {
  16. protected:
  17. MatcherTestBase() : matchers_(&replacements_) {
  18. matchers_.Register(std::make_unique<MatcherFactoryType>());
  19. }
  20. // Expects that the replacements produced by running the finder result in
  21. // the specified code transformation.
  22. void ExpectReplacement(llvm::StringRef before, llvm::StringRef after) {
  23. auto factory =
  24. clang::tooling::newFrontendActionFactory(matchers_.GetFinder());
  25. constexpr char Filename[] = "test.cc";
  26. replacements_.clear();
  27. replacements_.insert({Filename, {}});
  28. ASSERT_TRUE(clang::tooling::runToolOnCodeWithArgs(
  29. factory->create(), before, {}, Filename, "clang-tool",
  30. std::make_shared<clang::PCHContainerOperations>(),
  31. clang::tooling::FileContentMappings()));
  32. EXPECT_THAT(replacements_, testing::ElementsAre(testing::Key(Filename)));
  33. llvm::Expected<std::string> actual =
  34. clang::tooling::applyAllReplacements(before, replacements_[Filename]);
  35. // Make a specific note if the matcher didn't make any changes.
  36. std::string unchanged;
  37. if (before == *actual) {
  38. unchanged = "NOTE: Actual matches original text, no changes made.";
  39. }
  40. if (after.find('\n') == std::string::npos) {
  41. EXPECT_THAT(*actual, testing::Eq(after.str())) << unchanged;
  42. } else {
  43. // Split lines to get gmock to get an easier-to-read error.
  44. llvm::SmallVector<llvm::StringRef, 0> actual_lines;
  45. llvm::SplitString(*actual, actual_lines, "\n");
  46. llvm::SmallVector<llvm::StringRef, 0> after_lines;
  47. llvm::SplitString(after, after_lines, "\n");
  48. EXPECT_THAT(actual_lines, testing::ContainerEq(after_lines)) << unchanged;
  49. }
  50. }
  51. private:
  52. Matcher::ReplacementMap replacements_;
  53. MatcherManager matchers_;
  54. };
  55. } // namespace Carbon::Testing
  56. #endif // CARBON_MIGRATE_CPP_CPP_REFACTORING_MATCHER_TEST_BASE_H_