file_test_base.h 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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 <mutex>
  10. #include "common/error.h"
  11. #include "common/ostream.h"
  12. #include "llvm/ADT/SmallString.h"
  13. #include "llvm/ADT/SmallVector.h"
  14. #include "llvm/ADT/StringMap.h"
  15. #include "llvm/ADT/StringRef.h"
  16. #include "llvm/Support/VirtualFileSystem.h"
  17. #include "testing/file_test/autoupdate.h"
  18. namespace Carbon::Testing {
  19. // A framework for testing files. See README.md for documentation.
  20. class FileTestBase : public testing::Test {
  21. public:
  22. struct TestFile {
  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 << ", \"" << FormatEscaped(f.content)
  27. << "\")";
  28. }
  29. std::string filename;
  30. std::string content;
  31. };
  32. // Provided for child class convenience.
  33. using LineNumberReplacement = FileTestAutoupdater::LineNumberReplacement;
  34. // The result of Run(), used to detect errors. Failing test files should be
  35. // named with a `fail_` prefix to indicate an expectation of failure.
  36. //
  37. // If per_file_success is empty:
  38. // - The main file has a `fail_` prefix if !success.
  39. // - The prefix of split files is unused.
  40. //
  41. // If per_file_success is non-empty:
  42. // - Each file has a `fail_` prefix if !per_file_success[i].second.
  43. // - Files may be in per_file_success that aren't part of the main test
  44. // file. This allows tracking success in handling files that are
  45. // well-known, such as standard libraries. It is still the responsibility
  46. // of callers to use a `fail_` prefix if !per_file_success[i].second.
  47. // - If any file has a `fail_` prefix, success must be false, and the prefix
  48. // of the main file is unused.
  49. // - If no file has a `fail_` prefix, the main file has a `fail_` prefix if
  50. // !success.
  51. struct RunResult {
  52. bool success;
  53. // Per-file success results. May be empty.
  54. llvm::SmallVector<std::pair<std::string, bool>> per_file_success;
  55. };
  56. explicit FileTestBase(std::mutex* output_mutex, llvm::StringRef test_name)
  57. : output_mutex_(output_mutex), test_name_(test_name) {}
  58. // Implemented by children to run the test. The framework will validate the
  59. // content written to `output_stream` and `error_stream`. Children should use
  60. // `fs` for file content, and may add more files.
  61. //
  62. // If there is a split test file named "STDIN", then its contents will be
  63. // provided at `input_stream` instead of `fs`. Otherwise, `input_stream` will
  64. // be null.
  65. //
  66. // Any test expectations should be called from ValidateRun, not Run.
  67. //
  68. // The return value should be an error if there was an abnormal error, and
  69. // RunResult otherwise.
  70. virtual auto Run(const llvm::SmallVector<llvm::StringRef>& test_args,
  71. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>& fs,
  72. FILE* input_stream, llvm::raw_pwrite_stream& output_stream,
  73. llvm::raw_pwrite_stream& error_stream)
  74. -> ErrorOr<RunResult> = 0;
  75. // Implemented by children to do post-Run test expectations. Only called when
  76. // testing. Does not need to be provided if only CHECK test expectations are
  77. // used.
  78. virtual auto ValidateRun() -> void {}
  79. // Returns default arguments. Only called when a file doesn't set ARGS.
  80. virtual auto GetDefaultArgs() -> llvm::SmallVector<std::string> = 0;
  81. // Returns a map of string replacements to implement `%{key}` -> `value` in
  82. // arguments.
  83. virtual auto GetArgReplacements() -> llvm::StringMap<std::string> {
  84. return {};
  85. }
  86. // Returns a regex to match the default file when a line may not be present.
  87. // May return nullptr if unused. If GetLineNumberReplacements returns an entry
  88. // with has_file=false, this is required.
  89. virtual auto GetDefaultFileRE(llvm::ArrayRef<llvm::StringRef> /*filenames*/)
  90. -> std::optional<RE2> {
  91. return std::nullopt;
  92. }
  93. // Returns replacement information for line numbers. See LineReplacement for
  94. // construction.
  95. virtual auto GetLineNumberReplacements(
  96. llvm::ArrayRef<llvm::StringRef> filenames)
  97. -> llvm::SmallVector<LineNumberReplacement>;
  98. // Optionally allows children to provide extra replacements for autoupdate.
  99. virtual auto DoExtraCheckReplacements(std::string& /*check_line*/) -> void {}
  100. // Whether to allow running the test in parallel, particularly for autoupdate.
  101. // This can be overridden to force some tests to be run serially. At any given
  102. // time, all parallel tests and a single non-parallel test will be allowed to
  103. // run.
  104. virtual auto AllowParallelRun() const -> bool { return true; }
  105. // Runs a test and compares output. This keeps output split by line so that
  106. // issues are a little easier to identify by the different line.
  107. auto TestBody() -> void final;
  108. // Runs the test and autoupdates checks. Returns true if updated.
  109. auto Autoupdate() -> ErrorOr<bool>;
  110. // Runs the test and dumps output.
  111. auto DumpOutput() -> ErrorOr<Success>;
  112. // Returns the name of the test (relative to the repo root).
  113. auto test_name() const -> llvm::StringRef { return test_name_; }
  114. private:
  115. // Encapsulates test context generated by processing and running.
  116. struct TestContext {
  117. // The input test file content. Other parts may reference this.
  118. std::string input_content;
  119. // Lines which don't contain CHECKs, and thus need to be retained by
  120. // autoupdate. Their file and line numbers are attached.
  121. //
  122. // If there are splits, then the splitting line is in the respective file.
  123. // For N splits, the 0th file is the parts of the input file which are not
  124. // in any split, plus one file per split file.
  125. llvm::SmallVector<FileTestLine> non_check_lines;
  126. // Whether there are splits.
  127. bool has_splits = false;
  128. // Arguments for the test, generated from ARGS.
  129. llvm::SmallVector<std::string> test_args;
  130. // Extra arguments for the test, generated from EXTRA-ARGS. Unlike ARGS,
  131. // setting EXTRA-ARGS does not suppress the default arguments.
  132. llvm::SmallVector<std::string> extra_args;
  133. // Files in the test, generated by content and splits.
  134. llvm::SmallVector<TestFile> test_files;
  135. // The location of the autoupdate marker, for autoupdated files.
  136. std::optional<int> autoupdate_line_number;
  137. // Whether there should be an AUTOUPDATE-SPLIT.
  138. bool autoupdate_split = false;
  139. // Whether to capture stderr and stdout that would head to console,
  140. // generated from SET-CAPTURE-CONSOLE-OUTPUT.
  141. bool capture_console_output = false;
  142. // Whether checks are a subset, generated from SET-CHECK-SUBSET.
  143. bool check_subset = false;
  144. // Whether `--dump_output` is specified, causing `Run` output to go to the
  145. // console. Output is typically captured for tests and autoupdate.
  146. bool dump_output = false;
  147. // stdout and stderr based on CHECK lines in the file.
  148. llvm::SmallVector<testing::Matcher<std::string>> expected_stdout;
  149. llvm::SmallVector<testing::Matcher<std::string>> expected_stderr;
  150. // stdout and stderr from Run. 16 is arbitrary but a required value.
  151. llvm::SmallString<16> actual_stdout;
  152. llvm::SmallString<16> actual_stderr;
  153. RunResult run_result = {.success = false};
  154. };
  155. // Processes the test file and runs the test. Returns an error if something
  156. // went wrong.
  157. auto ProcessTestFileAndRun(TestContext& context) -> ErrorOr<Success>;
  158. // Does replacements in ARGS for %s and %t.
  159. auto DoArgReplacements(llvm::SmallVector<std::string>& test_args,
  160. const llvm::SmallVector<TestFile>& test_files)
  161. -> ErrorOr<Success>;
  162. // Processes the test input, producing test files and expected output.
  163. auto ProcessTestFile(TestContext& context) -> ErrorOr<Success>;
  164. // Runs the FileTestAutoupdater, returning the result.
  165. auto RunAutoupdater(const TestContext& context, bool dry_run) -> bool;
  166. // An optional mutex for output. If provided, it will be locked during `Run`
  167. // when stderr/stdout are being captured (SET-CAPTURE-CONSOLE-OUTPUT), in
  168. // order to avoid output conflicts.
  169. std::mutex* output_mutex_;
  170. llvm::StringRef test_name_;
  171. };
  172. // Aggregate a name and factory function for tests using this framework.
  173. struct FileTestFactory {
  174. // The test fixture name.
  175. const char* name;
  176. // A factory function for tests. The output_mutex is optional; see
  177. // `FileTestBase::output_mutex_`.
  178. std::function<FileTestBase*(llvm::StringRef exe_path,
  179. std::mutex* output_mutex,
  180. llvm::StringRef test_name)>
  181. factory_fn;
  182. };
  183. // Must be implemented by the individual file_test to initialize tests.
  184. //
  185. // We can't use INSTANTIATE_TEST_CASE_P because of ordering issues between
  186. // container initialization and test instantiation by InitGoogleTest, but this
  187. // also allows us more flexibility in execution.
  188. //
  189. // The `CARBON_FILE_TEST_FACTOR` macro below provides a standard, convenient way
  190. // to implement this function.
  191. extern auto GetFileTestFactory() -> FileTestFactory;
  192. // Provides a standard GetFileTestFactory implementation.
  193. #define CARBON_FILE_TEST_FACTORY(Name) \
  194. auto GetFileTestFactory() -> FileTestFactory { \
  195. return {#Name, [](llvm::StringRef exe_path, std::mutex* output_mutex, \
  196. llvm::StringRef test_name) { \
  197. return new Name(exe_path, output_mutex, test_name); \
  198. }}; \
  199. }
  200. } // namespace Carbon::Testing
  201. #endif // CARBON_TESTING_FILE_TEST_FILE_TEST_BASE_H_