file_test_base.h 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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_TESTING_FILE_TEST_FILE_TEST_BASE_H_
  5. #define CARBON_TESTING_FILE_TEST_FILE_TEST_BASE_H_
  6. #include <gmock/gmock.h>
  7. #include <gtest/gtest.h>
  8. #include <functional>
  9. #include "common/error.h"
  10. #include "common/ostream.h"
  11. #include "llvm/ADT/SmallString.h"
  12. #include "llvm/ADT/SmallVector.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/Support/VirtualFileSystem.h"
  15. #include "testing/file_test/autoupdate.h"
  16. namespace Carbon::Testing {
  17. // A framework for testing files. See README.md for documentation.
  18. class FileTestBase : public testing::Test {
  19. public:
  20. struct TestFile {
  21. explicit TestFile(std::string filename, llvm::StringRef content)
  22. : filename(std::move(filename)), content(content) {}
  23. friend void PrintTo(const TestFile& f, std::ostream* os) {
  24. // Print content escaped.
  25. llvm::raw_os_ostream os_wrap(*os);
  26. os_wrap << "TestFile(" << f.filename << ", \"";
  27. os_wrap.write_escaped(f.content);
  28. os_wrap << "\")";
  29. }
  30. std::string filename;
  31. llvm::StringRef content;
  32. };
  33. // Provided for child class convenience.
  34. using LineNumberReplacement = FileTestAutoupdater::LineNumberReplacement;
  35. explicit FileTestBase(llvm::StringRef test_name) : test_name_(test_name) {}
  36. // Implemented by children to run the test. For example, TestBody validates
  37. // stdout and stderr. Children should use fs for file content, and may add
  38. // more files.
  39. //
  40. // Any test expectations should be called from ValidateRun, not Run.
  41. //
  42. // The return value should be an error if there was an abnormal error. It
  43. // should be true if a binary would return EXIT_SUCCESS, and false for
  44. // EXIT_FAILURE (which is a test success for `fail_*` tests).
  45. virtual auto Run(const llvm::SmallVector<llvm::StringRef>& test_args,
  46. llvm::vfs::InMemoryFileSystem& fs,
  47. llvm::raw_pwrite_stream& stdout,
  48. llvm::raw_pwrite_stream& stderr) -> ErrorOr<bool> = 0;
  49. // Implemented by children to do post-Run test expectations. Only called when
  50. // testing. Does not need to be provided if only CHECK test expectations are
  51. // used.
  52. virtual auto ValidateRun() -> void {}
  53. // Returns default arguments. Only called when a file doesn't set ARGS.
  54. virtual auto GetDefaultArgs() -> llvm::SmallVector<std::string> = 0;
  55. // Returns a regex to match the default file when a line may not be present.
  56. // May return nullptr if unused. If GetLineNumberReplacements returns an entry
  57. // with has_file=false, this is required.
  58. virtual auto GetDefaultFileRE(llvm::ArrayRef<llvm::StringRef> /*filenames*/)
  59. -> std::optional<RE2> {
  60. return std::nullopt;
  61. }
  62. // Returns replacement information for line numbers. See LineReplacement for
  63. // construction.
  64. virtual auto GetLineNumberReplacements(
  65. llvm::ArrayRef<llvm::StringRef> filenames)
  66. -> llvm::SmallVector<LineNumberReplacement>;
  67. // Optionally allows children to provide extra replacements for autoupdate.
  68. virtual auto DoExtraCheckReplacements(std::string& /*check_line*/) -> void {}
  69. // Runs a test and compares output. This keeps output split by line so that
  70. // issues are a little easier to identify by the different line.
  71. auto TestBody() -> void final;
  72. // Runs the test and autoupdates checks. Returns true if updated.
  73. auto Autoupdate() -> ErrorOr<bool>;
  74. // Returns the name of the test (relative to the repo root).
  75. auto test_name() const -> llvm::StringRef { return test_name_; }
  76. private:
  77. // Encapsulates test context generated by processing and running.
  78. struct TestContext {
  79. // The input test file content. Other parts may reference this.
  80. std::string input_content;
  81. // Lines which don't contain CHECKs, and thus need to be retained by
  82. // autoupdate. Their file and line numbers are attached.
  83. //
  84. // If there are splits, then the splitting line is in the respective file.
  85. // For N splits, the 0th file is the parts of the input file which are not
  86. // in any split, plus one file per split file.
  87. llvm::SmallVector<FileTestLine> non_check_lines;
  88. // Whether there are splits.
  89. bool has_splits = false;
  90. // Arguments for the test, generated from ARGS.
  91. llvm::SmallVector<std::string> test_args;
  92. // Files in the test, generated by content and splits.
  93. llvm::SmallVector<TestFile> test_files;
  94. // The location of the autoupdate marker, for autoupdated files.
  95. std::optional<int> autoupdate_line_number;
  96. // Whether checks are a subset, generated from SET-CHECK-SUBSET.
  97. bool check_subset = false;
  98. // stdout and stderr based on CHECK lines in the file.
  99. llvm::SmallVector<testing::Matcher<std::string>> expected_stdout;
  100. llvm::SmallVector<testing::Matcher<std::string>> expected_stderr;
  101. // stdout and stderr from Run. 16 is arbitrary but a required value.
  102. llvm::SmallString<16> stdout;
  103. llvm::SmallString<16> stderr;
  104. // Whether Run exited with success.
  105. bool exit_with_success = false;
  106. };
  107. // Processes the test file and runs the test. Returns an error if something
  108. // went wrong.
  109. auto ProcessTestFileAndRun(TestContext& context) -> ErrorOr<Success>;
  110. // Does replacements in ARGS for %s and %t.
  111. auto DoArgReplacements(llvm::SmallVector<std::string>& test_args,
  112. const llvm::SmallVector<TestFile>& test_files)
  113. -> ErrorOr<Success>;
  114. // Processes the test input, producing test files and expected output.
  115. auto ProcessTestFile(TestContext& context) -> ErrorOr<Success>;
  116. // Transforms an expectation on a given line from `FileCheck` syntax into a
  117. // standard regex matcher.
  118. static auto TransformExpectation(int line_index, llvm::StringRef in)
  119. -> ErrorOr<testing::Matcher<std::string>>;
  120. // Runs the FileTestAutoupdater, returning the result.
  121. auto RunAutoupdater(const TestContext& context, bool dry_run) -> bool;
  122. llvm::StringRef test_name_;
  123. };
  124. // Aggregate a name and factory function for tests using this framework.
  125. struct FileTestFactory {
  126. // The test fixture name.
  127. const char* name;
  128. // A factory function for tests.
  129. std::function<FileTestBase*(llvm::StringRef path)> factory_fn;
  130. };
  131. // Must be implemented by the individual file_test to initialize tests.
  132. //
  133. // We can't use INSTANTIATE_TEST_CASE_P because of ordering issues between
  134. // container initialization and test instantiation by InitGoogleTest, but this
  135. // also allows us more flexibility in execution.
  136. //
  137. // The `CARBON_FILE_TEST_FACTOR` macro below provides a standard, convenient way
  138. // to implement this function.
  139. extern auto GetFileTestFactory() -> FileTestFactory;
  140. // Provides a standard GetFileTestFactory implementation.
  141. #define CARBON_FILE_TEST_FACTORY(Name) \
  142. auto GetFileTestFactory()->FileTestFactory { \
  143. return {#Name, [](llvm::StringRef path) { return new Name(path); }}; \
  144. }
  145. } // namespace Carbon::Testing
  146. #endif // CARBON_TESTING_FILE_TEST_FILE_TEST_BASE_H_