file_test_base.h 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. friend void PrintTo(const TestFile& f, std::ostream* os) {
  22. // Print content escaped.
  23. llvm::raw_os_ostream os_wrap(*os);
  24. os_wrap << "TestFile(" << f.filename << ", \"";
  25. os_wrap.write_escaped(f.content);
  26. os_wrap << "\")";
  27. }
  28. std::string filename;
  29. std::string content;
  30. };
  31. // Provided for child class convenience.
  32. using LineNumberReplacement = FileTestAutoupdater::LineNumberReplacement;
  33. // The result of Run(), used to detect errors. Failing test files should be
  34. // named with a `fail_` prefix to indicate an expectation of failure.
  35. //
  36. // If per_file_success is empty:
  37. // - The main file has a `fail_` prefix if !success.
  38. // - The prefix of split files is unused.
  39. //
  40. // If per_file_success is non-empty:
  41. // - Each file has a `fail_` prefix if !per_file_success[i].second.
  42. // - Files may be in per_file_success that aren't part of the main test
  43. // file. This allows tracking success in handling files that are
  44. // well-known, such as standard libraries. It is still the responsibility
  45. // of callers to use a `fail_` prefix if !per_file_success[i].second.
  46. // - If any file has a `fail_` prefix, success must be false, and the prefix
  47. // of the main file is unused.
  48. // - If no file has a `fail_` prefix, the main file has a `fail_` prefix if
  49. // !success.
  50. struct RunResult {
  51. bool success;
  52. // Per-file success results. May be empty.
  53. llvm::SmallVector<std::pair<std::string, bool>> per_file_success;
  54. };
  55. explicit FileTestBase(llvm::StringRef test_name) : test_name_(test_name) {}
  56. // Implemented by children to run the test. For example, TestBody validates
  57. // stdout and stderr. Children should use fs for file content, and may add
  58. // more files.
  59. //
  60. // Any test expectations should be called from ValidateRun, not Run.
  61. //
  62. // The return value should be an error if there was an abnormal error, and
  63. // RunResult otherwise.
  64. virtual auto Run(const llvm::SmallVector<llvm::StringRef>& test_args,
  65. llvm::vfs::InMemoryFileSystem& fs,
  66. llvm::raw_pwrite_stream& stdout,
  67. llvm::raw_pwrite_stream& stderr) -> ErrorOr<RunResult> = 0;
  68. // Implemented by children to do post-Run test expectations. Only called when
  69. // testing. Does not need to be provided if only CHECK test expectations are
  70. // used.
  71. virtual auto ValidateRun() -> void {}
  72. // Returns default arguments. Only called when a file doesn't set ARGS.
  73. virtual auto GetDefaultArgs() -> llvm::SmallVector<std::string> = 0;
  74. // Returns a regex to match the default file when a line may not be present.
  75. // May return nullptr if unused. If GetLineNumberReplacements returns an entry
  76. // with has_file=false, this is required.
  77. virtual auto GetDefaultFileRE(llvm::ArrayRef<llvm::StringRef> /*filenames*/)
  78. -> std::optional<RE2> {
  79. return std::nullopt;
  80. }
  81. // Returns replacement information for line numbers. See LineReplacement for
  82. // construction.
  83. virtual auto GetLineNumberReplacements(
  84. llvm::ArrayRef<llvm::StringRef> filenames)
  85. -> llvm::SmallVector<LineNumberReplacement>;
  86. // Optionally allows children to provide extra replacements for autoupdate.
  87. virtual auto DoExtraCheckReplacements(std::string& /*check_line*/) -> void {}
  88. // Runs a test and compares output. This keeps output split by line so that
  89. // issues are a little easier to identify by the different line.
  90. auto TestBody() -> void final;
  91. // Runs the test and autoupdates checks. Returns true if updated.
  92. auto Autoupdate() -> ErrorOr<bool>;
  93. // Runs the test and dumps output.
  94. auto DumpOutput() -> ErrorOr<Success>;
  95. // Returns the name of the test (relative to the repo root).
  96. auto test_name() const -> llvm::StringRef { return test_name_; }
  97. private:
  98. // Encapsulates test context generated by processing and running.
  99. struct TestContext {
  100. // The input test file content. Other parts may reference this.
  101. std::string input_content;
  102. // Lines which don't contain CHECKs, and thus need to be retained by
  103. // autoupdate. Their file and line numbers are attached.
  104. //
  105. // If there are splits, then the splitting line is in the respective file.
  106. // For N splits, the 0th file is the parts of the input file which are not
  107. // in any split, plus one file per split file.
  108. llvm::SmallVector<FileTestLine> non_check_lines;
  109. // Whether there are splits.
  110. bool has_splits = false;
  111. // Arguments for the test, generated from ARGS.
  112. llvm::SmallVector<std::string> test_args;
  113. // Files in the test, generated by content and splits.
  114. llvm::SmallVector<TestFile> test_files;
  115. // The location of the autoupdate marker, for autoupdated files.
  116. std::optional<int> autoupdate_line_number;
  117. // Whether checks are a subset, generated from SET-CHECK-SUBSET.
  118. bool check_subset = false;
  119. // Output is typically captured for tests and autoupdate, but not when
  120. // dumping to console.
  121. bool capture_output = true;
  122. // stdout and stderr based on CHECK lines in the file.
  123. llvm::SmallVector<testing::Matcher<std::string>> expected_stdout;
  124. llvm::SmallVector<testing::Matcher<std::string>> expected_stderr;
  125. // stdout and stderr from Run. 16 is arbitrary but a required value.
  126. llvm::SmallString<16> stdout;
  127. llvm::SmallString<16> stderr;
  128. RunResult run_result = {.success = false};
  129. };
  130. // Processes the test file and runs the test. Returns an error if something
  131. // went wrong.
  132. auto ProcessTestFileAndRun(TestContext& context) -> ErrorOr<Success>;
  133. // Does replacements in ARGS for %s and %t.
  134. auto DoArgReplacements(llvm::SmallVector<std::string>& test_args,
  135. const llvm::SmallVector<TestFile>& test_files)
  136. -> ErrorOr<Success>;
  137. // Processes the test input, producing test files and expected output.
  138. auto ProcessTestFile(TestContext& context) -> ErrorOr<Success>;
  139. // Runs the FileTestAutoupdater, returning the result.
  140. auto RunAutoupdater(const TestContext& context, bool dry_run) -> bool;
  141. llvm::StringRef test_name_;
  142. };
  143. // Aggregate a name and factory function for tests using this framework.
  144. struct FileTestFactory {
  145. // The test fixture name.
  146. const char* name;
  147. // A factory function for tests.
  148. std::function<FileTestBase*(llvm::StringRef exe_path,
  149. llvm::StringRef test_name)>
  150. factory_fn;
  151. };
  152. // Must be implemented by the individual file_test to initialize tests.
  153. //
  154. // We can't use INSTANTIATE_TEST_CASE_P because of ordering issues between
  155. // container initialization and test instantiation by InitGoogleTest, but this
  156. // also allows us more flexibility in execution.
  157. //
  158. // The `CARBON_FILE_TEST_FACTOR` macro below provides a standard, convenient way
  159. // to implement this function.
  160. extern auto GetFileTestFactory() -> FileTestFactory;
  161. // Provides a standard GetFileTestFactory implementation.
  162. #define CARBON_FILE_TEST_FACTORY(Name) \
  163. auto GetFileTestFactory() -> FileTestFactory { \
  164. return {#Name, [](llvm::StringRef exe_path, llvm::StringRef test_name) { \
  165. return new Name(exe_path, test_name); \
  166. }}; \
  167. }
  168. } // namespace Carbon::Testing
  169. #endif // CARBON_TESTING_FILE_TEST_FILE_TEST_BASE_H_